#discord-bots
1 messages · Page 88 of 1
ehm..
i said like thrice
I'm blind..
oh last thing how do I make it be in embed? @slate swan
!d discord.Embed use this class and construct an embed, later send it using the embed kwarg in .send method
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, 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.
x == y Checks if two embeds are equal.
New in version 2.0...
bot.responses = ["WRHEGIRHGH", "GRWHUGRHEAGUH", "FHSUGHUAGU", "FREHUGHEU", "RWGHUEHGU", "GREHIUGHA", "RIGEWFWUAN",
"GHERIGHWOD", "GERIAGHI", "GHDIAGH", "GHFDSIGH", "GREGQJOF", "GWEGHUSI", "GWRHGUIHA", "HGIHIGRIS"]
@tasks.loop(hours=2)
async def drops():
await bot.wait_until_ready()
channel = bot.get_channel(986712676019359835)
embed = discord.Embed(title="100 CHAKRA DROP!", description=f"First one to dm Mecha Naruto {}")
#await channel.send(random.choice(bot.responses))
drops.start()```
no I know how to use it
look here
whats the issue then
do I do it like this
embed = discord.Embed(title="100 CHAKRA DROP!", description=f"First one to dm Mecha Naruto {bot.responses} will win")
yeah
that's correct
ayo @slate swan it just sent all codes
I need it to send one randomly
intreaction not wotking why ?
wrap that in random.choice then 🗿
how
do I just write
{random.choice bot.responses} or what
how did you do that here?
close, but no
{random.choice(bot.responses)}
Damn man you typed the whole alphabet in a list, you could've just
from string import ascii_lowercase
alpha = list(ascii_lowercase)```
YESSS
And yeah it doesn't work because your callback is inside __init__ for no reason
i remove it
still not working
You need to move it out
my mistake
ya i did
like this
yes
await callback(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The callback associated with this UI item.
This can be overridden by subclasses.
views only have on_interaction iirc
in dpy yes
which one should i use discord.py or pycord?
pycord is not an available choice at all
@limber bison you need to either use @discord.ui.button decorator for each button or make Button subclass
its just... yeah
why not
From what I know their code is messed up, but I haven't seen it by myself
loop work on it
hello! how to store data in json file from score with update
i am using loops
Not really related to the channel, depends, how large is that data and how much times does the data get mutated in a certain time span?
sounds like something a db would be better for
!d json.dump
json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)```
Serialize *obj* as a JSON formatted stream to *fp* (a `.write()`-supporting [file-like object](https://docs.python.org/3/glossary.html#term-file-like-object)) using this [conversion table](https://docs.python.org/3/library/json.html#py-to-json-table).
If *skipkeys* is true (default: `False`), then dict keys that are not of a basic type ([`str`](https://docs.python.org/3/library/stdtypes.html#str "str"), [`int`](https://docs.python.org/3/library/functions.html#int "int"), [`float`](https://docs.python.org/3/library/functions.html#float "float"), [`bool`](https://docs.python.org/3/library/functions.html#bool "bool"), `None`) will be skipped instead of raising a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError").
The [`json`](https://docs.python.org/3/library/json.html#module-json "json: Encode and decode the JSON format.") module always produces [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") objects, not [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. Therefore, `fp.write()` must support [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") input.
If *ensure\_ascii* is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If *ensure\_ascii* is false, these characters will be output as-is.
import json
import asyncio
import aiofiles
content = {'test': 'test'}
async def main():
async with aiofiles.aopen('file.json', 'w') as file:
json.dump(content, file)
asyncio.run(main())
how would i do py list(x, x + 1, x - 1 for x in a_list)
with a local db you could do ```py
import sqlite3
conn = sqlite3.connect('STRING HERE')
conn.execute('CREATE TABLE IF NOT EXISTS scores (primary_key INT PRIMARY KEY NOT NULL, extra_data TEXT NOT NULL)')
conn.execute('INSERT INTO scores VALUES (?,?)', (1, 'test'))
conn.commit()
conn.close()
forgor 💀
!e
print(list(x + i for i in range(-1, 2) for x in a_list))```
#bot-commands
what are you trying to do
also incorrect syntax
and you need to zip it
print(*(x+i for i,x in zip(range(-1,2), a_list)))
what do you mean incorrect syntax, it worked as expected
this?
!E
a_list = [1, 2, 3, 4]
print(list(x + i for i in range(-1, 2) for x in a_list))
@quaint epoch :white_check_mark: Your 3.11 eval job has completed with return code 0.
[0, 1, 2, 3, 1, 2, 3, 4, 2, 3, 4, 5]
How would it not be valid?
That wouldnt be a good example especially inside an asynchronous environment
!pypi aiofiles
👍
how can i make it so that the bot only allows commands to be send in one channel
anyone?
@discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks").
These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event.
If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error").
for you it would look like something along the lines of
def some_check(ctx) -> bool:
return ctx.channel.id == someidhere
because the callback won't ever trigger, does it print ok?
ya this tha problem it didnt ! how i deal with this
not printing ok
how i trigger them
but i dont know how many buttons command will create !
''' let this be inside the for loop '''
button = discord.ui.Button(...)
button.callback = self.callback
buttons.append(button)
self.add_item(button)
''' then inside the callback you can remove the loop that checks for the buttons '''
''' remove the following part '''
for i in self.buttons:
if i == buttons
''' remove this part and unindent the rest of your code '''
this would be actually cleaner
@limber bison .
got it
great!
let me try thanks
sure
how do i mention a channel?
property mention```
The string that allows you to mention the channel.
can someone help me pls. I coded a discord bot but visual studio dont know "import discord , and from discord.ext"
is says no definition for discord
it doesn't matter he is not your boss, you're the boss bro
lol
yeah but he doesnt run then
You've probably got the wrong interpreter selected. The best way to handle these issues is by using venvs
uh i know nothing about that. i just ignore him and run
i used the python version
I would just use sublime text editor and windows power shell
windows power shell 💀
it's actually pretty good, version 7 atleast
test the import and make sure you got them installed...visual studio could be using a different version of python then the one you installed the packages on for discord
hey if your on windows it's not horrible
ah fuck iam dumb ass fuck i didnt even installed power shell thank you all for your help
yea you'll def want to get powershell going vs the regular command line
You sure? If you did, you wouldn't be getting the error
Set up a venv just to be sure
Setting up a venv is always good practice and you should do it always anyway
agree
this is most definitely your best solution. sometimes visual studio code selects the wrong interpreters or you've mistakenly selected one
how
or you've installed discord.py on the wrong interpreter
yea to see for sure you can goto where python is installed and check the directory that holds installed packages
python is not working when i wanna open it "failture, please enable dc overlay"
can someone help ,me
.
Can you send the error message?
sure
Look dms
Here @sick birch
Sorry for dm
This is a pycharm issue, maybe ask in #editors-ides?
discord.abc.Messageable.fetch_message(msg_id)
What am i doing wrong ?
K thanks you
error : Missing a positional argument 'id'.
fetch_message is a method of something that inherits from discord.abc.Messageable
For instance, a discord.TextChannel, or a discord.VoiceChannel
ah i see thanks
how to whitelist someone on my bot by doing .whitelist (id)
you'd require a database and a command that manipulates your database
and then an on_command event to check if the command invoker is actually whitelisted or blacklisted
how to fix anyone know?
maybe commands.permissions instead of commands.has.permissions ?
!d discord.ext.commands.has_permissions
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
fixed it i need to do has_permissions
how to whitelist someone on my bot by doing .whitelist (id)
Ashley already told you?
when?
oh
😅
but how do i do cuz i dont understand..
to_d["fields"] has less than 4 elements
Access a valid element, so something less than 3
Yes
Try 1, then 0
If both of those don't work it's an empty list
Hello how do i make a bot only work when you whitelist
Example:
.whitelist @slate swan
bot: succesfully whitelisted Lordoxez into ids.json
prsnc = ["Ping me!", f"On {str(len(bot.guilds))} servers!", "Crypto Stuff will be added soon 😶", "wtf is that smell?"]
@tasks.loop(seconds=120)
async def change():
act = discord.Activity(type=discord.ActivityType.watching, name=random.choice(prsnc))
await bot.change_presence(status=discord.Status.do_not_disturb, activity=act)```
it's not changing the presence, can somebody help me?
id = str(message.author.id)
if id in data:```
add something like that to every command
okay,but what do i put after if id in data: the json?
Theme??
wdym
yo
within a check function of apy @bot.event async def on_message(message):function
am I allowed to make the check function an async function?
cause i wanna check the user ID given in a message
Just use the check/code that's inside the function inside the event?!?!?
i am
its just on discord.py docs the check function u see there isnt async
I'd say the easiest way to find out is to try it
Just use the object the event bot.wait_for returns and then do asynchronous tasks inside of a command if thats what you're looking for?
oh i didnt know that yields
i thought it just checks if true or false for the check function
Yes?
the check kwarg takes a callable that returns bool but you can just check the object Bot.wait_for returns which it depends on which you specified
ok thanks
Hello how do i make a bot only work when you whitelist
Example:
.whitelist @Lordoxez
bot: succesfully whitelisted Lordoxez into ids.json
In this case it would be a message object, but it seems like you're hard coding this functionality, what are you trying to do?
didn’t someone answer this for you already?
no,i just need a part of code then i can understand
run cmd, get user id add it into json or db wtv you are using then u need to check if they exist in said db when they run a cmd
Should use a db
100%
nvm i finded for myself https://youtu.be/88kt2HzXYbw
Short video on making a discord bot that you can use to make a whitelist system!
𝘽𝙖𝙘𝙠𝙜𝙧𝙤𝙪𝙣𝙙 𝙈𝙪𝙨𝙞𝙘!
https://www.youtube.com/watch?v=ge3GT8_un6s
ok lol
the bot waits for a middle man to paste this format (screenshot)
so its checks if it contains bits of the format
at the same time, it checks if the user ids provided exist in case they made an error (but that part needs to be in an async func)
once that stuff is verified the bot moves on to check other following stuff
That code is honestly quite bad and thats bot what you wanted exactly either
yeah i see..
🥲
is it ok to use a while loop within a py @bot.event async def on_message(message): that verifies if a```py
msg2 = await bot.wait_for('message')
im not using check cause i want to do stuff like `bot.get_user`
ah but the while loop is prob not an async thing
if you carefully use it sure, while loops work fine in async if the code inside it isnt blocking, you just have to worry about the normal stuff like getting into infinite loops
Hello I’m trying to make a machine learning bot for a discord. I’ve made it with basic commands- how do I make sure it saves when I input commands in python? How do I import to discord. I’ve already imported a bot with predetermined if/else commands before
ight thanks
I don't see the point
a while True with a wait_for is functionally equivalent to an on_message
anyone sees something wrong
even when ids provided are wrong it moves on
its meant to check user ids exist, if they dont the check isnt meant to be positive
wait_for checks cant be async
ah
then ill return the wait_for message and check the msg there in a while loop, and not use the check
if the person cancels the trade ill verify if the message contains that too to end the loop
id definitely consider refactoring this into a separate function you can call and storing a bot var to keep track of active tickets
your on_message is going to get real complicated if its all being done in one place
so like aiosqlite?
if it could potentially be a long-running ticket (where your bot might restart) sure you can keep track of tickets there
ight, thanks for the advice
Python doesn't do typechecking
!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/latest/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
Thats its type if youre looking to annotate it
If you're asking for the right type hint, then it's commands.Context
discord.ext.commands.errors.HybridCommandError: Hybrid command raised an error: Command 'edit' raised an exception: AttributeError: 'FursonaEdit' object has no attribute 'to_components'
anyone know why
nvm im dumb
i need help with a bot that talks when a new channel is opened and it puts a button saying hi or bye
No documentation found for the requested symbol.
!d discord.on_channel_create
No documentation found for the requested symbol.
ok guess not
!d discord.on_guild_channel_create
discord.on_guild_channel_delete(channel)``````py
discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.
Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
ok ty
i just started python lol
also im trying to make it so after they press the button the bot sends an embed and asks the person to send the persons dev id then it adds them to ticket
Does the rate limit messaging apply to singular messages, or does it apply to the bot as a whole?
e.g I can only edit 1 message 5 times every 5 seconds.
Or can I edit multiple messages
Basically, I'm just trying to say, do messages have individual limits, or does it apply to the bot
Applies to your bot as a whole
Well.. discord isn't a game platform..
😠 Who said it's not
That's the second question you've asked and said "nvm" to lol..
the answer is yes, but I suppose you figured that out already
is there a way i can make it so when i type someones dev id the bot adds the person to ticket
im basicaly making a multi tasking ticket tool
Someone help me use the API
Half and half, you have to take into account bucket ratelimit and global ratelimiting
what is that
Buckets are determined based on a few major parameters used for each endpoint, a ratelimit is dependent on the bucket formed. Let's say I send a message in channel with an id 123, I would access the message creation endpoint via channels/123/messages. That has now become a bucket, so any further messages in THAT channel will take a use off the bucket's ratelimit
For instance, the message ratelimit currently for sending is 5/5s that means in each channel I could send 1 message per second if your library handles bucket ratelimiting
But this is encapsulated by the global ratelimit, meaning you cannot exceed 50 requests a second
So it's a make of half and half, your original question that is.
Reminds me of how people do "Best anti-nuke bot, bans 120members/s"
@bot.command()
async def slots(ctx, amount=None):
slots = ['bus', 'train', 'horse', 'tiger', 'monkey', 'cow']
slot1 = slots[random.randint(0, 5)]
slot2 = slots[random.randint(0, 5)]
slot3 = slots[random.randint(0, 5)]
slotOutput = '| :{}: | :{}: | :{}: |\n'.format(slot1, slot2, slot3)
ok = discord.Embed(title = "Slots Machine", color = discord.Color(0xFFEC))
ok.add_field(name = "{}\nWon".format(slotOutput), value = f'You won {2*amount} coins')
won = discord.Embed(title = "Slots Machine", color = discord.Color(0xFFEC))
won.add_field(name = "{}\nWon".format(slotOutput), value = f'You won {3*amount} coins')
lost = discord.Embed(title = "Slots Machine", color = discord.Color(0xFFEC))
lost.add_field(name = "{}\nLost".format(slotOutput), value = f'You lost {1*amount} coins')
if slot1 == slot2 == slot3:
await update_bank(ctx.author, 3 * amount)
await ctx.send(embed = won)
return
if slot1 == slot2:
await update_bank(ctx.author, 2 * amount)
await ctx.send(embed = ok)
return
else:
await update_bank(ctx.author, -1 * amount)
await ctx.send(embed = lost)
return
Error - undefined variable update_bank
but im not sure how i should define it.
?
I need help w that
Its used as an asynchronous function? If you're asking about its functionality we cant really help much as it depends on your abstractions and its purpose
Well i tried defining it but i got loads of errors like you cannot assign a await function etc
#i did this
update_bank==ctx.author
This is only for 3-4 servers O_O
and its only 1 game per server.
1 edit a second
I think a better alternative would be to move the snake once a user clicks on a button. There should be no ratelimits that way as you're just responding to an interaction, and you should be able to have as many servers as possible running it
i did that for the past 3 prototypes but all my friends said it was so boring.
sheeeesh
What
I agree 😭

So my plan was to make this bot for my friends, in 2 languages.
Java and python just for some experience and learning of syntax
After I do that, I plan on releasing one globally that will fail and only get like 1 server invite 😦
And after I do that 😭 I'll work on a starcraft 2 machine learning bot
not rlly ml but... idk
Why learn only syntax in a language and why Java?
I find it interesting.
I just want to grasp all of them. Know basic syntax
write basic programs, experiment
see what I like, and do it 🙂
Right now I love python for it's simplicity.
I also like C++ because it makes me feel like a professional.
You find being verbose interesting?🤔
You love C++ because of that?!?!?
That was a joke, but I do enjoy C++
Me too!
Oh, in that case, yes that was not a joke.
@client.command()
async def person(ctx):
message = await ctx.send("Please wait while image generates...")
now = datetime.now()
print(f'Person command was used at {now.strftime("%m/%d/%Y %H:%M:%S")}')
r = requests.get("https://thispersondoesnotexist.com/image")
image_file = io.BytesIO(r.content)
file1 = Image.open(image_file).convert('RGB')
file1.save("Img/person.PNG")
file=discord.File("Img/person.PNG", filename="person.PNG")
await message.edit(content=file)
Help please :(
You must pass the file in the file parameter
await message.edit(file=file)

while im at it, why does this
@client.command()
async def person(ctx):
r = requests.get("https://thispersondoesnotexist.com/image")
image_file = io.BytesIO(r.content)
file1 = Image.open(image_file).convert('RGB')
await ctx.send(file1)
Result in this?
Those are 2 separate messages
I'm pretty sure thats how discord formats messages now or always has? Blockingio😩
But why does it send the <PIL.Image.image part instead of just the image
because thats probably the object's repr and a valid url that got embeded, you should use discord.File which expects a bytes like object in its constructor iirc
You have to use the attachments kwarg I think
!d discord.Message.edit
await edit(*, content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
you could delete the last message when the image sends
or use delete_after
asyncio.run() cannot be called from a running event loop
async def input(self, direction: str) -> None:
valid = is_valid(self.previous_direction, direction)
if valid:
self.previous_direction = direction
self.direction = direction
if self.started is False:
self.started = True
while self.lost is False:
await run(self.move)
await asyncio.sleep(1)
async def move(self) -> None:
# Miscellaneous
y_increment, x_increment = self.TRANSLATIONS[self.direction]
# Movement
self.head = (self.head[0] + y_increment, self.head[1] + x_increment)
# Pop tail
self.tail.insert(0, self.previous_head)
self.tail.pop()
# Update self.previous_head
self.previous_head = self.head
# Edit post
await self.post(edit = True)
btw run is imported from asyncio
Why are you using asyncio.run?
to thread an async function
master
Why not just await it? 
it might delay every thijng
asyncio.run also can delay everything
oh
yay it works! thx 🙂
@sick birch I apologize but are you here to help, I'm sorry for bothering you everytime
sure what's up
asyncio.run
creates the event loop, you should use it outside of async functions to start your main function
asyncio.create_task
would be how you add a async function to the event loop without awaiting
I got it.
My new issue is that I'm not able to end the game after it's done.
how do you mean
As in
my main.py file uses a class from a different file, and that different class handles all the logic.
After the player wins or loses, I have to set their game value to None, but my main.py is not able to identify when it's done.
can anyone help me with API's
There is no trigger
if game_value is None:
break
```?
nono
hey, can u help me with this API
which one
{'message': "Authentication failed! The request must include a valid and non-expired bearer token in the 'Authorization' header."}
ooo you're having an issue getting the variable into the relevant file?
me?
No idea ho wto use it
no, Christopher
dang igh
So my issue is, after the game is done. In this dictionary, I have to set their value to None
But that dictionary is in main.py, not in the class file
What's the issue?
yeah, move it to a new file then import it into both files
or put it in the main logic file and import it into main
I'm having trouble having 2 files communicate
What are you trying to do? Seems like an XY problem
Snake.py manages the entire game.
put the variable into the logic file then import snake then you can do snake.dictionary_name to access it
Just import the necessary functions and classes from snake.py
!paste
Hey, can you help me with an API
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.
logic file
That's why the API docs are there, no?
in the snake file
the dict is in main.py
lmao, i dont understand how to use a thing in it
Well, looks like you've got your starting point then
ok
then to access the dictionary you just do snake.dictionary_name
The dictionary isn't just used for snake, it's used for all the other games too
It's used to keep track of their games open
Would that still work?
then i would move it to a config.py or central place that you can import into all of them
you can run into issues with circular imports otherwise
just make sure you dont do from config import dictionary_name because that creates a new object
How to make a function that do something like: Type a command first, the bot replies, and type a message, and bot respond to that message?
use a wait_for
!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.10)"). 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.10)") 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.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
I was confused on your way so I tried something else, and it works but its not efficient
while GAMES_OPEN[interaction.user.id].lost is False:
await asyncio.sleep(1)
GAMES_OPEN[interaction.user.id] = None
while loops are blocking fyi
they block everything?
right
wouldn't the asyncio.sleep return control back?
yeah nvm didnt see that
but I don't see why you would need a loop to just manipulate values
I want to make my bot so people have to authorize the bot and I can make them join severs
Just like a restore bot
well what do you mean
do you mind explaining in detail
Alright, so they verify and authorize the bot, doing that gives us access to pull them to our new server
yes
you mean like grant access to their account?
oh yeah that's something to do with oauth2 grant
How would I code that Lmao
if i'm correct
well overral you would need the grant for it, when they authorize access to their account
i believe its by using an access token
How do I code it lol
i can try to help you, i'm intrigued by this
Bet
well you would obviously need to use json and sessions
what ide do you use, visual studio code or pycharm?
Pycharm
import requests
url = "https://discord.com/api/v8/channels/893363878728192041/messages"
data = {"content": "hi navi"}
header = {"Authorization": f"Bot {token}"}
resp = requests.post(url,data=data,headers=header)
print(resp.status_code)
Guys why i am getting 404 status code?
its just the token i think no need to add Bot
I got 401 status code now
check ur token and credentials
My token is correct
check link then idk i haven't used discord api directly before 
and in class so can't check docs
make sure that your bot the permissions to send messages in that specific channel
Bot is required
I am sending dm not to channel
nice
So?
I got 404 status code
Alright, so I have this modal:py class get_ad(discord.ui.Modal): def __init__(self): super().__init__( discord.ui.InputText(style = discord.InputTextStyle.long, label = "Enter your Advertisement", placeholder = "Maxium of 250 characters, 5 lines.", max_length = 250), title = "Advertisement", timeout = None) async def callback(self, interaction: discord.Interaction): await interaction.response.pong() and when open it using ```py
modal = get_ad()
await ctx.send_modal(modal)
InteractionResponse .pong isn't even a thing
oh wait is that py-cord lmao
Yeah
is ctx an interactionResponse?
Hi
Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use input to read a string and float() to convert the string to a number. Do not worry about error checking the user input - assume the user types numbers properly.
everyone they you solve the qusetion for me and send me plz ?
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.
Pls help me anyone 🙏
I have n button in list , now i want to to set there callback , like if button possition in list is 0 then send 0 on discord so on ! How can I achieve?
Not found 
!d discord.NotFound
exception discord.NotFound(response, message)```
Exception that’s raised for when status code 404 occurs.
Subclass of [`HTTPException`](https://discordpy.readthedocs.io/en/latest/api.html#discord.HTTPException "discord.HTTPException")
Bro i not using dpy
Yeah but that's the same exception 
I would send you links but my google searches on Italian sites 
401 is invalid credentials
But i got 404
It's not found 
can be both the channel or the token
I am trying to dm through this code
i suggest you to try some easier API, since discord ones are pretty advanced, so you can learn requests and responses 
I replaced my Id with channel ID and it worked but i want to dm
LMAO the id of an user is not the ID of his channel
When you use a bot and do await User.send you call the send method that before sending the message to the user it creates a DMChannel, once the channel is created the bot can send the message
How to create dm channel?
Hi
can i have / commands only for a particular channel instead of a server or a particular grp of people
like i want the command only for admin
I have #admin channel and @admin role in my server but i dont want that / command to be known by others
!d discord.ext.commands.has_permissions
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
@commands.Cog.listener()
async def on_message_edit(self,before,after):
if not after.author.bot:
if before.content != after.content:
embed=nextcord.Embed(title="Message edit",description=f"Edit by {after.author.mention} in {before.channel.mention} {before.jump_url}", color=0xfd9fa1, timestamp=datetime.datetime.utcnow())
fields=[("Before",before.content,False),("After",after.content,False)]
for name, value, inline in fields:
embed.add_field(name=name,value=value,inline=inline)
chan = self.bot.get_channel(933978399280599080)
await chan.send(embed=embed)
what does this error mean?
before.content or after.content was none
For channels i think that you will have to create a custom check, this is the structure:
from discord.ext.commands import check, CheckFailure
from discord import Context
class MyCustomCheckError(CheckFailure):
def __init__(self, message):
self.message = message
super().__init__(message=self.message)
def my_check():
def predicate(ctx: Context):
if ctx.author.id != ctx.guild.owner_id:
raise MyCustomCheckError("only the owner of the guild can execute this command")
return check(predicate)
i want for slash("/") commands
just go to server integrations and remove permissions from everyone to use that command
that will just leave it to admins and owners
oh smart
it's the same just use the Interaction instead of context and discord.app_commands.check, discord.app_commands.CheckFailure instead of the ones that i used
!d disnake.Embed.check_limits lmao disnake is on another level
check_limits()```
Checks if this embed fits within the limits dictated by Discord. There is also a 6000 character limit across all embeds in a message.
Returns nothing on success, raises [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") if an attribute exceeds the limits...
Guys is it possible to make a api in my discord bot
Like a api using flask when anyone hit that api my bot sends a message
How to make?
create the api using flask, on the request invocation use the discord REST API and create a message
why is the time shifted?
Idk how to use discord REST api
how do i fix this? i just updated the discord.py to the newest version
and its showing this now
now it's InteractionResponse, but it is edit_message without original, you can get the InteractionResponse object by Interaction.response
!d discord.Interaction.response
Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using followup instead.
!d discord.InteractionResponse.edit_message
await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by editing the original message of a component or modal interaction.
i have noething that edits the original message
or edits a message at all unless deleting counts as editing
bruh the error is saying that you are trying to use the edit_original_message method with an Interaction object 
Guys how i can dm a user with its id in dpy?
if .send @rich otter
member: discord.member, arg
await member.send(arg)
@commands.command
async def send(self, ctx, member: discord.Member, arg)
await member.send(arg)
--note this is for cogs just remove self if its not in a cog
something like this?
Bruh what package are you using 
what is that from discord.commands import Option? that doesn't exist
https://github.com/Rapptz/discord.py
How can I get used from it iD?
it used to work
!d discord.commands import Option
the user that send or user that was sent to
2.0
2.0 is the new
i want the old one, when you coded that
Bruh Option didn't exist in 2.0 neither
and the commands module is child of the ext module
Well, the code is wrong 
i guess so
ok so then i need help please
how would i make the / option type of command
so it shows options
self, interaction: discord.Interaction, opt: Option(str, choices = ["Tickets Channel","Commands Channel","Verification Channel","Joins Channel"], required = True),
!d discord.app_commands.AppCommand.options
A list of options.
Pardon?😅
#discord-bots message
Use this gist
for the user that sent do print(ctx.author.id) if your trying to do the user that it was sent to do print(member.id)
thank you
YES THIS IS WHAT I WAS LOOKING FOR TOO THANK YOU VERY MUCH
async def setupchannels(self, interaction: discord.Interaction, opt: discord.app_commands.AppCommand.options(str, choices = ["Tickets Channel","Commands Channel","Verification Channel","Joins Channel"], required = True), channel: discord.TextChannel):
TypeError: 'member_descriptor' object is not callable```
is interaction the member_descritpor
app commands are a mess with d.py, do you want to add an OptionList? or that the parameters of the command are showed when you type /command ?
What's this
You're trying to add options to your slash command?
yes
i am trying to add a optionlist
yup this one
You can take a look at their examples
https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/transformers.py#L80-L89
examples/app_commands/transformers.py lines 80 to 89
# In order to support choices, the library has a few ways of doing this.
# The first one is using a typing.Literal for basic choices.
# On Discord, this will show up as two choices, Buy and Sell.
# In the code, you will receive either 'Buy' or 'Sell' as a string.
@client.tree.command()
@app_commands.describe(action='The action to do in the shop', item='The target item')
async def shop(interaction: discord.Interaction, action: Literal['Buy', 'Sell'], item: str):
"""Interact with the shop"""
await interaction.response.send_message(f'Action: {action}\nItem: {item}')```
alrighty thank you both
!e print(f"{number:03}")
@limber bison :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'number' is not defined
!e print(f"{7:03}")
@limber bison :white_check_mark: Your 3.11 eval job has completed with return code 0.
007
then don't use replit 
Ok
Now I'm going in vs code
Why are you using discord_components
How to tag someone with discord.py in message.
Example
@slate swan
Embed:
Here's your daily reward!
DM me /claim to claim ur rewards
<@id> or user.mention
no..i mean tag the user who uses the bot
on_command_error is a global error handler... not a command specific one
what should i do
Then what I use
ctx.message.author.mention```
!d discord.ext.commands.MissingPermissions
exception discord.ext.commands.MissingPermissions(missing_permissions, *args)```
Exception raised when the command invoker lacks permissions to run a command.
This inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
you can access the permissions missing through the exception obj ^
No need for the message attribute
!d discord.ext.commands.Context.author
Union[User, Member]: Returns the author associated with this context’s command. Shorthand for Message.author
@unkempt canyon is exclusive to this server, but you can check out its src by using !src in #bot-commands
Who can tell me how to make a button that removes the last message?
mentions in Embeds are not allowed, you can only add them in fields or description but the user will not receive any ping or notifications
Member.mention
Who needs information what is written here:
"Only you can see this message, click here to remove it"
!d discord.Member.mention
property mention```
Returns a string that allows you to mention the member.
@app_commands.choices(channelchoices = [
Select(name = 'Tickets Channel'),
Select(name = 'Commands Channel'),
Select(name = 'Joins Channel'),
Select(name = 'Chat Channel'),
Select(name = 'Verify Channel'),
Select(name = 'Vouch Channel')
])
async def setupchannels(self, int: discord.Interaction, channelchoices: Select[int], channel: discord.TextChannel):```
Select is showing up yellow scribbles
Select class is under ui modules, it is not used with commands
Choice wont work
@app_commands.command()
@app_commands.describe(fruits='fruits to choose from')
@app_commands.choices(fruits=[
Choice(name='apple', value=1),
Choice(name='banana', value=2),
Choice(name='cherry', value=3),
])
async def fruit(interaction: discord.Interaction, fruits: Choice[int]):
await interaction.response.send_message(f'Your favourite fruit is {fruits.name}.')```
because it is not choice neither 
.-.
readed choice lowercase sorry, you have to import it
!d discord.app_commands.Choice
class discord.app_commands.Choice(*, name, value)```
Represents an application command argument choice.
New in version 2.0.
x == y Checks if two choices are equal.
x != y Checks if two choices are not equal.
hash(x) Returns the choice’s hash.
from discord.app_commands import Choice?
yup
that fixed it thank you
You can mention them in the embeds description, why say you cant and then say you can?
mentions != pings
cuz I forget to add the descriptions before 

So the components which has the user highlighted can have the mention inside the embed, So the author, the title, the field name and the footer cannot have a mention inside them.
Even if the mention is highlighted, the mentioned user will not receive any ping or notification from the mentions inside the embed
how to make hyperlinks in discord.py?
[test here](link here)
f string?
nope
or format?
it's just like how u do in github
I have the category ID, need to fetch that category to make a channel in.
how would i do that ?
get_channel or fetch_channel
Category ?
categories are channels
Thnx
I wanna make a avatar command that will send a person's avatar
CODE:
@bot.command()
async def avatar(ctx, *, avamember: discord.Member = None):
if avamember == None:
embed = discord.Embed(description='❌ Error! Please specify a user', color=discord.Color.red())
await ctx.reply(embed=embed, mention_author=False)
else:
userAvatarUrl = avamember.avatar_url
embed = discord.Embed(title=('{}\'s Avatar'.format(avamember.name)), colour=discord.Colour.red())
embed.set_image(url='{}'.format(userAvatarUrl))
await ctx.reply(embed=embed, mention_author=False)
Error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url' ```
PLS HELP ME OUT
avamember.avatar.url
hello, im trying to make a ticket bot. my problem is that if someone selects for example report section, then they can't select it again. they have to select something else and then click report. ( as you see there is a checkmark next to report because its already clicked ) how can do that so when someone selects a section, their selection gets removed?
!e f"{365:02}"
@limber bison :warning: Your 3.11 eval job has completed with return code 0.
[No output]
!e print(f"{365:02}")
@limber bison :white_check_mark: Your 3.11 eval job has completed with return code 0.
365
how do i convert a exe file to python ???
!e print(f"{5:02}")
@limber bison :white_check_mark: Your 3.11 eval job has completed with return code 0.
05
dont occupy the channel please
#bot-commands
https://cdn.discordapp.com/attachments/343944376055103488/1021383037201678437/unknown.png
hello, im trying to make a ticket bot. my problem is that if someone selects for example report section, then they can't select it again. they have to select something else and then click report. ( as you see there is a checkmark next to report because its already clicked ) how can do that so when someone selects a section, their selection gets removed?
It was changed to display_avatar.url
pls guys i need help on this
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
why tf is this getting a error
url=ctx.guild.icon_url```
literally
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Guild' object has no attribute 'icon_url'
!d discord.Guild.icon
property icon```
Returns the guild’s icon asset, if available.
guyss helppp
interaction.user.add_roles([5673479347694876202358]) @naive briarlike this ?
It is not in the for of a link
or ([discord.object(id)])
Then get the url from it
!d discord.Asset.url
property url```
Returns the underlying URL of the asset.
In embeds.0.thumbnail.url: Scheme "<property object at 0x00000289e833e610>" is not supported. Scheme must be one of ('http', 'https').
I am getting this error
because I coded this:
embed.set_thumbnail(url=discord.Guild.icon)
You have to get the url from it first
embed.set_thumbnail(url=guild.icon.url)
Its still a error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'url'
you do that by removing that item from the view and editing the msg with the new view
to remove you can use Select.options which returns a list of options
Then the guild has no icon
how to add single role to a member
await member.add_roles(*role)
await member.add_roles([4567498426694927]) this is how ?
First you gotta get the role object - role = guild.get_role(4567498426694927) and then await member.add_roles(role)
Just the ID
await member.add_roles(123)
Or role
oh you can do it with an id?
Can't remember 
discord.object(34564363436546) this will work ?
no idea
thanks, i did it only by doing:
await interaction.message.edit(view=self)
yea that's exactly what you had to do
nope
await interaction.user.add_roles([interaction.guild.get_role(1021123493804384266)])
this ?
shouldn't be a list
await interaction.user.add_roles(interaction.guild.get_role(1021123493804384266))
this right
dont say no pls
its correct
But error prone
How can I disconnect a member from vc ?
!d discord.Member.move_to when you put None to the channel parameter the member will be disconnected from the channel
await move_to(channel, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Moves a member to a new voice channel (they must be connected first).
You must have [`move_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.move_members "discord.Permissions.move_members") to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
Changed in version 1.1: Can now pass `None` to kick a member from voice.
Got it
what is this error how i slove it
I have this, ```py
await commands.ColourConverter().convert(ctx, "#fff223")
you can simply put the hexcode as 0xhexcode without the octothorpe
every extension needs to have a setup function
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(CogClass(bot))
.title() method is useless, it capitalizes letters after apostrophes so i get stuff like Don'T
how fix 😤
!e
print("don't".title())```
@dull terrace :white_check_mark: Your 3.11 eval job has completed with return code 0.
Don'T
which is rule 7
Yeah, but I'm getting the hex string from an input. So I'm not sure how to.
nevermind found the answer, can use capwords()
Nice
I'm brain dead lmao
!e
import string
print(string.capwords("don't"))
@dull terrace :white_check_mark: Your 3.11 eval job has completed with return code 0.
Don't
if it's inside a command, just typehint the argument with discord.Colour
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
What to do with xml code
you can get the color using int("hex string",16) if thats what you need
<This is xml code or wot?>
Bruh
Ok nothing
?
@slate swan i was saying what to do with that async def setup(bot: commands.Bot) -> None:
put it at the end lines of your extension(s)
Ok
How to delete the original response while making a followup ?
!d discord.InteractionResponse.delete_original_response
wha-
!d discord.Interaction.delete_original_response
await delete_original_response()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the original interaction response message.
This is a lower level interface to [`InteractionMessage.delete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.delete "discord.InteractionMessage.delete") in case you do not want to fetch the message and save an HTTP request.
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'ApplicationContext' object has no attribute 'delete_original_message'
py-cord?
indeed
why don't people state their libs when it's not dpy smh
well, i switched yesterday forgot to mention : (
it's fine lol
here you go -> https://docs.pycord.dev/en/stable/api.html?highlight=delete_original#discord.Interaction.delete_original_message
also, use an interaction not appctx
that method won't work with an AppCtx

lemme see how pycord's slashes work
im so confused where is extension(s)
try typehinting ctx with discord.Interaction
and why would you ever switch to py-cord lmao, that's like so much worse
cogs.
nah, i found out, you gotta store the message and delete that lmao with that
ew py-cord
jesus, the indentation, it needs to be outside the cog but inside the file
idk ran into a problem with dpy which no one was experiencing, i updated the version, it broke a lot of stuff, py-cord seemed to solve both
how to check that if the server has a icon and if it, then continue
!indent
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
yo can u help me out
lmao py-cord ain't a high-fi shit either
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
icon = ctx.guild.icon.url if ctx.guild.icon else None
if icon is None:
"No guild icon"
very very much confusing
nice
lol you were late i figured it out
I would still recommend to revert to dpy but ok
but thanks
rude nice
Oh, cool! Should the # be a part of the string?
no
@slate swan do you have any step that i can understand properly
hmm would recommend learning python
class YourCogIWhichIDontCareAbout(commands.Cog):
...
async def setup(bot):
...
also learn python
im learning it slowly slowly im new
now where i have to paste it
same place in cog?
smh
hm
btw I was wondering something.
if we do not make discord command a async function then how would it behave?
Like it would only run one command each at a time?
same happens with me
let the setup be at the end of the cog file but outside the cog
no that's not how discord's formatting works
timestamp = f"<t:{datetime.datetime.utcnow().timestamp()}:R>"
this is represented with utils.format_dt as
timestamp = discord.utils.format_dt(datetime.datetime.utcnow(), style="R")```
😐 before you reference this in your embed
how it is possible😂
how i can do this outside the cog file
no😂
like what
so what to do now
dude...
class Cog(...):
def __str__(...):
...
async def setup(...):
...
here ya go
now add it to the embed too
^
right
yeah
that's how it'll work, you'll have to add the duration of time after which the giveaway will end create a timestamp out of that
HHMMSSFormat nice function name
(utcnow() + timedelta(seconds=duration_seconds)).timestamp()
and timedelta is imported from datetime
!e
duration_seconds = 1069
import datetime
now = datetime.datetime.utcnow()
delta = datetime.timedelta(seconds=duration_seconds)
future_time = now + delta
print(future_time.timestamp())
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
1663600633.321189
easy as that
Hello how do i make a bot only choose a mine?
Like when i do .mines 1 i want the bot to choose only 1 mine
This is my attempt
a = random.choice([0, *range(1,5)])
b = random.choice([0, *range(6,10)])
c = random.choice([0, *range(11,15)])
d = random.choice([0, *range(16,20)])
e = random.choice([0, *range(21,25)])
@discord.ext.commands.guild_only()
@bot.slash_command(name="mines", description="Predicts Mines for a lordoxez game")
async def mines(ctx, bombs, round_id):
1 = a
You have to add the timedelta to it before making timestamp from it
timestamp = discord.utils.format_dt(
datetime.utcnow() + datetime.timedelta(seconds=duration_seconds),
style="R",
)
for numbers we use range(x) what for capital ABCD.. ?
If it's unused, ye
Hello how do i make a bot only choose a mine?
Like when i do .mines 1 i want the bot to choose only 1 mine
This is my attempt
a = random.choice([0, *range(1,5)])
b = random.choice([0, *range(6,10)])
c = random.choice([0, *range(11,15)])
d = random.choice([0, *range(16,20)])
e = random.choice([0, *range(21,25)])
@discord.ext.commands.guild_only()
@bot.slash_command(name="mines", description="Predicts Mines for a lordoxez game")
async def mines(ctx, bombs, round_id):
1 = a
weird question, but how would you add "creation of discord bots" in a professional way in a resume? 🤔
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.
Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
I said it's datetime.timedelta not datetime.datetime.timedelta
!e
from datetime import timedelta
print(timedelta(seconds=10))
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
0:00:10
Let's just import timedelta
from datetime import timedelta
...
timestamp = discord.utils.format_dt(
datetime.utcnow() + timedelta(seconds=duration_seconds),
style="R",
)
🫠
anyone know any youtube vidoes on how to make a ticket system with discord.py
bruh it's the easiest discord bot project so far 
https://github.com/ifisq/discord-ticket-system this is an example, you can find more on github
A ticketing bot that I wrote in python for my Auroris Development server. Follow us at https://twitter.com/aurorisdev - GitHub - ifisq/discord-ticket-system: A ticketing bot that I wrote in python ...
this is the "giveaway"?
ctx.guild.name or inter.guild.name
!d discord.TextChannel.create_invite
await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates an instant invite from a text or voice channel.
You must have [`create_instant_invite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_instant_invite "discord.Permissions.create_instant_invite") to do this.
that is an hyperlink, you will do it like you do in a markdown file text
you don't need to put the * 
you didn't add the f before the string
!fstrings
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.
.
you put the text in the square brackets and the url in the parentheses
with an invite 
Anyone know why I’m recieving this error?
Code:```py
async def on_guild_join(self, guild: discord.Guild):
print(f"I was invited to {guild.name} - ({guild.id}). It has been added to the database.")
db = self.cluster["Aziel"]
collection = db["Main"]
data = {"_id": guild.id, "prefix": "!"}
collection.insert_one(data)
**Error:** https://paste.pythondiscord.com/siqovomodo
*For content, I’m using mongodb.*
with buttons?
This is an awful example
i need a good example
I picked up the first one that i found, i told you that you can search others, there are tons of them on github
Hello, would someone help me how to program the discord bot?
you'll have to look at examples and guides and read the docs tbf
Seems like it either can't connect to the database or you just need to use async wrapper (you do need to use it anyway)
wdym use an async wrapper
Pymongo isn't async is it
Honestly I don't know async wrappers for mongo but imma look them up rq
!pypi motor you need to use this I think @mental hollow
yeah I’m using motor
Then collection.insert_one should be awaited?
tried that
it was purely an IP issue
anyone knows how i can make a music play command ?
spotify or youtube
or smth else
I use this commands twice in two different places and it sends them both at the same time
@bot.listen()
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send(
ctx.message.author.mention + " **You do not have the __`Administrator Permission`__ to use this command.**")
@bot.listen()
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send(
ctx.message.author.mention + " **You do not have the __`Manage Messages Permission`__ to use this command.**")
the MissingPermissions exception has a .missing_permissions attribute containing a list of whatever permissions were missing (e.g. 'administrator' or 'manage_messages'), you can format your bot's response based on that rather than having two on_command_errors
Why wouldn't?
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
Even if you arent using youtube as your source for music it would be a problem getting all the licenses of each song you play
ok
RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(music_cog(bot))
what is that error ?
The setup function is now an async function and discord.ext.commands.Bot.add_cog is also an async method
ok so what do i do ? how do i fix it ?
any way to give Colors in discord.Colours as an OptionChoice ?
Upon the calling of the method given you await its return value which is a coroutine and then make the setup function an async function?
Hey! I was looking for some help!
Here is my code:
https://hastebin.com/oyoyimixaz.sql
I was wanting so the only person who can interact with the buttons is the person who ran the command. How would i do that?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
idk what you mean
I think you should have a grasp of that knowledge as this library does use asynchronous abstractions?
?
You would pass the Member object to the View's constructor(__init__)
where and how would i do that
You have been ratelimited by the Discord REST API, Use the command kill 1 in your terminal to kill your container that also changed your IP
?
thank you
Just don't use replit
You can probably expect a hexcode and convert it into the object, iirc the constructor of discord.Colour can accept a hexcode
I used to convert it with int with base 16
how can i restart my bot using a cmd
yeah, but i think i would need to make the whole list myself right, to stay within the domain of the colours available ? and because no one would search up hexcodes anyway
!e py print(int("ffaaff", 16))
@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
16755455
It depends what you mean by restart
It depends, What?
refresh bot
Elaborate
what ?
?
like i wanna shut down the bot then restart it ,just like a phone
Do you want to kill all the process or just the WS connection?
Anyone knows how to fix this ?RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited bot.add_cog(help_cog(bot))
where and how would i do that
I've already helped both of you? I'm not willing to spoonfeed either
!async
Concurrency in Python
Python provides the ability to run multiple tasks and coroutines simultaneously with the use of the asyncio library, which is included in the Python standard library.
This works by running these coroutines in an event loop, where the context of the running coroutine switches periodically to allow all other coroutines to run, thus giving the appearance of running at the same time. This is different to using threads or processes in that all code runs in the main process and thread, although it is possible to run coroutines in other threads.
To call an async function we can either await it, or run it in an event loop which we get from asyncio.
To create a coroutine that can be used with asyncio we need to define a function using the async keyword:
async def main():
await something_awaitable()
Which means we can call await something_awaitable() directly from within the function. If this were a non-async function, it would raise the exception SyntaxError: 'await' outside async function
To run the top level async function from outside the event loop we need to use asyncio.run(), like this:
import asyncio
async def main():
await something_awaitable()
asyncio.run(main())
Note that in the asyncio.run(), where we appear to be calling main(), this does not execute the code in main. Rather, it creates and returns a new coroutine object (i.e main() is not main()) which is then handled and run by the event loop via asyncio.run().
To learn more about asyncio and its use, see the asyncio documentation.
i didnt understand what you meant
What did you not understand exactly?
everything
he said, you should start by learning about asyncio to which i tagged you
i didnt get that from his explanation
i still dont know what to do
Should start by searching asyncio on yt and eventually read the docs here https://docs.python.org/3/library/asyncio.html
await function()
If you need a list of good resources check here: #discord-bots message
and how do i add this to it ? bot.add_cog(help_cog(bot)) ?
You make setup an async function?
Its a rhetorical question?
damn these are some good resources
I know right, ive used them allot through my journey in python
where would i put it
lmao guess they gonna be used by me a lot too now
you use words i dont even know
Thats nice, you should also check out pythons docs which i didnt really do, but now i do.
how do i put buttons under each other instead of next?
mh, I'll watch the async thing too 👀
yeah i am waiting for the release of stable 3.11, it has a lot of features i need, i had some issues with it so had to stick to 3.10
It gives you a good solid understanding of concurrency and the asynchronous implementation of asyncio in python
Which features? Speed, better errors? I'm mostly excited about using the star unpacked(*) used on iterables in for loops e.g
for a in *b, *c:
...
haha same, unpacking is what i need too
Exception groups and the Self type look nice as well
where would i find the docs for what i am tryin g to do
I've always wanted to understand the async module more deeply
Well then you're in luck as it also shows the history of asyncio in python. Yep thats how deep it goes!
🙏
havent looked into them, what i was looking forward to was better error indication, speed and unpacking.
I was mostly interested in speed
how do i put buttons under each other ?
Hey! I was looking for some help!
Here is my code:
https://hastebin.com/oyoyimixaz.sql
I was wanting so the only person who can interact with the buttons is the person who ran the command. How would i do that?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
You’d pass down ctx.author from your command to your view
where and how?
Your view would take a member parameter
You’d have an interaction_check that checks if interaction.user == self.author
Return true if yes return false if no with an optional ephemeral message
Your view's constructor(__init__)*
"self" is not defined
Did you just pasted Robin's code to yours?
somewhat
how do i put buttons under each other ?
Pass the row kwarg
ah just enter ?
If we want to be pedantic. Though we needn’t answer a question with more questions
Hm?
I wouldnt say my correction raises any more questions over your answer.
i dont 100% understand
point proven
!d discord.ui.View.interaction_check
await interaction_check(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.
This is useful to override if, for example, you want to ensure that the interaction author is a given user.
The default implementation of this returns `True`.
Note
If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.on_error "discord.ui.View.on_error") is called.
so, i now have something that works. But when a random person clicks the button i want it to ping them adn such but it pings the button owner
How would i fix that:
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Instead of ctx.author.mention, use interaction.user.mention to mention the user clicking the button
I'd also suggest responding to it like you would an interaction, so you can make it emphemeral
Like
await interaction.response.send_message("This is not your Button!", ephemeral=True)
<3 thank you
guild = "whatever you want it to be"
hey guys do someone know how to add a url leading to a file in my bot's folder? Cuz it gives me this error In embeds.0.image.url: Scheme "assets/motivation.png" is not supported. Scheme must be one of ('http', 'https').
To use images in embeds, you first need to load them as a file, then put an atttachement:// uri as the image url
file = discord.File("assets/motivation.png")
embed = discord.Embed()
embed.set_image(url="attachement://motivation.png")
await ctx.send(file=file, embed=embed)
tysm brother. Will try it
u can only react to messages with on_message yh?
no way to do it in a command right
You can still access the message object, so yes, you can.
!d discord.ext.commands.Context.message
The message that triggered the command being executed.
Note
In the case of an interaction based context, this message is “synthetic” and does not actually exist. Therefore, the ID on it is invalid similar to ephemeral messages.
ok thanks
the bot sends an embed saying type dev id and once the person sends the dev id the bot adds them to ticket thats all i need PLEASE HELP
What do you mean by ticket? It's just ID no such thing as developer ID
yeah liek copy the persons id
and paste it then the bot adds them to the channel
this is what i have
import discord
client = discord.Client(intents=discord.Intents.default())
class YourBetterClassName(discord.ui.View):
def init(self):
super().init()
self.value = None
@discord.ui.button(label='B', style=discord.ButtonStyle.green)
async def a(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('Works', ephemeral=True)
self.value = True
self.stop()
@discord.ui.button(label='A', style=discord.ButtonStyle.grey)
async def b(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('Works', ephemeral=True)
self.value = False
self.stop()
@client.event
async def on_guild_channel_create(channel):
await channel.send(view=YourBetterClassName())
if anyone can add on to it thatll be greatly appreciated
!d discord.TextChannel.set_permissions
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to do this...


