#discord-bots
1 messages · Page 588 of 1
disnake, discord.js ¯\_(ツ)_/¯
yes just friend me and call but be in mute and share screen @boreal ravine
but im on mobile
thx
what
help plss
i am also mobile
bot unban but dont send embed
dadasiduhjadas
await ctx.send(f"Gracz {discord.Object(arg).name} Został odbanowany przez {ctx.author.name}.")
``` that
dude i am also mobile @boreal ravine
🗿
?
well u didnt have an embed
cant, just watch a tutorial
anyone got anytutorials on discord dictionary bots
yes but dont send it
@boreal ravine thanks bro
what i gave up trying to read documentation
!resources learn how to index dicts pls 🙏 😔
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
or just google "how to index dicts"
Is this correct way? ```py
@edit.command()
async def msg(self, ctx, message: discord.Message, *, content: str = None):
msgs = await self.bot.fetch_message(message)
msgs.edit(content)
@boreal ravine bot dont do it, but unban
correct way of what
yes
to edit message *
@boreal ravine
thx
!pypi disnake
try the command u did but add a ==2.21 at thee end @tame marsh
but now ikeep getting the same outpur
!d discord.TextChannel.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") from the destination.
yes thats right
index it more
thx
use parameters
ok
am I supposed to give a channel in there?
ERROR: Could not find a version that satisfies the requirement disnake==2.21 (from versions: none)
2.2.1 oops
ERROR: Could not find a version that satisfies the requirement disnake==2.2.1 (from versions: none) still
discord.TextChannel is replaced with an instance of it
mm did u install disnake?
thats waht im doing
.
querystring = {"term":"wat"}
response = requests.request("GET", url, headers=headers, params=querystring)```
my params=querystring
i didnt mean that
I mean this
def define(word): #word is a param
...
define("kayle")
I'm not a professional
but I'm certain
that you could use aiohttp instead of requests
cuz everyone says that so I'll say that too
mhm
but all my code is requests
what is "wat"
A word.
This gave me a error: https://paste.pythondiscord.com/fobenuyuku.sql ```py
@edit.command()
async def msg(self, ctx, message: discord.Message, channel: typing.Optional[discord.TextChannel] = None, *, content: str = None):
if content is None:
await ctx.send("Message content is not provided")
if channel is None:
channel = ctx.channel
msgs = await channel.fetch_message(message)
msgs.edit(content)
hm
add a content kwarg
.edit(content=content)
hm
@boreal ravine whats the name of the argument for an message id image
in a slash command
message id image?
parameters
like normal functions
in this wat is the term
yeah
how to i change that to useinput
params
Parameters vs. Arguments
A parameter is a variable defined in a function signature (the line with def in it), while arguments are objects passed to a function call.
def square(n): # n is the parameter
return n*n
print(square(5)) # 5 is the argument
Note that 5 is the argument passed to square, but square(5) in its entirety is the argument passed to print
please learn functions before using discord.py
!params
Parameters vs. Arguments
A parameter is a variable defined in a function signature (the line with def in it), while arguments are objects passed to a function call.
def square(n): # n is the parameter
return n*n
print(square(5)) # 5 is the argument
Note that 5 is the argument passed to square, but square(5) in its entirety is the argument passed to print
#bot-commands
nope. did not work
hm
Jesus Christ dude ints don’t have an attribute called name. If you want it to display there name. Fetch the member
Does anyone know if it’s possible to create custom embeds in discord with tkinter or do I have to create a whole GUI like Mee6 / Carlbot for e.G to get this done? Atm I have to write the embed in my script itself but moderators can‘t do that
Get the id of an image uploaded by an user
no…..
And this as an argument in a slash command
So i need a GUI ? Well this is kind of complex, right? 🥲
What are your intentions again?
You want to make a custom embed thing?
You can’t even do that. You only have what discord gives you.
Yes but you can give a template, the moderator will just have to fill in the text or img he wants
Are u trying to do custom embeds online thru site?
Oh I know what you mean now
I first wanted to ask if this is the only way or is there a way to „customize“ directly through discord?
I mean you can like build the embed one step at a time
If that’s what you mean
And give out the finished product once you’re done building
My friend has a command for custom cmds.. he does it using an embed builder and then converting to JSON
https://embedbuilder.nadekobot.me/
Idk how to make it tho
Exactly what I said earlier
The problem with this is, only I will be able to add this code to the bot
Not my staff
Are you trying to create a command like:
!createembed <embedtitle>.. etc
No.. u can listen to the msg sent by staff to make the embed.. if it's not in json throw an error msg @twilit scarab
This would be a good way if it’s possible
I mean that’s not hard then
is your bot defined as client or bot? I can make some simple code for that
This gave me a error: https://paste.pythondiscord.com/fobenuyuku.sql ```py
@edit.command()
async def msg(self, ctx, message: discord.Message, channel: typing.Optional[discord.TextChannel] = None, *, content: str = None):
if content is None:
await ctx.send("Message content is not provided")
if channel is None:
channel = ctx.channel
msgs = await channel.fetch_message(message)
msgs.edit(content)
what type of error?
It’s possible
As Client, would appreciate that 🙏 script is in python
@client.command()
async def embed(ctx, title, description):
embed = discord.Embed(
title = title,
description = description,
colour = discord.Colour.from_rgb(red, green, blue) # you can edit these yourself or get inputs for it
)
await ctx.send(embed=embed)
can u show me how u invoked the command?
He said it’s Client.
just capitalise the C then
i did !edit msg <some message id> Hello
That not what I mean
discord.Client?
discord.Client
Ah
.command() isn’t applicable
your supposed to do !edit msg msgid channelid content
I tried that as well
Wait a sec I can send a code of my self made embeds seems very similar
i don't think you can have another param if you set one to None
what was the error?
you can
🤧
Yep did not work
@client.command()
async def displayembed(ctx):
embed = discord.Embed(
title = 'Title',
desciption = 'Das ist eine Beschreibung',
colour = discord.Colour.blue())
embed.set_footer(text='Das ist die Fußzeile')
embed.set_image(url='https://th.bing.com/th/id/R.62a4c8c1e6c7c1d5bf82f6a4045b9eef?rik=4lMjn%2bzGk5IaHQ&riu=http%3a%2f%2fcdn.onlinewebfonts.com%2fsvg%2fimg_2382.png&ehk=iXWYrW4JB4Ccu6%2fybCCde3JhkK9rBCktSurZ5dEzUVs%3d&risl=&pid=ImgRaw&r=0')
embed.set_thumbnail(url='https://apis.mail.aol.com/ws/v3/mailboxes/@.id==VjN-Zbt3c8-N7kOxm6T1YDJHrc92A3z36kOm-0-_CS-m8DoM6JCVFZntKKrwX6KKwGaBo7_qQ9o-6a8oIA8hEkZ7zw/messages/@.id==AC5734sGxdJAYW1pVwSIKFySmYM/content/parts/@.id==3/thumbnail?appid=aolwebmail&size=400w')
embed.set_author(name='Autor Name',
icon_url='https://apis.mail.aol.com/ws/v3/mailboxes/@.id==VjN-Zbt3c8-N7kOxm6T1YDJHrc92A3z36kOm-0-_CS-m8DoM6JCVFZntKKrwX6KKwGaBo7_qQ9o-6a8oIA8hEkZ7zw/messages/@.id==AC5734sGxdJAYW1pVwSIKFySmYM/content/parts/@.id==2/thumbnail?appid=aolwebmail&size=400w')
embed.add_field(name='Feld Name', value='Feld Anzahl', inline=False)
embed.add_field(name='Feld Name', value='Feld Anzahl', inline=True)
embed.add_field(name='Feld Name', value='Feld Anzahl', inline=False)
await ctx.send(embed=embed)
Lol don’t look at the format, im on mobile rn
Why
same error?
It’s working, but how can the moderator customize this himself just with a command?
parameters
Displayembed(Ctx, title, description, embed_field) and so on?
!e
def embed(title, desc):
print(f"Title: {title}\nDescription: {desc}")
print(embed(title="Hi", desc="Yes"))
``` something like this Ig
@boreal ravine :white_check_mark: Your eval job has completed with return code 0.
001 | Title: Hi
002 | Description: Yes
003 | None
Okay nice, I’ll play around with that later. Now I know where to start. Thank you!!! 🙏🙏🙏
well idrk you must've done something wrong in the args/params
i did it lol
nice
how do i tell the user about error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range
like this
!d discord.ext.commands.Bot.on_command_error
await on_command_error(context, exception)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default command error handler provided by the bot.
By default this prints to [`sys.stderr`](https://docs.python.org/3/library/sys.html#sys.stderr "(in Python v3.9)") however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
I don't know what is wrong in there
me either I cant try ur code since im not on pc
you wrote 'description' wrong
thx anyways, I will try to find smth
👍
because youre passing a message object to fetch
discord.Message typehint already converts it to a message object
Oh...
entry = {
'title': f'Top {limit} Osu scores for {member.display_name}',
'fields': [
{'name': 'Artist', 'value': m.artist},
{'name': 'Title', 'value': m.title},
{'name': 'Creator', 'value': m.creator},
{'name': 'CS (Circle Size)', 'value': m.diff_size},
{'name': 'AR (Approach Rate)', 'value': m.diff_approach},
{'name': 'HP (Health Drain)', 'value': m.diff_drain},
{'name': 'OD (Overall Difficulty)', 'value': m.diff_overall},
{'name': 'Length', 'value': m.total_length},
{'name': 'Score', 'value': i.score},
{'name': 'Max Combo', 'value': i.maxcombo},
{'name': 'Hits', 'value': f"{i.count300}/{i.count100}/{i.count50}/{i.countmiss} (300/100/50/misses)", "inline": False},
{'name': 'Perfect', 'value': "Yes" if i.perfect else "No"},
{'name': 'Rank', 'value': i.rank},
{'name': 'PP', 'value': i.pp},
{'name': 'Mods', 'value': str(i.enabled_mods)},
{'name': 'Date', 'value': str(i.date)}
]
}
entries.append(entry)
messages = []
for entry in entries:
messages.append(entry)
await ctx.send("\n".join(messages))
```This be a smol osu command m trying and i cant get entry thing to be sent as one message...and could someone help me wid dat and adding these values to multiple embeds....like when they run `!osu scores 2` it gives 2 embeds which i can later put it up as paginator thingy
I was creating a command a clear, and it works, in addition I wanted the bot to send a message: "I have deleted the messages." i tried to do it with delete_after = 5 but it doesn't work. Can someone help me?
await ctx.reply(f"I have deleted the messages.", delete_after = 5)
```ctx.reply or send according to what u want
i am using it in an embed, it doesn't work
send an ss mayb
ss?
screenshot*
define it doesnt work
it has no errors when the command is executed
delete_after=5,colour=discord.Colour.green())
await ctx.send(embed=embed)
``` this is the code
embed = discord.Embed(description=f" Deleted.."colour=discord.Colour.green())
await ctx.send(embed=embed, delete_after = 5)
``` try this
wait
@river kindle this this
peashe
Does anyone know how to have the bot send animated emotes in separate lines? My attempt at it wasn't very good :
Edit : Nevermind, figured it out.
!ot please
Off-topic channels
There are three off-topic channels:
• #ot0-psvm’s-eternal-disapproval
• #ot1-perplexing-regexing
• #ot2-never-nester’s-nightmare
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Please read our off-topic etiquette before participating in conversations.
\n
hey @boreal ravine pls click on the link which i send
pls
no
there's a quiz abt me
no
why
Yeah I just figured it out... turns out I had `` in some poor places.
Stop bullying people into clicking your link
👍
Now that I fixed it, it works!
<@&831776746206265384> #discord-bots message
Why is this here?
feels like some virus ngl
Defcon + tempmute command I guess
its a link where you have to answer abt me and i'll see how knows me best!
@tawdry perch
that is strictly off topic @ebon plank and advertising is not allowed unless approved
You actually wont
you ending your sentences with "!" is what's making it 100x more sus
yo not everything
sus , alt?
yes,i am new to discord
Nothing that is really that special
if bugs were features , many
Bugs are features
is this wrong?
role = discord.utils.get(ctx.author.guild.roles, id=905084755400335370)
await ctx.author.add_roles(role)
``` when the bot gets to this part of the command it results in a CommandInvokeError... why?
just use ctx.guild.roles
i though it was supported
.
.
what do i do then
I was asking that as question?
because it soed say that theya re supported
oh
use another python version
cant
why
it needs to meet discrod.py requirements
Discord.py supports 3.8+, not only 3.8.9.
pp
Source?
You need to install the packages again.
does it work on 3.10.0
Well, it works with 3.5.3 and higher. So I guess the answer is obvious.
is 3.10 higher than 3.5.3? 😳
and 3.10.0 does not have any critical changes so it should work
git says 3.8 -> https://github.com/Rapptz/discord.py
reload vsc
you are not using it anywhere yet (may be a problem)
wdym
Might have changed, but still 3.10 is higher than 3.8.
No.
reload vsc
for me it is sometimes
This error means that the package is not installed. Though, it's a known visual issue with VSC.
ye
oh
that's why we reload after installing pkg
Then I have mistaken it to another error, my bad
There's no error when you don't use a package.
wdym
how do i change it
py -3.10
Kai's here, I'm gonna just watch now. 
where
help him igtg
Your doing fine, we're vouching 
?
make new app in heroku delete the current one
i did lol
same error??
do that mate it console
i am also using vsc rn i know from bottom line u r sending
if member.premium_type == discord.PremiumType.nitro_class:, is this not valid?
same with if member.premium_type == discord.PremiumType.nitro:
give the same error
@mild token
so how do i change
show code
ok
help pls lol
just doing py should give all the info.
u need to configure your environment variable
i recommend to uninstall all other py version and keep only 1
only when i do python3 --version it shows 3.10.0
how to do that
whats the command
how u r your script
wdym
oo u r on mac i forgot 😂
how u run your code??
play button thing
if member.premium_type == discord.PremiumType.nitro_class:, is this not valid?
same with if member.premium_type == discord.PremiumType.nitro:
use python3 yourfilename.py
@bot.command(name='captcha')
async def verify(ctx):
member = ctx.author.name
user = ctx.author
randomstr = (''.join(
random.choice(string.ascii_uppercase + string.digits)
for _ in range(7)))
randomvar = str(randomstr)
confirm = discord.Embed(
title='text here ' + ctx.author.name,
description=
'text here: ``'
+ str(randomstr) +
'``. text here',
color=0xf1c40f)
confirm.add_field(
name='text here',
value=
'text here'
)
welcome = discord.Embed(title='text here',
description='text here',
color=0xc27c0e)
confirm = await ctx.author.send(embed=confirm)
def check(m):
return ctx.author == m.author and m.content == randomvar
await bot.wait_for("message", check=check)
msg1 = await ctx.author.send(
'text here')
await asyncio.sleep(5)
await ctx.author.send(
'text here')
await asyncio.sleep(2)
await msg1.delete()
role = discord.utils.get(ctx.guild.roles, id=905084755400335370)
await ctx.author.add_roles(role)
dont use play button
then
mm idk
use python3 yourfilename.py
if member.premium_type == discord.PremiumType.nitro_class:, is this not valid?
same with if member.premium_type == discord.PremiumType.nitro:
in console
ill just come back another time
^^^ python3 -m pip install discord.py
his default is 2.7
.
so... have no error in the code?
yeah im download ing all the stuff first
i recommend to learn virtual environment
pipenv will make your life easier
if u have multiple py version
idk
this i didnt knew ty
from where
is your bot working??
entConnectorCertificateError(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)')]
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x104adf2b0>
nope
check pin for ssl certificate error
From this channel.
if i remember correctly stella given very nice explanation
can someone help me?
?
oo wait
just re run your code
Check this channels pins using CTRL + P
huh
just rerun your code
i did
same error??
@ornate lichen
@ornate lichen
yeah
?
^
ggole what
can u like read messsages?
Thanks for spoiling.
??
@ornate lichenI have no idea about the certificates thing, it should be related to securing the connection. But about the unclosed session, I suppose you are using a static session and not making use of an async context manager, so you should call __aexit__ on the session, this closes the connection which is what the context manager should have done.
Sorry, ignore that, it's just that sometimes people have to give some effort of searching it themselves.
^
whr do i run it
i already told him to check pins if he is able to check he would have ¯_(ツ)_/¯
I suggest clicking the link of @mild token.
some people dont read messages 😎
Such a shame stella left though 😓
she did?
yeh she is in my friend list though we use to fight a lot 😂 , she is very intelligent
@slate swan they didnt?
idk what yall talking about
😂
do i just add?
3rd last pin
dont tag random people 😂
yeh just checked 😂
Well I was asking a question
👍
🤨
yup did it
when u gonna stop asking for help 🤨
🤧
I'll take you on that.
We could use a smart set of hands, there are still alot of repl.it users. And people who don't bother to learn OOP.
🥱
Easy to learn hard to master.
Depends.
Easy to learn since python is an OOP lang
Everything you learn as basics should have something to do with OOP
@bot.command ()
async def giveaway (ctx, time = None, *, prize = None):
if time == None:
return await ctx.send ("Incluye una ** duración **!")
if prize == None:
return await ctx.send ("Porfavor pon un ** premio **!")
embed = discord.Embed (colour=0x87CEEB)
embed.add_field(name=f"Sorteo!",value=f"{ctx.author.mention} ha creado un **sorteo** || Premio: **{prize}**")
time_convert = {"s": 1, "m": 60, "h": 3600, "g": 86400}
gawtime = int(time[0] * time_convert[-1])
embed.set_footer(text = f'Este sorteo acaba en: {time}')
gaw_msg = await ctx.send(embed=embed)
await gaw_msg.add_reaction("🎉")
await asyncio.sleep(gawtime)
new_gaw_msg = await ctx.channel.fetch_message(gaw_msg.id)
users = await new_gaw_msg.reactions[0].users().flatten()
users.pop(users.index(bot.user))
winner = random.choice(users)
await ctx.send (f"Enhorabuena! {winner.mention} ha ganado el **sorteo!** || Premio: `{prize}`")```
why my giveaway code doesnt work?
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: -1```
gawtime = int(time[0] * time_convert[-1]) i think its this but idk how to fix it
time_convert = {"s": 1, "m": 60, "h": 3600, "g": 86400} has no key '-1'
how i can make it check the list if the leter is in the list to the operation?
what do you mean? what list
time_convert = {"s": 1, "m": 60, "h": 3600, "g": 86400}, list no i dont remember the name
I don't understand your code's purpose, please be specific such as "how do I reverse a list"
that is a dict
you want to check if some value is in the dict?
if something in time_convert:
i want if time has an s it multiplies for the number i said in time_convert
I see you're trying to get a duration, maybe try using datetime.strptime, more reliable
dont know how to use that
wait actually you can't use that in this case, sorry! try cheking this
https://github.com/chrisdewa/dpytools/blob/master/dpytools/parsers.py
to_timedelta is what you need in order to convert a string into a datetime.timedelta object
okk, i will check
it parses stuff like this and converts to timedeltas
2d15h20s > 2 days 15 hours 20 seconds
1w1d > 1 week 1 day
specifically for discord bots
thanks to @distant birch ;)
async def vk(ctx, member : discord.Member, *, reason=None):
embed68 = discord.Embed(title="Votekick", description=f"vote imod {member.mention}", color=0xf4000)
channel88 = bot.get_channel(907352866946158632)
await channel88.send(embed=embed68)```
Can someone help me remake this to
When 5 votes have been send then the bot kicks the user 🙂
Alo
if member.display_avatar.is_animated():
nitro = " :Nitro:"
else:
try:
req = await self.bot.http.request(discord.http.Route("GET", "/users/{uid}", uid=user.id))
banner_id = req["banner"]
if banner_id:
nitro = " :Nitro:"
except:
nitro = ""``` no errors, probably due to the exception, but im not sure what im doing wrong
What’s the problem. You can’t just ask what’s wrong without giving intentions or anything.
im trying to make the bot check if a user has an animated avatar
if the output is true, then it defines nitro as 
if its not true, it checks if the user has a custom banner
if that result is true, it defines nitro as 
if that result is also false, it defines nitro as ""
Both of those ways are kinda unreliable. Just because someone has nitro that doesn’t mean they will have a banner or a animated pfp. Some people might be just in it for the boosts or the emojis
nitro = None
or False
this works fine as nitro = ""
as seen here
but the attributes and strings themselves were causing problems i believe
Bro has damn near every badge i can think of 😭
what are the 2 yellow ones and the far left one
staff, certified dmod, server partner, hypesquad events, hypesquad house, bug hunter (level 2), early supporter, nitro, nitro booster
damn nice
**Badges**\n{staff}{mod}{partner}{hypesquad}{bravery}{brilliance}{balance}{bh}{bh2}{botdev}{early}{nitro}{boost}```
The only badge i can think of that he doesnt have is Bot Dev
That's a lot of badges
defining these things are a pain :/
yeah theres like 12 of them that you can access trough the .public_flags attribute its a pain
(










)
exactly lmao
ive defined every mobile status, desktop status, web status, public flag, custom status, and now im working on rich presence
rich presence? how so
speaking of, how can i check if a user is playing something
playing, watching, listening to, streaming, ect
!d discord.Member.activities
The activities that the user is currently doing.
Note
Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.
thanks
ive got all lol
good good
f
could things like this work? py if member.activity is 'streaming':
no
yikes
if isinstance(member.activity, discord.Streaming):```
@commands.group(description='Give a member a role./Take away a members role.')
@commands.has_permissions(manage_roles=True)
async def role(self, ctx, member : commands.MemberConverter, *, role : MXRoleConverter):
if role in member.roles:
await member.remove_roles(role)
await ctx.reply(f'Removed `{role.name}` from `{member.name}`.')
else:
await member.add_roles(role)
await ctx.reply(f'Gave `{role.name}` to `{member.name}`.')
@role.command(description='Give a member a role./Take away a members role.')
@commands.has_permissions(manage_roles=True)
async def all(self, ctx, role : MXRoleConverter):
Yes the command is complete.
discord.ext.commands.errors.MemberNotFound: Member "all" not found.
invoke_without_command = True in the group decorator
look at the code though, it's a command group, i'm confused on why it isn't invoking the 'all' subcommand.
and ty
subcommands without that work like this @distant tree :
!role <member> <role> all <role>
for example
okay ty
member.activities
right
what does that mean? a list
well
its meant to test if the users streaming
i was just asking you if ive done it right lol
so in otherwords
if isinstance(member.activities, discord.Streaming):``` is the proper way to go about it
no
isinstance(member.activities, list) would be the only case that would be true
as it is, as i said, a list
custom_activity = discord.utils.find(lambda act: isinstance(act, discord.CustomActivity), member.activities)
listening = discord.utils.find(lambda act: isinstance(act, discord.Spotify), member.activities)
using this can i return a true/false? py if discord.utils.find(lambda act: isinstance(act, discord.Spotify), member.activities) is True: listening = "Listening to" elif discord.utils.find(lambda act: isinstance(act, discord.Spotify), member.activities) is False: listening = "" elif discord.utils.find(lambda act: isinstance(act, discord.Spotify), member.activities) is None: listening = ""
what
it would be is True not == True
find will try to find
alright, and same for false obv
and return None if not found
yep
Yea also add a none
spotify = discord.utils.find(lambda act: isinstance(act, discord.Spotify), member.activities)
if spotify:
listening = "Listening to"
else:
...
huh never know you could get a specifc member activity
so if i wanted to know if they were playing roblox, then it would be discord.Roblox.member.activites?
ae lol
wait so is there a list of discord.INSERT.member.activites?
member.activities
so just spotify?
that is not how object-oriented-programming works
Oh. So is it like how it knows you are connected to spotify and the same thing with minecraft?
or is that wrong.
uhm
discord.Spotify and discord.Streaming exist as they are integrations w the companies and discord
Ohhhhhhhhhhh so it has to be an integration?
k
class discord.Game(name, **extra)```
A slimmed down version of [`Activity`](https://discordpy.readthedocs.io/en/master/api.html#discord.Activity "discord.Activity") that represents a Discord game.
This is typically displayed via **Playing** on the official Discord client.
x == y Checks if two games are equal.
x != y Checks if two games are not equal.
hash(x) Returns the game’s hash.
str(x) Returns the game’s name.
would have to be discord.game?
yes
scroll down from here once it loads:
there are the different types
discord.Game, discord.Streaming, etc
streaming, watching, game?
discord.Game, discord.Streaming, discord.CustomActivity and discord.Spotify
ahhhhhhhhh ok
streaming and watching are discord.Activity.type
which returns a discord.ActivityType such as discord.ActivityType.listening
of course all of them being instances not the classes, etc etc basic oop
How do you make buttons with v2?
from discord_components import Button, ButtonStyle, Select, SelectOption, ComponentsBot
rolesbutton = await ctx.send("-------------------------", components=[Button(style=ButtonStyle.red, label="Click to view member list", custom_id="button1")])
interaction = await client.wait_for(
"button_click", check=lambda inter: inter.custom_id == "button1"
)
@client.event
async def on_button_click(interaction):
with open('userlist.txt') as f:
lines =f.readlines()
f.close()
listembed = discord.Embed(name='Role Members', description=''.join(lines))
listembed.set_thumbnail(url="")
await interaction.channel.send(content=None, embed=listembed)
with open('userlist.txt', 'w') as f:
f.truncate(0)
f.close()
This is pulled straight from my working bot, I included everything the bot references for buttons
Ofc, the txt file parts is specific to the bot, so ignore that and the embed parts
Thanks
Np, if you have any questions about it, feel free to DM or ping me
👍
Hey, I am migrating my code to slash commands, and I've ran into trouble. I am aware of my problem being that I respond to the same interaction more than once. I have tried many different methods to fix this but I gave up. Here's what I want the output to be:
When the /gban command is ran, the interaction is immiedtely responded to with "Banning user from all SL2 servers". Then, once the user is banned from one server, the interaction's original message is edidted, and the "Banning user" message is gone and now it says "User was banned from: (insert server)" As they are being banned from every server, the bot continues to edit and add the server they are being banned from BUT keeps the earlier servers as well. There should also be an exception edit, so if a user cant be banned from the certain servers I defined, it should also insert that server and alert the command executor to the failure. Finally, once all is done, there should be a bolded message at the end of the message that says "Banned the user from all SL2 servers".
@client.slash_command(name="gban", guild_ids=[794596546830008330], description="Ban a user from all SL2 servers!")
async def gbanslash(ctx, user: disnake.User, reason: str):
if ctx.author.id in authors:
for guild in client.guilds:
if guild.id in guilds:
try:
await guild.ban(user)
await ctx.response.send_message(content='Sucessfully banned **' + str(user) + '** from the server called **' + guild.name + '**')
except (disnake.Forbidden, disnake.HTTPException):
await ctx.response.send_message(content='There was an error banning **' + str(user) + '** from the server called **' + guild.name + '**')
await ctx.response.send_message(content='Successfully banned **' + str(user) + '** from all SL2 servers!',mention_author=True)
else:
await ctx.response.send_message(content='Only SL2 High Command can run this command, please contact **SaintBrighten#3919** for more information!', delete_after=5)
await ctx.message.delete(delay=5)
Here is my current code, obviously I am aware of the interaction already responded error as aforementioned.
Any and all advice/help would be appreciated on how to achieve this!
this nested dictionary wont work {'data': 'compontent_type': 2, 'custom_id': '暋ࣁ微⟺徍囈㩅繁ղ汦ℕ犦殿媧寐㻉枱槮็椕絮坪ಁ㾯糎燩㝀耀'}} it says sytanax error
you smelled component wrong
also idk how to read those symbols
are those symbols right?
fym there is 😕
So I have this problem:
In cogs i have to define variables each time in the command
Is there a way to put it 1 time like in a main.py file?
what? docs? source? 100% sure this is false
wait if im using a cog, and i want to define variables, i do i have to do it like this: ```py
class Test(commands.cog):
def __init__(self, client):
self.client = client
self._last_member = None```?
wdym
oh ok
Nvm
Cogs are just python classes, so its the same as using a class
If your unfamiliar with them I'd suggest brushing up on em
import discord
from discord.ext import commands
client = commands.bot(commands_prefix = !)
@client.event
async def on_ready():
await client.change_presence(activity=discord.game('hi'))
print('bot is ready.')
client.run
Invalid syntax line 4
you forgot the quotes at !
Ok ty
and it's not commands_prefix, its command_prefix
Expression cannot contain assignment perhaps you meant ==
show me the code
Ok
import discord
from discord.ext import commands
client = commands.bot('command_prefix' = '!')
@client.event
async def on_ready():
await client.change_presence(activity=discord.game('hi'))
print('bot is ready.')
client.run
@dusky pine
remove quotes for command_prefix
Its
client = commands.bot(command_prefix = '!')
Ok
capitalize Bot
yea that too
client = commands.Bot(command_prefix = '!')
Capital b on Bot
Ok
AYYY
Ty
@slate swan thx
Ty aswell
hi
Np
i need help with class link for python
^
Kk
NOW
My status bot is finished
Nice
Thanks
alex
i need help can u talk to me in dms
import discord
import os
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("/Hi"):
await message.channel.sent("Hello!")
client.run(os.getenv('TOKEN'))```
Am I doing something wrong? My bot won't go online
uh i think ur right send me ss of the error
Traceback?
i need help
?
No error
its a error but i dont want show it on the discord server bc it shoes my bot token can i show u in dms
Just remove the token
Yuh
Maybe its not getting the roken
I forgot to add the token
.
I got a python code for status and I got json code for appearance (phone icon) but the online from python code is taking over json code
It's still not working
Show error
It doesn't show an error... the program just does... nothing
client.run needs to be outside of the event
Unindent it 1 level
Also don't make a bot like that
changed that and like 5 errors in lines that aren't even there pop up
Send the error
I'm not, I'm learning bots for the first time and I just want to get the bot up
Using a / as a prefix is a bad idea
Process.env.TOKEN
Are you using repl?
While this may seem like a nice and free service, it has a lot more caveats than you might think, such as:
- The machines are super underpowered.
-
- This means your bot will lag a lot as it gets bigger.
- You need to run a webserver alongside your bot to prevent it from being shut off.
-
- This isn't a trivial task, and eats more of the machines power.
- Repl.it uses an ephemeral file system.
-
- This means any file you saved via your bot will be overwritten when you next launch.
- They use a shared IP for everything running on the service.
This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.
@slate swan ^
I use hacker plan
I use repl bc I can code on pc and mobile so I can code on the go lol
I have shit pc bc it’s laptop
So repl is good
Yes
But it’s not really affecting much
Its still a self bot
It’s just changing icon to phone
Well self bot is for yourself
So it’s not actually self bot
😎😎😎😎
I'm not sure how the rules would stand on doing something like that
I mean using something to change the status to mobile
I'm aware of discord tos and this servers tos
I'm guessing that he means the status showing the mobile icon
ah.
I started on it but it wasn’t working there so I switched to pycharm
i was wondering if there is a method to get the date when a user joined a server?
!d discord.Member.joined_at
An aware datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be None.
@shy roost
ah okay
i did joined_on
and that didn't work, i'll try this out
@slate swan that worked, I have another question, how can I get the url of a user's avatar?
I got my bot online... will It stay online if I close pycharm?
@timber kindle no if you are locally hosting it through pycharm. If you deploy it to a server like a ssh one that you can purchase, then you won't have to deploy it from pycharm and it will stay online, but if you are deploying your bot through pycharm, then your bot depends on it, therefore if you close the pycharm window, the bot will go offline.
makes sense
!d discord.Member.avatar_url
No documentation found for the requested symbol.
i swear this is what it is but
example:
await ctx.send(f"{member.avatar_url}")
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.avatar "discord.User.avatar")
but to get the url u must add _url
is this right client = commands.Bot(command_prefix=prefix, intents=intents)
yes
k so i want my bot perfix to be =help tell me the code
command_prefix = '=help' i guess?
but why tho
=helphelp, =helpban, =helpkick
i dont see the point but 🤷♂️ who am i to question it
bro it gives me erros when i tryed it
said errors are?
command_prefix = '=help i copy paste it and it gave me errors
What's the error
said errors are?
im assuming that you didnt do command_prefix = '=help' (add a quote at the end)
but why =help
It doesn’t look like the string is completed
also who use =help as a prefix 🤔
fr weird to see a prefix as a word and not a symbol
yea
Dank memer does that
I do think this choice is strange though
=helpwhois @final iron
Imagine typing that in
also =helphelp
never knew
prefix is pls
^
lol
but his prefix is =help it's must be help or just = =help is weird when he want to send the help command he should use =helphelp weird.
I know. I also stated that

userid = message.author.id
idk = str(userid) + 'wool'
```will this work
will it be 757508305256972338wool?
try it and see
idk where to try
if you add a space before the word wool it will be good
Make a test command
i dun wanna risk my whole project
im storing it to database
!eval print('testing' + 'wool')
@silent ermine :white_check_mark: Your eval job has completed with return code 0.
testingwool
yep i think
@bot.command()
async def test(ctx):
userid = message.author.id
idk = str(userid) + 'wool'
print(idk)
You can always create a second bot for testing
message is undefined
!d discord.ext.commands.Context
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
oo
try doing message.content in the command and you'll get what im saying
message is basically ctx (context)
wdym
yes
message is basically ctx
thanks
ok
ctx is context
variable naming doesnt matter
message == context in that scenario
you can even use just c as your context py async def cmd(c):
oo
really?
i think yes
await c.channel.send() or await message.channel.send() in this case
c ofcourse
why not
oo
its just a function which works regardless of variable names
i get it now
or even c.send would work
context has a send coro
!d discord.ext.commands.Context.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
can i write userid = message.author.id itself as a line of code?
not in a function
cuz i cant
message.author.id is the integer id of the author of the message
message would be undefined then
ya
well not necessarily
why cant you write that inside a command function?
i wanna make it universal var
message.author.id is the id of the author of a message object
it has to be same everytime?
make a bot variable
well then just do userID = c.author.id or userID = message.author.id
context object
true, but that's how you'd make it a global variable
wait whats wrong with it btw
if you really wanted to
thats what i do and get message not defined
add it as your bots property
how
because with concurrent code, the variable would update for other concurrently running functions
bot._my_id = the id
simpl
well in the async def commandNAME(message) it has to be message or what ever the "message/c/context" is supposted to be
show me your code
the id you want to be global...
you can
i wanna make user_id as the var name is this how i do it?
yeah sure
you would get it when u do , bot.user_id
or in specific places
does it need to stay same forever , or update ?
its same forever
i wanna do this
i save those user's items with their code
like 12345432wool
1232947648329fish
so i will take their id and add it to the items
to get their items
so at the place where you defined bot py bot = commands.Bot(..............> #just add this below bot.user_id = #the id you want
i dont have this line of code
=.=
huh how do you define a bot object then?
well then what do you define the bot object?
lemme create one
dont say you use discord.Client 🔪
erm
use discord.Bot
client = discord.Client()
:(
oof
its not a thing in discord.py
Only pycord uses that
no?
yes
i use discord.py
oh wait its bot = commands.Bot
!d discord.ext.commands.Bot this is the thingy
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
yes
i write like this?
bot = commands.Bot
client = discord.Client()
yeah
bot = commands.Bot(command_prefix = commands.when_mentioned_or("$", "$$"))
its much more helpful while making commands
or that ig
i did this
if message.content.startswith('rpm help'):
wdym by commands
.
thats cogs right
no?
do you do @commands.command()?
...?
well thats not a good way of making commands
yea
define a prefix and then do like @client.command(), etc
just use commands.Bot it makes life easier
client.event()
hm
undefined name 'commands'
i meant client.command() lol sorryz
ok look here bud: bot = commands.Bot(command_prefix = commands.when_mentioned_or("$", "$$"))
from discord.ext import commands
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
erm ok
@loud junco Read this, it's much better than what you have right now
@loud junco
Here is a basic starting main.py (or what ever the name of the main file is):
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
@bot.command(name="hello")
async def hello_world(ctx):
await ctx.send("Hello, world!")
bot.run("your_token_here")```
why spoonfeed
yes, but they wont understand if you spoonfeed and I already gave a tutorial about discord.ext.commands
I am helping summarize it
he literally doesnt know how to add parameters to functions ☠️
the type of things you should learn before using dpy
Well then.
It can be useful to other members who understand it and need a basic starting file but ok 
im going to change everything in my bot again
AHHH
import discord.ext.commands
from discord.ext import commands
```this 2 is the same right?
or isit different
first line is wrong
this one?
import discord.ext.commands
=.=
Well ig if you use the first one your gonna have to do
discord.ext.commands.Bot()
oo ok
but like what sarthak said the 2nd import is better
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
dont ask about everything pls
think he means its inefficient
anything you did with discord.Client is possible with commands.Bot
so it will work 'too' i meant
alright
other than that there are many other ways to make commands with it
as mentioned in the tutorial kayle sent
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
.dev
what
how to get .dev
Buy





