#discord-bots
1 messages · Page 562 of 1
i try
Oh it’s not working because you forgot to start the task
usually you have to start the task like this, in on_ready
@client.event
async def on_ready(): # let's see if the bot is up
if not change_status.is_running(): # making sure it hasn't started yet
change_status.start()
this needs to be defined under the tasks.loop
I would also recommend cycle, as above, so you don't run into an error when you reach the end
Any errors? What’s your code? (Exclude the token)
You won’t need the client.wait_until_ready
ok
wait 1 minute to see if worked
it only says playing status 1
;-;
should i use the other cycle thing
how to make !help an embedded instead of ""
wdym
!d discord.ext.commands.Bot.help_command
The help command implementation to use. This can be dynamically set at runtime. To remove the help command pass None. For more information on implementing a help command, see Help Commands.
ty
this
discord.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.
WHAT DOES THESE EVEN MEAN??
like bruh
You're sending way too many requests
Are you hosting on repl?
yes
lol
but I havent been on this repl since yesterday
IP addresses that make too many invalid HTTP requests are automatically and temporarily restricted from accessing the Discord API. Currently, this limit is 10,000 per 10 minutes. An invalid request is one that results in 401, 403, or 429 statuses.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
sometimes you just need to read the error to understand
You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.
I read it but like
dont use replit
replit uses a shared IP thats why your getting rate limited
How to check if a user is present in a server
yes but how do I host it 24/7 through things like VSC
Use a paid service or self host
You host it locally on your own machine
Better than not being able to run your bot at all
meaning?
I have a data base of urls that I want to have automatically delete when sent what is the best way of doing this
You should also consider if people are actually using your bot
you don't, you can't
No
I mean in can run and be open but not show on my bar
Like I want my bot to check if my 2nd bot is present in the server if it is I don't want it to respond but if it is not I want it to send a message
?
hm idk
if any(url in message.content for url in list_of_urls):
....
if my_other_bot_id in [m.id for m in guild.members]:
print("Woah my bots here")
Im sure you can figure the rest
Thanks
thanks
Hello
what is the best buttons library compatible with nextcord
also is discord-slash compatible with it
if your using a 2.0 fork that has buttons use it dont use 3rd party libs + forks
nextcord doesnt yet
it was an example
doesnt what
have buttons built in
I'm not spoonfeeding you it all. Figure out where to get a guild from whereever your using your code
?
it does though
They do
how would i run through all banned users to unban them all
but i want a better buttons library with extensive documentation and users using it so they may have the same bugs
lemme go check
a for loop
Read the Docs simplifies technical documentation by automating building, versioning, and hosting for you. Build up-to-date documentation for the web, print, and offline use on every version control push automatically.
you can view the examples + documentation
of nextcord?
yes
isnt there any other way?
I know but i havent migrated to nextcord yet... I plan to soon
Till then which button library can i use
hm
would this work for a dictionary
sorry my bad
but can you suggest a buttons libary please?
so tht it will work with nextcord then also, i dont have to change my code
for now i strictly need a third party library
Discord.py master
uh.....?
Use any 2.0 version for buttons
ok
You can do dict comprehension as well
Im not sure of third party libs for it though
3rd party libs are buggy
nice
im sorry what does that mean
i cant figure out how to unban all users in a dsicord
please someone help me out
it wont let me unban via id either
@bot.command()
@has_permissions(ban_members=True)
async def unban(ctx, userId: discord.User.id):
user = get(id=userId)
await ctx.guild.unban(user)
im not going to waste your time please try to make sense of what that says though
so you don't have to ask again
yeah
I took advice from y'all and used nextcord
mhm
problem is i have like 100 discord-slash slashcommands
AND THEY ALL IMPORT DISCORD AND DISCORD EXT
oh nvm
i read it ban
but more importantly I cant rewrite so many lines of code
there must be an easier way
well the discord_slash library is meant only to use with discord.py
does not nextcord rename the library ( itself )as discord?
you just have to change every instance of discord.something to nextcord.something
it shld
sad
unban all command i know how to do that
how can i use the same setup then on another pc
its igving random errors
iterate thru the ban list , and use .unban
!d discord.Guild.bans
await bans()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves all the users that are banned from the guild as a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`BanEntry`](https://discordpy.readthedocs.io/en/master/api.html#discord.BanEntry "discord.BanEntry").
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to get this information.
how do you access audit logs through bot to look for certain events
!d discord.AuditLogAction
class discord.AuditLogAction```
Represents the type of action being done for a [`AuditLogEntry`](https://discordpy.readthedocs.io/en/master/api.html#discord.AuditLogEntry "discord.AuditLogEntry"), which is retrievable via [`Guild.audit_logs()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.audit_logs "discord.Guild.audit_logs").
heres some random code I found in the docs
async for entry in guild.audit_logs(action=discord.AuditLogAction.ban):
print(f'{entry.user} banned {entry.target}')
so you would change the AuditLogAction.ban to a different action
Nextcord works with the discord namespace. Install discord slash. Pip uninstall discord.py. pip install nextcord
i did tht
it shows error everywhere discord is imported
can someone help me with purge
chzz = guild.get_channel(887043608308514889)
await chzz.purge(limit=200)```
AttributeError: 'NoneType' object has no attribute 'purge'
however if I use it under a command it works with ctx like:
await ctx.channel.purge(limit=amount)```
could yall check #help-peanut
its about discord.py
dang you're right! @gloomy coral I messed up the channel id.. haha thank you so much
xD
Traceback (most recent call last):
File "C:\Users\jason\chad\bot.py", line 31, in <module>
slash = SlashCommand(bot, sync_commands=True)
File "C:\Users\jason\chad\venv\lib\site-packages\discord_slash\client.py", line 72, in __init__
self.req = http.SlashCommandRequest(self.logger, self._discord, application_id)
File "C:\Users\jason\chad\venv\lib\site-packages\discord_slash\http.py", line 22, in __init__
self._application_id = application_id
NameError: name 'application_id' is not defined```
What to do??
using discord slash command
use bot
module problem ig
!f-string
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
ExtensionFailed: Extension 'cogs.wordgames' raised an error: AttributeError: module 'discord' has no attribute 'Message'
Help
i am using nextcord but it shld work right
what was the code for the process_commands thing
await bot.process_commands(message)
Also next time you should probably search on docs
its much easier to ask people then search through docs that make no sense to me
my code still dosnt work
Well but the docs for discord.py have a search bar and examples
or atleast commands don't
Maybe you're returning before it reaches it?
im not going to get into an arguement I just can't comprehend what I read
no returns
It's in an on_message event, right?
yeah
Do you have any other on_message somewhere?
nope
Oh. Is your bot in 75+ servers & unverified?
its in 2
the actual command works the other ones dont
Indent the process commands out of your for loop
ok
it worked thanks and that the end of my bot
👍
actually nah ima add a really suffisticated logging system that logs everything
How to run 2 python file at the same time? One will be how bot run, and one is handling command
What? Just run your main bot file and use cogs for commands and event listeners
how do I remove this from the help command?
With the hidden=True kwarg
where do I put that
no im using the default help command
the default one is already good
Well apparently get_command is a thing
So get the help command and set the hidden argument to true I guess
hm
!d discord.ext.commands.Bot.get_command
get_command(name)```
Get a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list of commands.
This could also be used as a way to get aliases.
The name could be fully qualified (e.g. `'foo bar'`) will get the subcommand `bar` of the group command `foo`. If a subcommand is not found then `None` is returned just as usual.
How would I edit it though
Why do you need that
find out the ID of the specified user
And where do you use that
in the command
Team?
use the strip function.
Type hint the command argument to discord.Member
Then you can simply use .id
it does not output like that writes an error
Then show error and code?
!e py stripped = '<@&1234556>'.strip('<@&>') print(stripped)
Ignoring exception in command кик:
Traceback (most recent call last):
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 552, in transform
return await self.do_conversion(ctx, converter, argument, param)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 505, in do_conversion
return await self._actual_conversion(ctx, converter, argument, param)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 451, in _actual_conversion
ret = await instance.convert(ctx, argument)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\converter.py", line 195, in convert
raise MemberNotFound(argument)
discord.ext.commands.errors.MemberNotFound: Member "<@&901771204652843049>" not found.
@slate swan :white_check_mark: Your eval job has completed with return code 0.
1234556
Na, just type hint it for commands
Member not found
lol they are typehinting it as discord.Member and pinging a role , gg
You know that <@&id> is a role mention and not member mention right?
You mentioned a role when using the command
I'm an idiot didn't know
is it the correct way to do this? I want to make a database of all reaction roles and it's role id but instead of creating another json obj, it edits the existing one. How can i make it create a separate json obj for all reaction emoji and roles?
https://youtu.be/a2pYgIuVCxE Problem Formulation Given a JSON object stored in a file named "your_file.json" such as a list of dictionaries. How to append data such as a new dictionary to it? # File "your_file.json" (BEFORE) [{"alice": 24, "bob": 27}] # New entry: {"carl": 33} # File "your_file.json" (AFTER) [{"alice": 24, "bob": 27}, {"carl": 3...
cringe json
i could've used sql but it is a small thing so it is fine
lemme check it out
Read the JSON file
Save the dict in a variable
Append the new record to the dict
Open in write mode and just save the new dict to the json
I just did something called ✨ searching ✨ and sent the first link I got as result
nice XD
Might want to try it out sometimes
i didn't get the correct keyword in by brain at that time maybe thats why i dodnt got the result required
now i remember the keyword is "append"
i have to learn searching
thanks for the link btw
add data to json python
append data to json python
add data to existing json python
Just think about what you want to do in a few words
Any tutorials how to work with subcommands?
@slate swan it gives AttributeError: 'dict' object has no attribute 'append'
AttributeError
its dictvar.update()
sup so how do i make the embed a different color
class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
i need help
color attr
just send question bruh
Hi
I wanna make a reply bot how do I make it ?
!d discord.Message.reply
await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message").
New in version 1.6.
or ctx.reply
Not like that
then how?
i have a bot, i made it, so now i want to make an embed, I MADE IT, now i want to change the color, i did NOT make it
so how to change color
!d discord.Embed
class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
there is color attr
await message.channel.send("<whatever u want>")```
u make wtf = discord.Embed(title="bruh", description="very bruh lol", color=discord.Color.blue())
then when u want to send the embed u do await message.channel.send(wtf = wtf), right?
embed=wtf
sry not that one
oh ok
?
in specifing embed
what not in add field
like embed=discord.Embed(..., color=...)
color
bruh?
they just told you

j u s t s e n d m e t h e c o d e
they did XD
we dont spoonfeed
w h e r e
wtf = discord.Embed(title="bruh", description="very bruh lol", color=discord.Color.blue())
thats the code
(that was example)
o k a y
yes
ok
sorry but no
now what, do i just copy and paste this no
bruhhhhhhhhhhhh
bruhhhhhhhhh im a beginerrr bruhhhhhhhhhhhhhhhh
just type color = discord.Color.blue()
ok fine
now you just move color=discord.Colour.dark_blue() to embed
so like this? (color=discord.Colour.dark_blue()) (and i remove the (embed=embed) and replace this?
🤦♂️
fuck you guys
no problem
lmao

k i fixed ur code in replit @serene forum
oh @hasty iron maybe u know how to use subcommands, or where is their docs
!d discord.ext.commands.Bot.group
@group(*args, **kwargs)```
A shortcut decorator that invokes [`group()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.


it updates the existing one
i wanna create a new json obj
i want to append data in the json file inside a different {}
dict[index] = value
for me?
why not use a proper db (unrelated)
like { 'bruh': 182, 'lol': { 'bruhy': 1 } }
which one?
how can i do that?
data = get_json_data
data[message.id] = {'role_id': role_id, ...}```
can u pls give me another example of what and how to do that?
can be like that
get_json_data will be a func?
get_json_data is a dict with all that is in json file
oh got it
i already forgot how to get that dict form json)
is there a reason behind bots not being able to have rich presence images?
you mean why bots cant have rich presences?
ya
they technically do have a rich presence, but its just "playing __" for example
without an image
well have you tried testing it on your bot using an rpc maybe before asking here
that was not my question
its kinda like self botting though imo
makes sense
kinda wish it was built into discord.py cause i wanna customize my personal bots more
what loop don't cause commands to not works and is not infinite(you can set how many times it will be repeated)?
will it freeze ability to use commands like while loop?
yes thats how loops work
how can you send message to a user using their ids
possible (thanks to the people that corrected me, taught me something new)
u can send a message to a user who used a command tho
possible
thats what i did for a few of my bots help commands so that they didnt clutter chats
get by id
!d discord.ext.commands.Bot.get_user
get_user(id, /)```
Returns a user with the given ID.
lol bruh 
How do i convert time to timestamp i tried the datetime to timestamp one but have no idea how to convert the "time" to timestamp
date_string = "10/26/2021"
date = datetime.datetime.strptime(date_string, "%m/%d/%Y")
timestamp = datetime.datetime.timestamp(date)
await ctx.send(f"<t:{round(timestamp)}:R>")
Time i mean is like "10:00" or smth im trying to do timestamp
Im trying to do the discord timestamp one
That's why im asking here
yes but you need a number like 120958235 that you are converting from datetime
so not here
it could be related to this channel if you asked like how to make timestamp
Alright then 
In user_id: Value "<built-in function id>" is not snowflake.
i am using await bot.fetch_user(id)
more code pls
how would I set my help command in a cog (im using the default one just editing it)?
ty
Anyone?
noway
Why
you think i know?
There is a code but I can't find it
@discord-developers WHY BOTS CANT USE RICH PRESENCE
I didn't say YOU know it
ok
Just mean if anyone knows it
@strong ibex whyyy
Is it possible that there can be a Nonetype on client.guilds?
@indigo moth
Who are you pinging?
lol
@wary basalt
LOL noone's id will be 000000000000000000000
foot = [
"Trivia:\n...1",
"Trivia:\n...2",
"Trivia:\n...3"
]
embed.set_footer(text=random.choice(foot))
When I doing this, it give me error. Did I miss something or it not possible?
what error
@client.command(pass_context=True)
async def drink(ctx):
client.counter += 0.03
client.dict[ctx.author.id] = client.counter
await ctx.send(f'{ctx.author.mention}\'s Blood Alcohol Concentration level is now {client.counter}')
await asyncio.sleep(60*(60))
client.counter = 0
@client.command()
async def checkbac(ctx, arg : discord.Member):
await ctx.send(f'{ctx.mention} has a BAC of {client.dict[arg.author.id]}')```
error pls
that's not the error lol
its a game
basically
i run this function, my "counter" adds 0.3 and sets the updated value to my name
and in the next function im getting the counter value
ik its not
ok but what was the error that came
share error
not he asked bruh
what is your error
TypeError: Aliases of a command must be a list or a tuple of strings.
how do you define command
self explanatory
like decorator @commands.command
doesnt look like it's related with the game code
remove the random.choice thingy
bruh no
no it looks like they defined the command wrong
it's not related to aliases
But i need to give random list
sorry wrong ping lol
@block_info.command(name='grass_block', aliases='grassBlock')
async def grassBlock(self, ctx):
title = 'Grass Block'
desc = 'A grass block is a natural block that generates abundantly across the surface of the Overworld.'
link = 'https://minecraft.gamepedia.com/wiki/Grass_Block'
pict = 'https://static.wikia.nocookie.net/minecraft_gamepedia/images/b/b5/Vector_dirt.svg/revision/latest/scale-to-width-down/192?cb=20180202214450'
val1 = 'JE: `minecraft:grass_block`\nBE: `minecraft:grass`'
val2 = 'Tool: `Shovel`\nMin: `By Hand`'
foot = [
"Trivia:\nThis was first block added in Minecraft just like cobblestone and dirt",
"Trivia:\nA grass block used as icon of the Minecraft Launcher and BE App",
"Trivia:\nGrass blocks and dirt blocks changing between each other is a common cause of chunk updates."
]
embed=discord.Embed(title=title, url=link, description=desc)
embed.add_field(name='Block ID', value=val1, inline=True)
embed.add_field(name='Tool', value=val2, inline=True)
embed.set_thumbnail(url=pict)
embed.set_footer(text=random.choice(foot))
await ctx.send(embed=embed)
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/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: AttributeError: 'Context' object has no attribute 'mention'```
aliases needs to be a list
aliases=['grassBlock']
if u want only 1 alias just put the alias in a list
like this
ctx.author.mention
that code looks fine
??
Ok it work
code:
@client.command()
async def server(ctx, *, args):
username = ctx.message.author
bprint.info(f"{username} used the 'server' command")
if args.lower() == "info":
bprint.info(f"{username} used the 'server - status' command")
content = "info!"
elif args.lower() == "start":
bprint.info(f"{username} used the 'server - start' command")
content = "start!"
else:
content = "else??"
await ctx.send(content)
problem: If someone only uses $server with no args it spits out an args error. But I want it so that a error msg appears in chat. How could I do that?
@client.command(pass_context=True)
async def drink(ctx):
client.counter += 0.03
client.dict[ctx.author.id] = client.counter
await ctx.send(f'{ctx.author.mention}\'s Blood Alcohol Concentration level is now {client.counter}')
await asyncio.sleep(60*(60))
client.counter = 0
@client.command()
async def checkbac(ctx, arg : discord.Member):
await ctx.send(f'{ctx.mention} has a BAC of {client.dict[arg.author.id]}')```
it looks like u did ctx.mention
shit
@slate swan
my bad
you need to get the author, so that's ctx.author
arg.mention
ok arg
ctx.author is the author of the message
if you want their mention, it's ctx.author.mention
Could any1 help me?
he said arg.mention, look he have arg: discord.Member argument?
we all make mistakes
oh i see
it would be better to rename arg to member to make it more clear to read
add =""
but yes arg.mention then
=None is better
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/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: 439875622626394122
my. code is working, but there's a little bug
that's python error
not dpy
If i do !checkbac before i even drink, rather than it giving me 0.00 it gives me error
the index with user's id not exists in dict
yes bc i havent ran the !drink function before
cause u didn't save it in the dict
no way to fix?
try and except
noooo
u mean accept?
😬
if user_id not in dict:
return await ctx.reply('use !drink first')```
yea
mine works too lol
your is bad lol
y tho
too broad exception clause
uh ye
wdym? error?
what's the error
that key doesn't exist
already answered
u r about 5 min too late
heres the code im sending the error in a sec

error:
Ignoring exception in command server:
Traceback (most recent call last):
File "C:\Users\49159\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\49159\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Users\49159\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "C:\Users\49159\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 706, in _parse_arguments
kwargs[name] = await self.transform(ctx, param)
File "C:\Users\49159\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 542, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: args is a required argument that is missing.
you didnt specify that args is '' by default
do return
lol u didn't even listen to what we said
pls explain too
to stop function running
ok
thx

same error with return as well
most of users that ask there dont know basics
code pls
1 sec

yeah they should learn py first
@client.command(pass_context=True)
async def drink(ctx):
client.counter += 0.02
client.dict[ctx.author.id] = client.counter
await ctx.send(f'{ctx.author.mention}\'s Blood Alcohol Concentration level is now {client.counter}')
await asyncio.sleep(60*(30))
client.counter = 0
@client.command()
async def checkbac(ctx, *, arg : discord.Member):
await ctx.send(f'{arg.mention} has a Blood Alcohol Level of {client.dict[ctx.author.id]}')
if ctx.author.id not in client.dict:
return await ctx.send('0.00')
yeah, typehints are like...
lol
bruhhhh
if should be before await ctx.send
learn py properly first 😬
stop copying old tutorials when
lmk when u find this on a tutorial
yeah pass_context is bruhy useless
so it's copy pasta
literally wrote it myself by okay
what is that for, I never used it
dont care what yall say bro im proud bc ik i wrote this shit
it is just useless (in v >1.0)
sure you did
why did you use pass context then
that i looked up
it wasnt before 1.0
but most of the stuyff if by me
and bro yall so tough on discord yall aint gonna open ur mouth if u see me irl
little ass kid

@slate swan Please calm down, there's really no need to get angry no matter the situation
my fault
imma just leave chat
ok
async def solarflare(self, ctx, startTime=None, endTime=None):
url = f'https://api.nasa.gov/DONKI/FLR?startDate={startTime}&endDate={endTime}&api_key=Sw74skknSPoVUr4N7o6JsS0cep35Y4ylLelzsXy8'
data = requests.get(url).json()
pages = len(data)
content = data[0:pages]
current_page = 0
message = await ctx.send(f"Page {current_page}/{pages}:\n{content[current_page - 1]}")
await message.add_reaction("◀")
await message.add_reaction("▶")
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in ["◀", "▶"]
while True:
try:
reaction, user = await self.bot.wait_for("reaction_add", timeout=60, check=check)
if str(reaction.emoji) == "▶" and current_page != pages:
current_page += 1
await message.edit(content=f"Page {current_page}/{pages}:\n{content[current_page - 1]}")
await message.remove_reaction(reaction, user)
elif str(reaction.emoji) == "◀" and current_page > 1:
current_page -= 1
await message.edit(content=f"Page {current_page}/{pages}:\n{content[current_page - 1]}")
await message.remove_reaction(reaction, user)
else:
await message.remove_reaction(reaction, user)
except asyncio.TimeoutError:
await message.delete()
break
def setup(bot):
bot.add_cog(SpaceWeather(bot))
So what i wanted it to do was after the user clicks the reaction, it moves to the next page (edits the message) and remove the reaction, after clicking once it works fine, but it doesnt remove the reaction or doesnt move to the next page after that
How can I get the cog class name for a command/group?
the parent cog for the command/group?
yes
!d discord.ext.commands.Command.cog
The cog that this command belongs to. None if there isn’t one.
!d discord.ext.commands.Command.cog_name
property cog_name: Optional[str]```
The name of the cog this command belongs to, if any.
Same with the group
Ah cool thanks! (both)
!d discord.ui.Button
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
!d discord.ui.Select
class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu.
This is usually represented as a drop down menu.
In order to get the selected items that the user has chosen, use [`Select.values`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.Select.values "discord.ui.Select.values").
New in version 2.0.
How to set webhook username using python
i have this problem that reason is only the first word in the sentence. Does somebody know how to get the hole string?
You can use an asterisk as a parameter to pass everything after the asterisk to the next parameter
i tried write bot.event command
but is that possible if only we as admin can command the bot (not member) ?
hello i got a issue on heroku, did anyone can help me?
2021-10-27T09:26:21.966670+00:00 heroku[worker.1]: Starting process with command `phyton main.py` 2021-10-27T09:26:22.581705+00:00 heroku[worker.1]: State changed from starting to up 2021-10-27T09:26:22.637325+00:00 app[worker.1]: bash: phyton: command not found 2021-10-27T09:26:22.743918+00:00 heroku[worker.1]: Process exited with status 127 2021-10-27T09:26:22.933383+00:00 heroku[worker.1]: State changed from up to crashed
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
do you mean .split('#')
lmfao
Lucas ban eww
just trying to see if it works
it does you just made a typo
member = discord.Object(id=0) # user ID
try:
await guild.unban(member)
except discord.NotFound:
# member not banned / doesnt exist
it's supposed to split the name & the tag using # but u did a
ez
don't follow yt tutorials
copies gUilD is undefined pls help
async def add(ctx , num1:int , num2:int):
await ctx.reply(num1 + num2)```
why isnt this code working?
error?
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "add" is not found
did u run the command
yh
i did that n it aint working for some reason
@slate swan show full file if you could
Hey @slate swan!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Hey @slate swan! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
from discord.ext import commands
from discord.ext.commands.core import command
bot = commands.Bot(command_prefix='.')
@bot.command()
async def hello(ctx):
await ctx.reply('Wagwan?')
@bot.command()
async def add(ctx , num1:int , num2:int):
await ctx.reply(num1 + num2)
bot.run(')```
hm
maybe because of from discord.ext.commands.core import command
u want me to delete it?
yes
maybe it overwrites from discord.ext import commands idk
@slate swan does .hello work?
show full traceback/error
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "add" is not found```
full traceback if u could
i cant get commands.Bot's listen method to work in the main discord bot file
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
hm?
meaning?
full error
it shows theres no problem
i cannot execute anycode within my on_ready function in the same file
usually like this
Ignoring exception in
file://ur_file
the above exception was blah blah blah
u can though
its almost like it never worked except it worked like 4 hours ago
show me what u did
its like it does not got run atall
discord.ext.commands.errors.CommandNotFound: Command "add" is not found ```
this is all it shows me
you dont have a command named "add"
does it print something
nothing
how do i add it?
this is all i have output woze
make a command named add
hm
i disable members intents and it works 😡
oh
Create that command
did i say it works??? i ment it never works
async def add(ctx , num1:int , num2:int):
await ctx.reply(num1 + num2) ```
but i already have
Do you have on message events?
whats that
And does other commands work?
yes
And what is the full traceback
discord.ext.commands.errors.CommandNotFound: Command "add" is not found
Thats the whole traceback?
yh
isnt tracebaxk the thing that comes in the terminal
yes
yh thats what comes up
u said it dindt show up though
and now fucking on_message is not working cant fetch anything on_ready is not working
nothing is working anymore
Shuts down computer
im about to destroy my computer
same lmao
rage mode
are you sure you processed on_message event
show error
...
@slate swan rename the command
But all other commands work..?
it works
how
bro how many times have i shown u guys the traceback
your giving the error, not the traceback
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
A full traceback could look like:
Traceback (most recent call last):
File "tiny", line 3, in
do_something()
File "tiny", line 2, in do_something
a = 6 / b
ZeroDivisionError: division by zero
The best way to read your traceback is bottom to top.
• Identify the exception raised (in this case ZeroDivisionError)
• Make note of the line number (in this case 2), and navigate there in your program.
• Try to understand why the error occurred (in this case because b is 0).
To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.
You never did
fuck me it works now
out of nowhere it just works
i restarted visual code
thank you @tawdry perch @boreal ravine
I guess you never save the file

LMFAO
Hello, when I create folder for new discord bot, and when I will open cmd for that folder, I use command pip install discord.py and in the code I use import discord and from discord.ext import commands. After start program, it will do this: ModuleNotFoundError: No module named 'discord.ext'; 'discord' is not a package
Please help, what can i do?
what did you name this folder you created?
Do u use pycharm?
if you perchance called it discord python is now confused about what to import (the library you installed or this folder) (this conflict can occur if you named a file in this folder as discord.py as well)
VSC
Oh ok nvm then
so i made a seperate dban command which deletes the messages in the last 24 hours(which is default). but i dont want it to delete the messages when the normal ban command is used. this is the code that i have. what am i doing wrong?
@commands.command()
@commands.has_permissions(ban_members = True)
async def ban(self, ctx, member: discord.Member,*,reason = None, delete_message_days = 0):```
?
check for what python version you installed the package and what python version vsc is using
???
wdym
its not supposed to delete the messages of the banned user
then dont make it delete it?
how?
i dont think ban commands delete messages
this is what i m using rn:
async def ban(self, ctx, member: discord.Member,*,reason = None, delete_message_days = 0):
they do
i dont think its possible
it does
ok?
any idea how i can make it not delete them?
set delete_message_days to 0
@graceful gulch like this?
ive done that already though
thats a parameter though
do you think its delete_message_days : 0 and not delete_message_days = 0?
you do realise you also have to add to member.ban() too
what no why
oh
u cant typehint to a bool (0) tf
how do u expect to ban someone without banning them??
umm
@boreal ravine :white_check_mark: Your eval job has completed with return code 0.
5
Guys, how do I move a channel to a category? this is the code i have
async def mover(ctx, position, name):
if ctx.message.author.guild_permissions.manage_channels:
channel = get(ctx.guild.channels, name=name)
await channel.edit(category=position.upper())
In dpy internally they convert it
but sometimes your ide can raise issues if passing a different type to a function that’s type hinted
Those are type checkers, again vanilla python doesn't have this
maybe if you want it to be a certain something?
And if you run it then it won't error
No just readability, if you want a certain thing you use if statements etc to check
anyone?
!e
def add(a, b):
return a + b
print(add("hi", "you"))
``` who would wanna add strings together though
@boreal ravine :white_check_mark: Your eval job has completed with return code 0.
hiyou
then use isinstance and check if the param's type is the one you want, if not raise an error (most likely what dpy does too)
pleeeassee???
i know
but we werent talking about isinstance

Either way tyoehints in regular python don't do anything they just tell the person what the function expects
you can do that?
python evaluates the typehint tho
It does not evaluate it just acknlowdges its there
But doesn't do anything afterwards
No, I meant you put in an extra = on actidrnt
You only need 2
Guys, how do I move a channel to a category? this is the code i have
async def mover(ctx, position, name):
if ctx.message.author.guild_permissions.manage_channels:
channel = get(ctx.guild.channels, name=name)
await channel.edit(category=position.upper())
How can I DM a user with my bot?
im using cogs
!d discord.Member.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**.
show code
thanks
Am I invisible or smth 🥲
why is ur elif statement
indentation?
inside your if statment
that elif don't connect to anything
no lol i just dont know how to do that maybe get the category ID then move it in there? idk
ah....okay...thank you
its supposed to be like this
if ...:
elif ...:
``` but you did
```py
if ...:
elif ...:
how can I get discord api ping?
?
api ping?
use .latency with your bot constructor's name
it will give the bot's ping
Okay
oh
For proper
ping = int(bot.latency) *1000
what about the message latency?
TNX
can anyone help me or provide docs to make a fight mini-game command? like !fight {user}
but the options like fight,block,kick
and each user gets 1 chance after other and the fight ends 1 user hp goes 100-0 and options will be used as kick not !kick or !fight kick
I'll tell you how you can do it to take the user input, the rest is pure python which you have to do yourself, if you don't know then you really need to learn more python because this is really basic, to get the user input use wait_for and for the check simply check if the author is any of them (you can decide who starts), make sure you have a turn var which holds one of the users, after each time a user gives an answer, make sure to change the turn with the other player so that when you check for their message it'll only take the current player that needs to input and not both of them, after you got the message use .content.lower() and check if it's one of your options, if it is then do whatever you need to do, otherwise do something else
It's really really easy to create one, gl 👍
!d discord.ext.commands.Bot.wait_for
This is the wait_for that you'll need
It didn't send 🤨
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
how to get list of running tasks
if message.content.startswith('blender progetto'):
i have tried with if message.content.lower.startswith('blender progetto'):
but doesnt work
asyncio.all_tasks(bot.loop)
How can I get the users who clicked the button?
how to name a task
hello im new to discord py, would someone be able to help me make a command handler?
same thing
@tasks.loop()
async def name()
oh
elaborate please
Wdym i said what i wanted to do
do you mean the starter code?
how can I delete all rows at once from my sqlite database?
error handler?
so, you want to make cogs? or import those files and use their functions?
u mean making commands?
I was confused 🥲
same
if message.content.lower().startswith(.....)
hello
Can someone help me how do I delete all rows in my sqlite database without deleting my database?
sowwy, I don't know how to use sqlite
search google tho
yeah, i just searched
um did anyone understand about heroku?
I did it
oh sad
anyways, thanks @upbeat otter
i deployed like 9 time and it always show a same error
Process exited with status 127
cant you just do DELETE FROM table?
doesnt work
did you import
from discord.ext import tasks
how do i accept 2 errors only saying except once
i can make a function just how do u name the task
async def name()
except (Exception1, Exception2):
thx
when i do
for i in asyncio.all_tasks(bot.loop):
print(i.get_name())
``` it doesnt print the name of the function
wdym?
just use a print() inside the tasks to see which function is running and printing
i need to do it with a command outside the task
what does it print currently?
@tasks.loop(time):
async def function1():
print("function1 is running")
#do other stuff
this should help tho
Task-290
Task-2
Task-146
not that
my tasks works fine i dont need help with that
im trying to get a list of running tasks by doing a command elsewhere
ur giving me the wrong help btw
as it's stated in the docs "If no name has been explicitly assigned to the Task, the default asyncio Task implementation generates a default name during instantiation."
yep i guess, so how do we give it a name?
i think gota do get_task() then set_name in the task function
Bruh i just said what i wanted
😩
Use cogs and have 1 command per file/cog ig
do you wanna make commands?
oh yep u do that
oof, you could have said that earlier
i did
i can make a function just how do u name the task
i just said. i want my commands in seperate files in a folder
so, eventually I did this:
import asyncio
for i in asyncio.all_tasks(bot.loop):
print(i.get_coro().__name__)
also whats wrong here?
I just renamed it in the init function
self.task.start()
self.task.get_task().set_name(f'PlayerCountTask')
oh you mean cogs?
im trying to psudocode
=> isnt a thing only -> is
cogs?
oh
=> is js thing
yes it allows you to make commands in different files
that then
hm
lol
similar to := in python
wait ill give a tutorial
Ok, is there a way to send webhooks and embeds using discord webhook
embed.add_field(name='etc'....)
yes
how do i send a webhook trought that library
create webhook > make embed > send embed to webhook
yes
!d discord.TextChannel.create_webhook
await create_webhook(*, name, avatar=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a webhook for this channel.
Requires [`manage_webhooks`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_webhooks "discord.Permissions.manage_webhooks") permissions.
Changed in version 1.1: Added the `reason` keyword-only parameter.
!d discord.Webhook.send
oki
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., wait=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message using the webhook.
The content must be a type that can convert to a string through `str(content)`.
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.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be 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 to send.
Ohh
btw, you're trying to define f inside the parentheses right?
@bot.listen()
async def on_message(message):
if not (message.author == bot.user) and (message.content.lower().startswith('Hi')):
await message.reply(f"Hello", mention_author=True)
why it isnt working?
how should i put "await"
meaning?
you have lowercased the content..
domt worry someone is going to help me with cogs
this is js ;-;
imma send u the code
thats why i said like this lol
I do know js, but not discordjs ;-;
ok
Eviee's gist gave 404
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
mmm
how and i make it case insensitive
embed = discord.Embed(
title = 'Title',
colour = discord.Colour.blue()
)
embed.add_field(name='Field', value='Value')
send(???)
@boreal ravine
I printed both with [(i.get_name(), i.get_coro().__name__) for i in asyncio.all_tasks(self.bot.loop)]
Tasks: [('Task-126', '_run_event'), ('Task-125', '_run_event'), ('PlayerCountTask-1', '_loop'), ('Task-2', 'runner')]
do u know what the other tasks are
oop
.
no like, you have it lowercased already, then you're seeing if it starts with a string with uppercase letter in it?
A Cogs Example for the rewrite version of - discord.py - bot_example.py
you'll need to create the webhook first
yeah
how do I make it like: it shows, Voting Website in an embed, and it should take it to youtube?
ik
@safe fulcrum, looks like you posted a Discord webhook URL. Therefore, your message has been removed, and your webhook has been deleted. You can re-create it if you wish to. If you believe this was a mistake, please let us know.
wt-
yes, pass in all the required args (name should be enough) and then save the webhook thingy in a variable then send it
🫂
Anyone?
Hello. Please help me solve the problem - I created a bot that should change banners on the server after a certain time. But before launching, it gives the following error:
===== RESTART: C:\Users\Дмитрий\Desktop\discord-banner-changer-main\main.py ====
Traceback (most recent call last):
File "C:\Users\Дмитрий\Desktop\discord-banner-changer-main\main.py", line 2, in <module>
import discord
ModuleNotFoundError: No module named 'discord'
Code:
import os
import discord
import random
from discord.ext import tasks
BOT_TOKEN = ''
client = discord.Client()
@client.event
async def on_ready():
print("logged in: ", client.user)
@tasks.loop(minutes=5)
async def main():
images = os.listdir('images')
image = random.choice(images)
with open(f'images/{image}', 'rb') as f:
guild = client.get_guild(530367265053474818)
await guild.edit(banner=f.read())
@main.before_loop
async def before_main():
await client.wait_until_ready()
main.start()
client.run(BOT_TOKEN)
other tasks?
what
_loop would be other tasks
from discord.ext import commands
import os
bot = commands.Bot(command_prefix="!")
bot.load_extension("somecommands")
bot.run(os.environ['TOKEN'])
commands/somecommands.py
from discord.ext import commands # Again, we need this imported
class SomeCommands(commands.Cog):
"""A couple of simple commands."""
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.command(name="ping")
async def ping(self, ctx: commands.Context):
"""Get the bot's current websocket latency."""
await ctx.send(f"Pong! {round(self.bot.latency * 1000)}ms") # It's now self.bot.latency
def setup(bot: commands.Bot):
bot.add_cog(SomeCommands(bot))
try:
pip install discord
pip install discord.py```
idk whats wrong
any error?
.
