await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
#discord-bots
1 messages · Page 315 of 1
ahh I see
how can you change a view after the 15 minute,
Im having an issue here #1164726548264394892
In my on_raw_reaction_add can I remove the reaction of the user who added the reaction?
@whole shoal u ever figured this out
Im having the issue that when i click a button to edit a message after 15 minutes I get the error Invalid Webhook Token u had that issue like 5 months ago
Yes
how
!d discord.Message.remove_reaction 🫠
await remove_reaction(emoji, member)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Remove a reaction by the member from the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji).
If the reaction is not your own (i.e. `member` parameter is not you) then [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages) is needed.
The `member` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake) abc.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) instead of `InvalidArgument`.
should ping me
Where?
channel got locked
its about the error 401 Unauthorized (error code: 50027): Invalid Webhook Token
I know a lot of ppl ran into this error but I never seen anyone found a fix to it
Apparently it was a Discord Issue like 2 years ago
-_-
don't interaction responses freeze after 15 minutes or something like that
or am I just thinking of the ephemeral ones disappearing
!d discord.Webhook.send
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
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/latest/api.html#discord.File) object.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#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) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects to send.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
Okay then
Oh it just loaded
I'd suggest you to respond with interaction.response.edit_message directly instead of deferring the interaction and editing the stored message
elaborate
Elaborate what?
instead of doing interaction.response.defer + view.message.edit in ArticlePaginationView, you should directly use interaction.response.edit_message inside update_message
can't really elaborate more than that
Don't work either
what was the code that you tried?
@commands.Cog.listener()
async def on_guild_channel_create(self, channel):
async with self.bot.db.execute("SELECT threshold FROM ban WHERE guild_id = ?",(channel.guild.id)) as cur: check = await cur.fetchone()
async for i in channel.guild.audit_logs(limit=None, after=datetime.now() - timedelta(seconds=5), action=discord.AuditLogAction.channel_create):
await self.bot.db.execute('''INSERT INTO banaudit (guild_id, users) VALUES (?, ?)''', (channel.guild.id, i.user.id))
await self.bot.db.commit()
counter = 0
async with self.bot.db.execute("SELECT * FROM banaudit WHERE guild_id = ? AND users = ?", (channel.guild.id, i.user.id)) as cur: data = await cur.fetchone()
if data:
counter += 1
if counter == check:
await channel.guild.kick(i.user)
I'm trying to make limits for my antinuke. so if a user makes more channels than what the threshold is it'll kick them but no error
Ok
try debugging it yourself, nobody can reasonably help by just looking at the code
what I can tell though is counter is one variable for every single audit log channel create entry?
and how is creating many channels a nuke
which version of discord.py is installed
Or is that discord.py at all 
!d discord.ui.RoleSelect
class discord.ui.RoleSelect(*, custom_id=..., placeholder=None, min_values=1, max_values=1, disabled=False, row=None, default_values=...)```
Represents a UI select menu with a list of predefined options with the current roles of the guild.
Please note that if you use this in a private message with a user, no roles will be displayed to the user.
New in version 2.1.
hm
do some one knows whats that error?
await interaction.response.edit_message(content="Allows server moderators kick pople from the server", ephemeral = False)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: InteractionResponse.edit_message() got an unexpected keyword argument 'ephemeral'
the code:
class Select(discord.ui.Select):
def __init__(self):
options=[
discord.SelectOption(label="kick",emoji="🦵🏻",description="this kick people from the server"),
discord.SelectOption(label="ban",emoji="✨",description="this ban people from the server"),
discord.SelectOption(label="clear",emoji="🧹",description="this clears messages")
]
super().__init__(placeholder="Select an option",max_values=1,min_values=1,options=options)
async def callback(self, interaction: discord.Interaction):
if self.values[0] == "kick":
await interaction.response.edit_message(content="Allows server moderators kick pople from the server", ephemeral = False)
elif self.values[0] == "ban":
await interaction.response.send_message(content = "Allows server moderators ban pople from the server",ephemeral=False)
elif self.values[0] == "clear":
await interaction.response.send_message(content = "Clear messages in chat",ephemeral=False)
class SelectView(discord.ui.View):
def __init__(self, *, timeout = 180):
super().__init__(timeout=timeout)
self.add_item(Select())
@client.hybrid_command()
async def help_administration(ctx):
await ctx.send("Help administration command menu!",view=SelectView())```
await interaction.response.edit_message(content="Allows server moderators kick pople from the server", ephemeral = False)
line 40^^^^
you pretty much can't edit a message into ephemeral
oh god what is that font
new times roman killin it
whats the api for purge cmd
!d discord.TextChannel.purge
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages) to delete messages even if they are your own. Having [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) is also needed to retrieve message history.
Changed in version 2.0: The `reason` keyword-only parameter was added.
Examples
Deleting bot’s messages...
ty
when im selecting my select menu, it doesnt reset the choice it will stay applied, how can i reset the choices?
I think I did
I mean I found a way around it
Instead of editing the webhook, I just sent the message in same channel
hello, i’ve got a code that contains two tasks.loop, however if multiple users start the loops at the same time then i get an error. is there any way i can avoid this and allow multiple people to start multiple loops whenever?
just replace the view with new view
what error do you exactly get?
it says something about not being able to run 2 tasks at 1 time
!traceback - you should be able to run two tasks at the same time, unless you're running the same task twice
Traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
yes i’m running same task twice
and i want to know how i would be able to
You're not supposed to do that
Not with discord.ext.tasks.Loop, but maybe with asyncio.Task
with asyncio.task i can start two of the same loops at the same time?
Whoops
!e sure
import asyncio
async def work(wid: int):
print(f"[{wid}] started")
await asyncio.sleep(0.5)
print(f"[{wid}] stopped")
async def main():
loop = asyncio.get_running_loop()
loop.create_task(work(1))
loop.create_task(work(2))
await asyncio.sleep(0.6)
asyncio.run(main())
@naive briar :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | [1] started
002 | [2] started
003 | [1] stopped
004 | [2] stopped
Sometimes I forget how asyncio work
lol
Are there any docs on how to use asyncio?
I want to locally host my bot, can I run it without my IDE? don't want to edit, just have the bot running. its fairly lightweight
Don't want to have it always on either
just when Im on my pc i can have it running
What's wrong with using asyncio.create_task instead of retrieving an event loop object to do so? Or better yet, using an asyncio.TaskGroup:
from asyncio import run, sleep, TaskGroup
async def work(wid int):
print(f"[{wid}] started")
await sleep(0.5)
print(f"[{wid}] stopped")
async def main():
async with TaskGroup() as tg:
tg.create_task(work(1))
tg.create_task(work(2))
run(main())
A task group waits for its tasks to finish without you having to worry about it
(if you're using it as a context manager)
!d asyncio
Hello World!
import asyncio
async def main():
print('Hello ...')
await asyncio.sleep(1)
print('... World!')
asyncio.run(main())
```...
Similar names: prompt_toolkit.asyncio, aiohttp.asyncio
Sure as long as Python is installed
im a little confused? so would this work: asyncio.run(incoming(interaction.channel.id, msg.id))? when wanting to run a loop?
Do you want to start the bot on startup automatically? That has some complexity to set up
no
just run it with no interface so that it takes minimal resources
No. What's incoming and in what context are you using it?
incoming is the name of the loop
Is the bot project using a virtual environment of some sort?
async def incoming(channel_id, message_id):
Discord.py's discord.ext.tasks.loop?
this async def incoming(channel_id, message_id):
Is it decorated with @tasks.loop() or is it just an undecorated asynchronous function?
just an undecorated asynchronous function
What does it do? What is it for? Why does it need to run in a loop?
i made it in pycharm python 3.11
ive made a loop to check incoming bitcoin transactions into my wallet, just thought i'd expermient with a side project
What are channel_id and message_id for?
uh so
for these interaction.channel.id, msg.id
What's wrong with using the loop directly? I'm just used to it 🤷
Just a regular project? You should be able to just double click the main file to run it
You will not be using the task group when you're using this kind of background tasks with your bot anyway
it does use discord.py and random.py
It's considered part of the low level API of asyncio and nothing in the high level API accepts a loop as an argument (it's deprecated)
You should be using the high level API for normal stuff
Try seeing if you can run it by double clicking it
If it opens a terminal window and immediately closes, it means an unhandled exception was raised
i think .py files are associated with pycharm so it will auto open pycharm
From an application command?
no a button class
And why is that?
The button is responsible for starting a loop which checks incoming bitcoin transactions into your wallet?
correct
yeah it opens pycharm
!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, name=None)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop).
You can decorate incoming with @tasks.loop() (there's probably an example in the link)
i dont want to use that though because i want to start the same task more than once
This sort of loop calls incoming every set period of time
but i want to start the loop multiple times for different users and with tasks.loop i get an error when more than 1 of the same loop is started
what should I open the .py file with?
Oh, you should just have an infinite while True: loop with calls to asyncio.sleep like this:
async def incoming(channel_id, message_id):
...
async def button_interaction_handler(...):
while True:
await incoming(interaction.channel.id, msg.id)
await asyncio.sleep(delay)
Forgive me for not having learned discord.py components yet, but this should do if you define delay somehow. It's the delay in seconds between each time incoming will be called with that interaction's channel ID and whatever msg.id is
okay thanks
The call to asyncio.sleep is important as this is what lets other stuff do work after letting incoming do its thing every iteration
ill probbaly have py while True: await incoming(interaction.channel.id, msg.id) await asyncio.sleep(delay)
at the bottom of the button class because its the last thing to do after the button has been clicked
Is it critical to continue calling incoming with the same arguments after the bot shuts down due to internet problems or simply after a shutdown?
The interaction might be invalid anyway in that case but I'm not entirely sure. I'm new to this interaction system in discord.py
As a final thought, I'd suggest implementing a way to stop this loop somehow with another button or something, just so you don't have it running mindlessly when you don't want it any longer
when the transaction has been detected ill make it stop the loop
Are you using Windows?
indeed
From the official docs:
asyncio provides a set of high-level APIs to:
- run Python coroutines concurrently and have full control over their execution;
- perform network IO and IPC;
- control subprocesses;
- distribute tasks via queues;
- synchronize concurrent code;
Additionally, there are low-level APIs for library and framework developers to:
- create and manage event loops, which provide asynchronous APIs for networking, running subprocesses, handling OS signals, etc;
- implement efficient protocols using transports;
- bridge callback-based libraries and code with async/await syntax.
You only need to mess with the low level API for OS signal handling, as specified in the docs I guess
I suppose, if you only need to create tasks and not nothing else that would require you to have a loop yourself
Me when I want to use run_in_executor with process pools 😔
You're certainly advised to mess with the low level API to set an event loop policy of your own, that I know
asyncio.run and asyncio.create_task abstract the event loop away from you
asyncio in general manages event loops under the hood
Why are you using asyncio for multiprocessing in the first place?
Maybe ask me when I actually want to
concurrent.futures.ProcessPoolExecutor literally manages process pools for you
That's what I'd use as the executor for the run_in_executor 🤷
I don't know how nicely multiprocessing plays with asynchronous functions
Kind of sounds like a bad idea to let Python schedule OS processes
I've never reach the point when I actually need parallelizm, to be honest 😔
Then open a terminal in your project's main folder and type py your_main_file.py
If you want to reassociate .py files with it, maybe run the installer again and choose the repair option, idk
Opening a terminal and running programs from it is a good idea anyway when you might not have set up logging
Normally, after installing Python using a Windows installer from python.org, all .py files are associated with the py launcher for Windows if you happened to select that option in the installation process, but PyCharm may override that when it is installed after installing Python like this
Question for persitant view
Does it save all buttons from all servers that were created with this view?
persistent views technically don't "save" anything by themselves, anytime your bot restarts you have to recreate and add your views back to the bot
What’s the rate limit on banning members?
For? Libraries handle that
Banning guild members
I know, I’d like to keep the actual rate limit in mind though
There's no fix rate limits given for endpoints
There's the global rate limit of 50/sec and the rest is per endpoint and the library reading the headers as rate limits can change and are not fixed
Doesn’t discord have rate limits on specific endpoints?
They do
And they communicate that rate via the headers, as mentioned, as they are dynamic and not fixed, as also said
You won't get a list of all endpoints and their relative rate limits
Feel free to read https://discord.com/developers/docs/topics/rate-limits
What error is thrown when you’re ratelimited?
An HTTP response with the code 429 (Too Many Requests)
!d discord.RateLimited
exception discord.RateLimited(retry_after)```
Exception that’s raised for when status code 429 occurs and the timeout is greater than the configured maximum using the `max_ratelimit_timeout` parameter in [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client).
This is not raised during global ratelimits.
Since sometimes requests are halted pre-emptively before they’re even made, this **does not** subclass [`HTTPException`](https://discordpy.readthedocs.io/en/latest/api.html#discord.HTTPException).
New in version 2.0.
I didn't know there's an exception in discord.py for this
And for the raw HTTP response, it's in the link I've sent
Is it raised when a method like discord.Member.ban is being rate limited?
I thought these methods normally call asyncio.sleep under the hood until the rate limit is up (before actually sending a request which will rate limit)
testing it myself the headers give me 50/0.019s...?
Still not possible to ban users with unusual DM activty?
I want to create a task that check for suspicious users and ban them from the server
As you show in the screenshot, looks like not
Reading x-ratelimit-limit and x-ratelimit-remaining makes me think you can hit a rate limit 50 times until you're blocked or something
That's the amount of requests remaining
What permissions are required for changing a server vanity invite link?
If you hit that before it has been reset, you'll hit the rate limit of the endpoint
Better to count the number of times you've gotten a successful response up until this point
And before that, there's the 50/sec global rate limit you'll hit
Manage server and obviously admin iirc
Hold on, why is the rate limit response received with 204? That's No Content, not Too Many Requests
Because as the documentation says
you'll get these headers all the time, for every request
So that libraries can keep track of that and not even hit the 429 rate limit
Libraries should not make a request if it knows it will hit 429
Is it standard to send rate limit data per response to an endpoint?
Anyway that's off-topic
And how can i save them forever
Each API on the internet does it differently
Some have fixed rate limits that you don't need headers
Some are like Discord and dynamic, so sending headers is indeed useful
I thought pre-rate-limit notifications were standardized
But I guess Discord is doing its own thing with buckets or something
It is useful but I thought it would've been standardized
if your views are stateless (for example they don't have any parameters in __init__ that change between various messages), you can construct the view and add it to your bot once without using the add_view(message_id=) parameter, and that one view instance will start responding to any message you've sent before with the same custom_id, which is pretty convenient
if your views do need state like a user object (perhaps they own the view and you only allow that person to use the buttons), you will have to store that information along with the message ID onto disk, preferably a database, and then load the objects back during bot startup
.pin
But why 
Because it's Discord
Is there any examples for?
My buttons have all stored in a db with message id and custom id
@bot.command(name="shorten")
async def shorten(self, ctx, url):
shorturl = requests.get(f"is.gd/create.php?format=simple&url={quote(url)}").text
await ctx.send(f"Your link ({url}) has been shortened to: {shorturl}")
my code
my error - Traceback (most recent call last): File "/home/runner/Reaper/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1349, in invoke await ctx.command.invoke(ctx) File "/home/runner/Reaper/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1015, in invoke await self.prepare(ctx) File "/home/runner/Reaper/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 932, in prepare await self._parse_arguments(ctx) File "/home/runner/Reaper/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 839, in _parse_arguments transformed = await self.transform(ctx, param, attachments) File "/home/runner/Reaper/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 691, in transform raise MissingRequiredArgument(param) discord.ext.commands.errors.MissingRequiredArgument: url is a required argument that is missing
anyone know how i can get my bot to send a message after a command is used like discord does when ur in call for too long and it kicks you out
You shouldn't have self as your first argument if you're not in a class
besides the basic one in discord.py's repository no, but i just wrote up a gist about it which includes some examples you can look through:
https://gist.github.com/thegamecracks/0f9ab7ad3982e65ff4aa429acb39cc4e
Gist
A short tutorial on persistent views in discord.py - 1-readme.md
If I connect another instance of my bot to discords API, would the original instance keep running as normal?
i would assume it's fine given that its somewhat common for beginners to accidentally run two instances at the same time and get two responses from a single command, but im not sure if the documentation has any explicit guarantees about running two processes on the same "shard"
well, actual sharding has this statement:
https://discord.com/developers/docs/topics/gateway#sharding
... sessions do not have to be identified in an evenly-distributed manner when sharding. You can establish multiple sessions with the same
[shard_id, num_shards], or sessions with differentnum_shardsvalues. This allows you to create sessions that will handle more or less traffic for more fine-tuned load balancing, or to orchestrate "zero-downtime" scaling/updating by handing off traffic to a new deployment of sessions with a higher or lowernum_shardscount that are prepared in parallel.
how do i set a mobile status to a bot
My understanding of it is that it's actually a bug in Discords API rather than a feature
discord.py doesn't support it, so you'll either need to find a library that does, or edit the source yourself
Changing a libraries source code can be incredibly unstable, so it's not recommended
@commands.Cog.listener()
async def on_guild_channel_create(self, channel):
async with self.bot.db.execute("SELECT threshold FROM ban WHERE guild_id = ?",(channel.guild.id)) as cur: check = await cur.fetchone()
print(f'check = {check}')
async for i in channel.guild.audit_logs(limit=None, after=datetime.now() - timedelta(seconds=5), action=discord.AuditLogAction.channel_create):
await self.bot.db.execute("INSERT INTO banaudit VALUES (?,?)", (channel.guild.id, i.user.id))
await self.bot.db.commit()
print('test')
counter = 0
async with self.bot.db.execute("SELECT * FROM banaudit WHERE guild_id = ? AND users = ?", (channel.guild.id, i.user.id)) as cur: data = await cur.fetchone()
print(f'test2')
if data:
counter += 1
print('test3')
if counter == check[0]:
print('test4')
await channel.guild.kick(i.user)
kicks the user when the threshold is 1 in the database but not when it’s set to any other number, any help? I’m trying to make limits
i would guess it's because you're defining counter = 0 inside your async for loop
soo where do i put it
I am trying to create a HTTP-Only/Interactions-only bot
I got told to use stuff like Aiohttp, Quart, Flask, Fastapi, etc.
but idk where to start, any help?
All i am currently expecting is my bot to be online (with no status icon to make sure its HTTP or Interactions only)
help in #1165166283675930624 message
I still dont understand how to fix:
discord.errors.HTTPException: 401 Unauthorized (error code: 50027): Invalid Webhook Token```
Your webhook link might be wrong
I came to a conclusion its something with
await interaction.response.defer()```
thats whats causing the error
is what I think as of now,
Doesn't look like it
Can you send the whole snippet
Cuz according to the error it looks an issue with your webhook's link
Im not using any webhooks
Then its a followup ig
and if I dont use
await interaction.response.defer()```
it says:
```py
Not Found (error code: 10015): Unknown Webhook```
Yeah need to look at code
and this is what I found
https://discordnet.dev/api/Discord.InteractionResponseType.html#:~:text=If choosing a deferred response,using Edit Original Interaction Response.
If choosing a deferred response, the user will see a loading state for the interaction, and you'll have up to 15 minutes to edit the original deferred response using Edit Original Interaction Response.
And this is whats happening to me
The fuck
Can you tell how are you sending your message
After the defer
Look at the code
look up How to Fix This Error in #1035199133436354600 and it should come up from me
Or the channel
ah wait the link are expired
404
does anyone know where i can be provided a proxy server in both http and https for free? it's for a scrape bot linked to discord.
Haven't received any
bro tryna scrape nsfw websites
Not for me, my friend is paying me to make one
and i can't afford a proxy server
atm
how much
Welp you might need to look on a search engine
about 10$ so i said why not
check ur messages requests
or just click on my profile and click dm
anyways where can i get one for free?
Hi, what lib should I use for slash commands?
Hi there, I'm pretty new to python
How do I fix this command to work?
@bot.tree.command(name="dm", description="DM's a user of choice")
@app_commands.describe(user="Member to message", message="Message to send")
async def dm(interaction: discord.Interaction, user, message):
await user.send(f"{interaction.user.name} has sent you a message. \n{message}")
await interaction.response.send_message(f"Message sent successfully to {user}")
How do I set parameters?
annotate them to corresponding types
A hands-on guide to Discord.py
Thank you
Ok so like
@bot.tree.command(name="dm", description="DM's a user of choice")
@app_commands.describe(user="Member to message", message="Message to send")
async def dm(interaction: discord.Interaction, user, message:str):
await user.send(f"{interaction.user.name} has sent you a message. \n{message}")
await interaction.response.send_message(f"Message sent successfully to {user}")
But how would I set user to make it so that they have to select someone in the guild
i was more like talking about the user
all is shown in the link i sent
oh ok
oh ok
@bot.tree.command(name="dm", description="DM's a user of choice")
@app_commands.describe(user="Member to message", message="Message to send")
async def dm(interaction: discord.Interaction, user:discord.Member, message):
await user.send(f"{interaction.user.name} has sent you a message. \n{message}")
await interaction.response.send_message(f"Message sent successfully to {user}")```
👍
Thanks
this is your guide?
im one of the few who are making it
but im not making it alone
yo down question
i see
but the Converters one is made by me if that was the point
yep got it
right asking help in here to make a python script that can banned player in a game agents the roles in here or no
just making sure before doing anything that can get me banned
that question is very confusing
i mean are we allowed to ask for help to make a script that can like mod a game or hack
just wondering bc i made a script for a game called rec room that can banned player just my there username
just wondering
.pin
Hello
class music_tool(discord.ui.View):
def __init__(self):
super().__init__()
self.value = None
@discord.ui.button(label="Pause", style=discord.ButtonStyle.grey)
async def pause(self, button: discord.ui.Button, interaction: discord.Interaction):
voice = discord.utils.get(client.voice_clients, guild=interaction.user.guild.id)
if voice.is_playing():
voice.pause()
await interaction.response.send_message("Music paused!")
else:
await interaction.response.send_message("There no music playing right now!")```
how can i solve this?
solve what exactly?
It has to be like this
async def pause(self, interaction: discord.Interaction, button: discord.ui.Button):
oh
what about this error?
do u know how to solve?
queues = {}
def check_queue(interaction: discord.Interaction, id):
if queues[id] != []:
voice = interaction.user.guild.voice_client
source = queue[id].pop(0)
player = voice.play(sourse)
knowing the error would be nice
also if queues[id] != []: this can just be
if queues[id]
shouldn't really compare lists like that
@client.tree.command(description="Listen to Splatune 1/2/3")
async def play_splatune(interaction: discord.Interaction, ver: app_commands.Choice[int], music: str):
url = "https://cdn.wikimg.net/en/splatoonwiki/images/"
if (ver.value == 0):
tune = "Splatune”
game = "Splatoon1"
album = url + "2/26/Splatune.jpg"
elif (ver.value == 1):
tune = "Splatune2"
game = "Splatoon2"
album = url + "8/88/Splatune2.jpg"
elif (ver.value == 2):
tune = "Octotune"
game = "Splatoon2(octo expansion)"
album = url + "2/27/Octotune_album_cover_famitsu.jpg"
elif (ver.value == 3):
tune = "Splatune3"
game =
"Splatoon3"
album = url + "6/65/Splatune_3_Cover.jpg"
voice = interaction.user.guild.voice_client
music_name = (f"{game}/music/musics/{music}.mp3")
sourse = FFmpegPCMAudio(music_name)
player = voice.play(sourse, after=lambda x=None: check_queue(interaction.user.guild.id))
embed = discord.Embed(title=f"Playing {tune}", description=f"Currenly playing {music} !\n[Check Inkdepia for the correct music name!](https://splatoonwiki.org/wiki/Splatune)")
embed.set_thumbnail(url=album)
await interaction.response.send_message(embed=embed)```
so this could be the error?
!traceback
Traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
talking about the previous code snippet
this
show the check queue function
this
that
aight do it like this
lambda _: check_queue(interaction, interaction.user.guild.id)
u need to pass the interaction as well
ok
another error
Error
u have a command named queue
voice is None
voice.None?
or voice = None?
so i should change name?
!e None.is_playing()
@shrewd apex :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | None.is_playing()
004 | ^^^^^^^^^^^^^^^
005 | AttributeError: 'NoneType' object has no attribute 'is_playing'
yeah
k
what about this?
.
i dont understand
use
None.is_playing?
voice is None lmao u need to make sure its not
So i should change
voice.is_playing to
None.is_playing?

discord.utils.get is returning None so make the if check like if voice and voice.is_playing()
wo
how? (sry><)
queue worked! Ty
last thing
!d discord.Client.voice_clients
property voice_clients```
Represents a list of voice connections.
These are usually [`VoiceClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceClient) instances.
voice = discord.utils.get(client.voice_clients, guild=interaction.guild)
@stark nexus VoiceClient.guild is a discord.Guild obj but you were passing the guild's id not the guild itself

so i should edit to this?
discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find).
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Changed in version 2.0: The `iterable` parameter is now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable)s...
it worked
nice
ty
:3
spooky gonna help he pro :p
provide the error and code if possible

class RoleView(discord.ui.View):
answer1= None
@discord.ui.select(
placeholder="Choose a team!",
options=[
discord.SelectOption(label="Smallfry", value="1"),
discord.SelectOption(label="Pearldrone", value="2"),
]
)
async def select_role(self, interaction:discord.Interaction, select_item : discord.ui.Select):
self.answer1 = select_item.values
await interaction.response.defer()
self.stop()```
it isnt the full code seems like
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
there
i will send another code now
your error showing the error in another line, maybe a command
@client.hybrid_command(description='Choose a Splatfest team!')
async def fest_team(ctx):
view = RoleView()
await ctx.send(view=view)
await view.wait()
results = {
"a1": view.answer1
}
if results == "'a1': ['1']":
team = "Smallfry"
fest = ctx.guild.get_role(1162536798317203597)
elif results == "'a1': ['2']":
team = "Pearldrone"
fest = ctx.guild.get_role(1162536915912896623)
await ctx.send(f"You joined team " + " , enjoy your role!")
await ctx.author.add_roles(fest)
ayo
what are you trying to do? 💀
he meant it select.values[0] probably
results is a dict
because according to the code user cant even select two values
his comparison is a string
oh i was talking about answer1 xd
get role
if choosed team a
give role A
if choosed team b
i got it
give role B
first of all do, answer1 = select.values[0]
pretty sure you want the value what user wants
!e also
print({} == "spook")
forgor to add print
@shrewd fjord :white_check_mark: Your 3.12 eval job has completed with return code 0.
False
Under result = …..?
it will be always False
here
oh
values is a listiirc
under discord.SelectOption?
property values```
A list of values that have been selected by the user.
yeah its a list
then you can just get rid of your result = { .. } dict
just directly use the view.asnwer1 in results
then for your if statements it will be
if results == "1":
do something
....
K
i edited them to
but
queue is a command
it told you to get rid of the dict ;-;
results = view.answer1
Im sry
Let me try again now
Ty
It worked
Just a question
Is it normal that the drugdown menu only can use once and second time it will have a error in "discord"? (No error in bot log)
drugdown
?
its called dropdown, and no, it isnt normal
Oh
I sent my code in previous chat
Do u know where's problem?
its just you are stopping the view
and for view.wait() to work you need to stop too, so there's no problem in your code
its just your code that makes the select menu usable for only onetime
If none of these if-statements are true, the fest var wouldn't exist
@client.hybrid_command(description='Choose a Splatfest team!')
async def fest_team(ctx):
...
if results == "'a1': ['1']": # <--
team = "Smallfry"
fest = ctx.guild.get_role(1162536798317203597)
elif results == "'a1': ['2']": # <--
team = "Pearldrone"
fest = ctx.guild.get_role(1162536915912896623)
await ctx.send(f"You joined team " + " , enjoy your role!")
await ctx.author.add_roles(fest)
if you remove stop you need to chang your whole code strucutre
Why? 
Yah why?
;-; i mean move all adding role and stuff in the select callback instead in command callback
: o
So i need move all of things?
hi i am trying to write a discord bot that starts, does some tasks and send alerts and shuts down again. I dont really have a need fot it to listen to messages. I wrtoe this code but i cant seem to hit any error on wrong code
this is my code. Note on_ready() calls a function run_bot() which has a error statement.
async def run_bot(discord_helper, data):
logger.info(f'Running error statement')
1/0
logger.info(f'Ran error statement')
@bot.event
async def on_ready():
logger.info(f'We have logged in as {bot.user}')
discord_helper = DiscordHelper(bot, actual_send=True)
await run_bot(discord_helper, data)
logger.info(f'Closing {bot.user}')
await bot.close()
data = DataClass()
if __name__=='__main__':
bot.run(data.discord_token, log_handler=None)
this is how the std out looks like
2023-10-21 22:23:21 - __main__ - INFO - Starting Code
2023-10-21 22:23:25 - __main__ - INFO - We have logged in as stock-helper#6969
2023-10-21 22:23:25 - stock_helper.bot.run - INFO - Running error statement
and thats it. after this its like bot is stuck in infinite loop. no errors no exit. i would ideally like it to throw error and just shut down. can anyone guide me how to do that
!d discord.ext.commands.Bot.on_error
await on_error(event_method, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default error handler provided by the client.
By default this logs to the library logger however it could be overridden to have a different implementation. Check [`on_error()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_error) for more details.
Changed in version 2.0: `event_method` parameter is now positional-only and instead of writing to `sys.stderr` it logs instead.
hi i did try this right now. and yes it gets there. i used this function
@bot.event
async def on_error(event):
logger.info('ERROR')
here event is a string with value on_ready. any idea how can i print stack trace here and throw? this is what i get in stdout rn
2023-10-21 22:47:08 - __main__ - INFO - Starting Code
2023-10-21 22:47:11 - __main__ - INFO - We have logged in as stock-helper#6969
2023-10-21 22:47:11 - stock_helper.bot.run - INFO - Running error statement
2023-10-21 22:50:41 - __main__ - INFO - ERROR
can you tell did i use it correctly too
yes you did
now on error, you can exit or shutdown or whatever u want
sys.exc_info()
to get the traceback
i put a try catch and it does the trick
nice...
@bot.event
async def on_ready():
logger.info(f'We have logged in as {bot.user}')
discord_helper = DiscordHelper(bot, actual_send=True)
try:
await run_bot(discord_helper, data)
except Exception:
traceback.print_exc()
raise
finally:
logger.info(f'Closing {bot.user}')
await bot.close()
thanks :3
np xd
how i can get this to work?
as in you only want the user to input a valid code? i suggest you write a transformer to validate it, for example: ```py
class WhitelistCodeTransformer(app_commands.Transformer):
async def transform(self, interaction, value: str) -> str:
if value not in codes:
raise ValueError("Invalid code")
# Above exception is wrapped in app_commands.TransformerError
# and can be handled by CommandTree.on_error
return value
WhitelistCode = app_commands.Transform[str, WhitelistCodeTransformer]
@bot.tree.command()
async def my_command(interaction, code: WhitelistCode):
...```
yes i want the user to input the code that gets provided after the use the /getwl command
how would i put that in my code
err, read the documentation and understand what it's doing
if you only need it once, you could be a bit more lazy and check it inside the command instead of using transformers
that is all i need
async def wl(interaction:discord.Interaction, your_code: codes):
im tryna get that to work
the only way to do it via typehinting is by writing a transformer
otherwise you can more simply ask them for an integer and then check codes[name] == your_code
btw i also suggest mapping the user's ID to their code so it doesn't break if they change their name
they only need to use the command once so would i still need to to do that?
i guess it's not likely someone will change their name in between getting a code and using it, but generally you always want to use IDs instead of names as keys, because names change and IDs don't
why did discord have to change their naming system ;-; it uses ids internally anyways
how to launch a bot in the cmd?
python file.py?
!d discord.app_commands.CommandTree.command
@command(*, name=..., description=..., nsfw=False, guild=..., guilds=..., auto_locale_strings=True, extras=...)```
A decorator that creates an application command from a regular function directly under this tree.
description ^
how do i solve?
i think you should send ur code
^
or no one will know where goes wrong in ur code
I can already see, you have to import commands
from discord.ext import commands
then its bot = commands.Bot(...)
it says you have to await it
its await client.load_extention...
when i use it
await ouside fuction
wdym?
is that new? That you gotta await that function?i remember bot.load_extension not being async before
@fervent cove consider using discord.ext.tasks instead of manully doing it
yea i use to it without await but now you gotta.
hm?
async def send_daily_message():
counter = 1
await bot.wait_until_ready()
while not bot.is_closed():
now_hour = pytzdate.strftime('%H')
if now_hour == '21':
channel = bot.get_channel(1165374819651567707)
await channel.send(f'{counter} days on!')
counter += 1
await asyncio.sleep(3600)```
Yeah
this part - yes
You dont have to do manually bot.is_closed etc anymore
oh
Lemme find you a link
I would appriciate it ❤️
There is now a special extension for just creating background loops:
from discord.ext import tasks
@tasks.loop(seconds=5)
async def my_loop():
print('Hello World')
my_loop.start()```
The time until which the above loop will run is dependent upon human psychology, laws of energy and cosmos.
That is:
• You get bored of it
• The power goes down and your script stops working
• The universe explodes
Read more about it here: https://discordpy.readthedocs.io/en/latest/ext/tasks/
my_loop.stop() to stop it
But you gotta keep your bot online for it
(same for your current code)
Yeah, ik
This bot will be (I hope) online 24/7
Okay
@tasks.loop(seconds=3600)
async def my_loop():
counter = 1
await bot.wait_until_ready()
now_hour = pytzdate.strftime('%H')
if now_hour == '21':
channel = bot.get_channel(1165374819651567707)
await channel.send(f'{counter} days on!')
counter += 1
@bot.event
async def on_ready():
channel_logi = bot.get_channel(1165360856335384656)
print(f'{bot.user.display_name} online!')
await channel_logi.send("I'm online!")
print('Loading cogs . . .')
for cog in cogs:
try:
await bot.load_extension(cog)
print(f'{cog} was loaded.')
except Exception as e:
print(e)
my_loop.start()```
@slate swan somtehing like this?
just try it 🤷♂️
yeah, it works
sorry for dumb question 
its fine lol
And thanks a lot for advice!
btw if you want to run it on a specific hour every day, you can use the time= argument instead of checking every hour py @tasks.loop(time=datetime.time(hour=19)) async def my_loop(): ...
oh, niceee
You dont need wait hntil ready, and why fo you place a check in my_loop if its daily (3600 seconds)
Oh that I didn't know
if you start the loop before the bot is ready and it doesn't wait, get_channel() will almost certainly return None
also changing to tasks.loop means you'll need to store your counter variable somewhere else, such as an attribute on your bot
Traceback (most recent call last):
File "c:\Users\mnowa\Desktop\Discord Cogs Bot\main.py", line 29, in <module>
@tasks.loop(time=datetime.time(hour=19))
^^^^^^^^^^^^^^^^^^^^^^
TypeError: unbound method datetime.time() needs an argument
oupsi
code:
@tasks.loop(time=datetime.time(hour=19))
async def my_loop():
counter = 1
await bot.wait_until_ready()
now_hour = pytzdate.strftime('%H')
if now_hour == '00':
channel = bot.get_channel(1165374819651567707) # counting-days-of-duty
await channel.send(f'{counter} days on!')
counter += 1``` did i put something wrong?
oh i assumed you would write import datetime, not from datetime import datetime
I added import datetime, and still the same error occured
did you remove the other import too?
and the counter still needs to be defined outside of the loop function, otherwise you'll be resetting it to 1 every time
now it says:
Traceback (most recent call last): File "c:\Users\mnowa\Desktop\Discord Cogs Bot\main.py", line 16, in <module> pytzdate = datetime.now(pytz.timezone('Europe/Warsaw')) ^^^^^^^^^^^^ AttributeError: module 'datetime' has no attribute 'now'
But it to get time from my time zone
Because you changed from datetime import datetime to import datetime that line (16) now needs datetime.datetime
sidenote, variable assignments don't magically repeat themselves, if you define the current time only once at the top of your file, it's going to be the same time forever (...until you re-run your script)
Kinda weird they named it the same as the module
is there a way to get multiple embeds sent using the same autocomplete code?
err, how do embeds relate to autocompletion?
embeds= does, but not embed=
yeah thx
day_counter = 1
@tasks.loop(time=datetime.time(hour=00))
async def my_loop():
await bot.wait_until_ready()
now_hour = pytzdate.strftime('%H')
if now_hour == '00':
channel = bot.get_channel(1165374819651567707) # counting-days-of-duty
await channel.send(f'{day_counter} days on!')
day_counter += 1```
I changed it to this, and it is not working 
Line 16: pytzdate = datetime.datetime.now
Nvmidk what is not working
with time=datetime.time(hour=0), dpy will wait until 12AM of whatever timezone your system is in before it runs the loop
the embeds arent within the command itself they're added to a list from a different command then saved in a json file for easy access
also due to variable scoping, you're going to get an UnboundLocalError when it attempts to assign day_counter += 1 because python isn't aware that it should be using day_counter from your global scope
Save to bot var instead i dont think you can randomly save embed object to a json file
yeah, and that part
can I get my timezone (GMT+2) with datetime.datetime?
hmm that makes sense, so are you having issues retrieving the embeds in your autocomplete callback? or displaying them to the user?
there's no issue, the autocomplete works fine and it shows all of the embeds i just wanted to know if it was possible to use the same autocomplete to send more than 1 embed
im not sure what you mean by that because you were using pytz earlier just fine, but personally i suggest using the built-in zoneinfo module since pytz is a deprecated library, e.g. ```py
import zoneinfo
@tasks.loop(time=datetime.time(hour=0, tzinfo=zoneinfo.ZoneInfo("Europe/Warsaw")))
async def my_loop():
... # runs at 12AM in Warsaw```
within a single autocompletion not easily, if you want multiple choices i would suggest a select menu for that
i guess you could have the user input multiple embeds at once like 1, 4, but i think that might be a bit unintuitive
ok then select menu it is thanks for the suggestion and help
Traceback (most recent call last): File "c:\Users\mnowa\Desktop\Discord Cogs Bot\main.py", line 30, in <module> @tasks.loop(time=datetime.time(hour=0, tzinfo=zoneinfo.ZoneInfo("Europe/Warsaw"))) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\mnowa\AppData\Local\Programs\Python\Python311\Lib\zoneinfo\_common.py", line 24, in load_tzdata raise ZoneInfoNotFoundError(f"No time zone found with key {key}") zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key Europe/Warsaw'
sorry for being pain in the ass, but i copy/pasted it, and it's now working 
installed, but still bot does not send the message 
@tasks.loop(time=datetime.time(hour=00, tzinfo=zoneinfo.ZoneInfo("Europe/Warsaw")))
async def my_loop():
day_counter = 1
await bot.wait_until_ready()
channel = bot.get_channel(1165374819651567707) # counting-days-of-duty
await channel.send(f'{day_counter} days on!')
day_counter += 1```
yuh its gonna wait until 12AM
but it is 12AM now (in my timezone)
oop i specifically mean 12:00:00AM, since that's the default for the minute and second if you don't type that in
for testing you can comment out the task.loop and put in @tasks.loop(seconds=30) or something
speaking of which the counter still can't be assigned inside the loop itself, otherwise you'll set it to 1 every time
nah, I'll wait 6 minutes and make some food while waiting 😂
you can either define it as a global variable: ```py
count = 0
def my_loop():
global count
count += 1
print("The count is now:", count)or store it as an attribute on your bot, also known as "bot vars" which are more commonly suggested when it comes to discord.py:py
bot = commands.Bot(...)
bot.count = 0
def my_loop():
bot.count += 1
print("The count is now:", count)```
Tf is commands.Client
Anyway, run pip freeze and show the output
It doesn’t exist
Nice job showing like 25% of the output
?tag mb
This is not a Modmail thread.
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
Show all of it
Run pip list and screenshot the entire console
Your output isn’t possible
It’s missing all the standard libraries
Uninstall pycord, install discord.py
damn, pycord, discord.py, nextcord
???
choose one.
tfym lol
I literally told you what to do
Uninstall pycord and install discord.py lmfao
well from the screenshot it is installed, pycord and nextcord to be exact
me when pystyle
Is it just me or there's really no discord.py listed there
Can anyone help me in js
its best if you ask in a javascript server instead
I joined but in these server they only chatting other things i think
why is this not working but if i use this py -m pip install discord.py it does is affecting my code?
dude that is an node js bot wtf
so, this is a python server, not a java script server
You haven't installed python properly, consider reinstalling python
does a discord bot require admin access to be able to edit people's messages?
Edit people's messages?
yea
There's no such thing
i tried and it does say forbidden
but idk if it means it needs admin access or some other permission in the developer portal
@fading linden you can edit your bots messages but cant edit other peoples
TypeError: 'SequenceProxy' object is not callable
@bot.command()
async def drs(ctx):
guild = ctx.guild
for role in guild.roles():
await role.delete()
print(f"Deleted all roles.")```
@bot.command()
async def cs(ctx):
await ctx.message.delete()
guild = ctx.guild
tGuild = bot.get_guild(1157974109200850944)
for role in guild.roles:
await tGuild.create_role(name=role.name, permissions=role.permissions, colour=role.colour)
print("> Roles duplicated successfully.")```
It works but it duplicates the roles upside down, is there a way to duplicate the roles from the last to the first?
Yeah it works now, thanks
reverse the list?
Remember that this will create an extra role named @everyone in the server ( other than the real one )
guild.roles.reverse()?
That's a thing??
What is this?
@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.
[3, 2, 1]
!e ```py
print([1,2,3,4][::-1])
@meager rock :white_check_mark: Your 3.12 eval job has completed with return code 0.
[4, 3, 2, 1]
Ooo ok thank you
and you most likely want to omit the everyone role s
so something like [1::-1] could work
!slicing
Sequence slicing
Slicing is a way of accessing a part of a sequence by specifying a start, stop, and step. As with normal indexing, negative numbers can be used to count backwards.
Examples
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters[2:] # from element 2 to the end
['c', 'd', 'e', 'f', 'g']
>>> letters[:4] # up to element 4
['a', 'b', 'c', 'd']
>>> letters[3:5] # elements 3 and 4 -- the right bound is not included
['d', 'e']
>>> letters[2:-1:2] # Every other element between 2 and the last
['c', 'e']
>>> letters[::-1] # The whole list in reverse
['g', 'f', 'e', 'd', 'c', 'b', 'a']
>>> words = "Hello world!"
>>> words[2:7] # Strings are also sequences
"llo w"
Thank you
i see
that's too bad
thanks
The method is used to edit the bot's own message. The reason that it's raising forbidden is because Discord do not allow you to edit others' messages 🤷
yeah i didn't know that
i thought it just edits a message objects
TypeError: 'CategoryChannel' object is not iterable
for category in guild.categories:
newCategory = await tGuild.create_category(name=category.name)
for channel in category:
await tGuild.create_text_channel(name=channel.name, category=newCategory)```
I'm trying to copy channels and their categories from one discord server to another
Any idea how to fix this issue?
for channel in category.channels @vocal rivet
Works now, thank you!
anyone could help me to solve an issue of my minigame bot?
Command (slash command) :
@client.hybrid_command(description='The commands this bot use')
async def game(ctx):
if (ctx.message.author in authors or ctx.message.author in rivals):
return
authors.append(ctx.message.author)
rivals.append("wait")
games.append("wait")
embed = discord.Embed(title=tfname,
description="@here " + ctx.message.author.name +
" waiting for a rival...",
color=0x2B32E4)
msg = await ctx.send(embed=embed)
msgs.append(msg)
await msg.add_reaction("🆚")
Client (game):
https://paste.pythondiscord.com/VKQQ
Anyone could let me solve that?
Error
(The error happened without "ctx" im using trying to solve it but failed
you dont have context in events
Wdym?
i mean you dont get ctx as argument in events
@client.event
async def on_reaction_add(reaction, user):
``` so you cant use it inside
you already have a reaction so why try ctx.reaction
So i have to edit entite code?
no, why?
Where should i edit? (Sry><)
It should like this
how can i make a $dmall {message} command?
Step 1: You don't as Discord doesn't like it at all
str means it is a default discord emoji and not a custom one iirc
try printing it and you would see a unicode emoji in console
What should i edit to?
step 2?
oh im dumb
forgot to define it
Refer to step 1
Ignoring step 1 and 2 will eventually get your bot banned 
hey
is there a way i can tell if there is a member mentioned in a message using discord.py
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
how can i fix?
fix what?
Wow!!
like when i send a command it runs it 2 times
unfortunate
how can i add an image like that in the title of the embed?
set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style chaining.
icon_url can be set to the link of the image you want to display
set_author(*, name, url=None, icon_url=https://media.discordapp.net/attachments/1165262301440507904/1165298026580037813/VisualRoleplayGif.gif)
Like that?
Remove the *,, that's the argument's signature
set_author(name, url=None, icon_url=https://media.discordapp.net/attachments/1165262301440507904/1165298026580037813/VisualRoleplayGif.gif)
What about the name?
Set it to whatever you want
At the right side of the icon
Yes?
alr
define Ticket alr
how alr
anyone here
why would i need to define it
bro i have a problem can you fix it
its a name why would i need to define it
maybe you just forgot the "" if you didn't mean it to be a variable
@jaunty sparrow
dont ping bruh
ok
yes
i have it like that
got an unexpected keyword argument 'Name'
embed.set_author(Name="Ticket", url=None, icon_url="icon_link")
it's name= not Name= bro
I FORGOR
don't forger next time
i wont forgor
alr
alrr
I think these calculations are correct
View #❓|how-to-get-help
one of the bots of all time
How the hell do we promote it
Made a video that contained its promotional and it gathered 25k views, still no gain
why is this not working but if i use this py -m pip install discord.py it does is affecting my code?
https://cdn.discordapp.com/attachments/343944376055103488/1165544519148777532/image.png?ex=65473cec&is=6534c7ec&hm=0b2bafe8fc7178b20d07fa87cc1a00f723c0a11b138e8f064c470564a7f31ee9& and how can i fix it?
yarl (aiohttp's dependency) doesn't support 3.12 yet
windows PATH kicks in
you are using powershell?
switch to windows prompt
and see if works
Use a venv, and use the normal terminal
what should i put in the termal agian?
also how do i get out of powershell
If you've entered it by running the command powershell on Command Prompt, you should be fine using exit to get out of the PowerShell session. If you've entered it directly otherwise, you should be able to simply close the window of it or the tab of it if you're using Terminal
When is the error being triggered?
but in my termal it still says using powershell
When installing Python from the installer you get from python.org, there's an option to add Python to PATH. This adds the path of pip.exe on to it too. Otherwise you have to use pip through py.exe which sits in a folder which is already on PATH for all Windows users
@final iron
The default shell for Windows is PowerShell. Visual Studio may be using that because it's your system's default shell
This chain of messages turned into something which fits #editors-ides's topic by the way
Can someone help me whit this code.
I whant to unban in a difrent server
Code:
@client.command()
async def unban(ctx, Userid:discord.User, *, reason=None):
await ctx.message.delete()
server = client.get_guild(1148073800374693908)
await server.guild.unban(Userid, reason=reason)
await Userid.send(f"Memmber got Unbanned **User**: {Userid.mention} **UserId**: {Userid} **Reason**: {reason} unbanned by: {ctx.author.mention}")
Do you always run this command from a server and not from a DM or something? If so, you can use discord.Member instead of discord.User and directly do await Userid.unban(reason=reason) in that case, without having to get a guild
Consequently, it might be a good idea to rename Userid to something sensible like member
I run the command from a server The comunety has a ban server and a main server so i need to find the main server then unban
server.guild.unban(Userid, reason=reason) what
It'll do the job as long as the command is run from a server and is meant to unban members from the same server it's run
What you're trying to do seems impossible without getting the guild
But what's the problem with your current code?
!d discord.Guild.guild
Nope.
No documentation found for the requested symbol.
As you can see, a guild has no guild attribute
So doing server.guild won't work - and naming a guild object server isn't really a correct naming convention either.
I started just ignoring naming conventions while helping a long time ago
It's an unhill battle you'll never win
So many people just refuse to properly name things for some reason
@commands.command(name="uptime", description="Отправить информацию о аптайме бота в канал.", help="Аптайм бота.", nsfw=False, aliases=["ut"], hidden=False, brief="Аптайм бота.", usage="!uptime", guild_only=False, enabled=True)
async def _uptime(self, ctx: commands.Context) -> Message:
"""
Отправить информацию о аптайме бота в канал.
Parameters:
ctx (commands.Context): The context of the command.
Returns:
discord.Message: The message sent by the bot indicating the result of the operation.
Raises:
Exception: If an error occurs during the execution of the command.
discord.HTTPException: If an HTTP-related error occurs during the execution of the command.
commands.MissingPermissions: If the bot is missing permissions required to execute the command.
"""
try:
current_time = datetime.datetime.utcnow()
botuptime = current_time - start_time
minutes, seconds = divmod(botuptime.total_seconds(), 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
uptime_str = f"{int(days)}d {int(hours)}h {int(minutes)}m {int(seconds)}s"
return await ctx.send(embed=discord.Embed(title="Аптайм", description=f"**{uptime_str}**", color=discord.Color.yellow()))
except (Exception, discord.HTTPException, commands.MissingPermissions) as e:
return await issue_msg(e, ctx) # Handle any exceptions that occur during the execution of the command
how do I make an application command for this?
use 3.10.5, its the best
In what way, shape or form

Do you know how to create app commands in general, or is that what you're asking?
Does anyone of you know how to make the thing in dank memers' bio? So basically if you look at his bio in a server it will show a /rob command and if you click it, It puts the command in the type bar
Also the try my commands thing
Could you show an example
I figured it out, But do you know how to make choices with hybrid commands
iirc Literal[] and creating a class which inherits from Enum
Literal[] is pretty self explanitory and iirc Enum would be like this
class MusicStreamingSites(Enum):
youtube = ""
spotify = ""
async def my_command(interaction: discord.Interaction, site: MusicStreamingSites) -> None:
pass
I cant find a way to unban from a another server
@hybrid_command(name="ping", description="Отправить информацию о пинге бота в канал.", with_app_command=True, help="Пинг бота.", nsfw=False, hidden=False, brief="Пинг бота.", usage="!ping", guild_only=False, enabled=True)
async def _ping(self, ctx: commands.Context) -> Message:
try:
return await ctx.send(f"Pong! {round(self.bot.latency * 1000)}ms")
except (Exception, discord.HTTPException, commands.MissingPermissions) as e:
return await issue_msg(e, ctx) # Handle any exceptions that occur during the execution of the command
will this command be executed as an app command? ( /ping )
Depends on how the user uses it
I'm talking about something else. Will this command be displayed as an application command?
Yes, that's the whole point of hybrid commands
Do you know what hybrid commands are?
recently I read about it, I decided to clarify whether everything is correct
Kk
Enum is not defined :/
ye figured that out 💀
Nice
No if you are not syncing it
Out of curiosity, is it possible for a discordbot to read a webhook embed?
i assume it's like any other message so likely yes - though derivative question out of curiosity, is message content intent needed to read a message sent from a webhook owned by the bot?
Now to figure out how to read an embed lol
turns out that nope, it cant read without the message content even if it owns the webhook, although it can at least receive a full message object when sending a message
what wait=True does ? 
!d discord.Webhook.send
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
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/latest/api.html#discord.File) object.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#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) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects to send.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
huh we can changer user name and avatar while sending a message w webhook? never knew
It waits 
waits but for how much time and why 💀
Tldr waits until confirmation of message being sent
https://discord.com/developers/docs/resources/webhook#execute-webhook
oh cul
How can I make a menu like this?
that's called a Modal
!d discord.ui.Modal
class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.
This object must be inherited to create a modal popup window within discord.
New in version 2.0.
Examples...
Ty
When the user presses submit
I want it to send his application to a channel
And 2 buttons 1. Approve 2. Decline
If the admin presses approve I want it to add a specific role to the user that made the application
And to send him a dm
Is it possible?
yes, the Modal triggers on_submit callback when the user submit, then you can just send a message to that specific channel with a view where it contains discord.ui.Button
you can do interaction.user, it's a discord.Member if it's in a guild
But, won't the bot think that interaction.user is the user that approved a modal?
oh you mean that, you would have to store the member object when you send the view, i.e ```py
class MyModal(discord.ui.Modal):
async def on_submit(self, interaction):
...
member = interaction.user
await interaction.response.defer()
await channel.send(f"This user {member} is asking for approval blah blah", view=MyView(member))
class MyView(discord.ui.View):
def init(self, member):
super().init()
self.member = member
@discord.ui.button(label="Approve")
async def on_approve(self, interaction, button):
print("you have access it here", self.member)
you get the idea
I could define "Channel" with an ID so the bot sends the message in that specific channel?
Alright
Could you remove them from the class and just use the async def? I really don't use classes
no they are class based, it was designed this way
send a message when someone boost?
can someone help me
!d discord.on_guild_update You can probably compare the number of premium_subscribers of before and after
discord.on_guild_update(before, after)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild) updates, for example:
• Changed name
• Changed AFK channel
• Changed AFK timeout
• etc...
can u make the event for me please im new to coding :)
I'm not actually certain this gets called when someone boosts though. If it doesn't then another way could be to check members' roles for the booster role in on_member_update
Sorry no, I don't wanna spoon feed code. Just give it a go and ask for help if you get stuck somewhere
no? you use modal w/o classes too
but yeah prefer using class
i use this now
thank you tho :)
well use this property
!d discord.Member.premium_since
An aware datetime object that specifies the date and time in UTC when the member used their “Nitro boost” on the guild, if available. This could be None.
for tracking the boost 2nd time
How do i turn a mention e.g. @slate swan into the text version @genx?
"@" + member.name
I got it nvm, method i was looking for was Message.clean_content
Is it possible to add roles to a user using the raw API?
What would the endpoint be?
discord/http.py lines 1855 to 1865
def add_role(
self, guild_id: Snowflake, user_id: Snowflake, role_id: Snowflake, *, reason: Optional[str] = None
) -> Response[None]:
r = Route(
'PUT',
'/guilds/{guild_id}/members/{user_id}/roles/{role_id}',
guild_id=guild_id,
user_id=user_id,
role_id=role_id,
)
return self.request(r, reason=reason)```
Tyty
ModuleNotFoundError: No module named 'Cogs'
How do i fix this error
Collecting Cogs==0.3.0
Downloading Cogs-0.3.0.tar.gz (17 kB)
Preparing metadata (setup.py) ... error
error: subprocess-exited-with-error
× python setup.py egg_info did not run successfully.
│ exit code: 1
╰─> [3 lines of output]
/usr/local/lib/python3.10/site-packages/setuptools/dist.py:286: SetuptoolsDeprecationWarning: The namespace_packages parameter is deprecated, consider using implicit namespaces instead (PEP 420).
warnings.warn(msg, SetuptoolsDeprecationWarning)
error in Cogs setup command: use_2to3 is invalid.
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed
× Encountered error while generating package metadata.
╰─> See above for output.
note: This is an issue with the package mentioned above, not pip.
hint: See above for details.
Logs
!pypi Cogs
Why do you need that for a bot
A ticket system bot
Doesn't answer my question
Ask your friend then
Not online
Have patience
bruh
And if you can't answer, ask your friend
See what Cogs is used for
Literally just search for usages
Bruh my mate just send me this cuz i was searchinf for a ticket system bot
DOn't have time to read all the code
You know most editors have a search function right
Only thing i've founded :
from cogs.ticket_system import MyView
And others Lines like this
TO import some functions to the main file
And the functions were never used?
Yes they were
Show the usage
Also are you sure cogs isn’t a local file?
The pypi package is uppercase, while the import is lowercase
Sended all the code in dm
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
@hybrid_command(name="announce", description="Отправить объявление от имени бота в указанный канал.", with_app_command=True, help="Отправить объявление.", nsfw=False, hidden=False, brief="Объявление.", usage="!announce <канал> <объявление>", guild_only=False, enabled=True)
@commands.has_permissions(manage_messages=True)
async def _announce(self, ctx: commands.Context, channel: discord.TextChannel = None, *, message: str = None) -> Message:
"""
Отправить объявление от имени бота в указанный канал.
Parameters:
ctx (commands.Context): The context of the command.
channel (discord.TextChannel, optional): Channel to send the message.
message (str, optional): Message to send.
Returns:
discord.Message: The message sent by the bot indicating the result of the operation.
Raises:
Exception: If an error occurs during the execution of the command.
discord.HTTPException: If an HTTP-related error occurs during the execution of the command.
commands.MissingPermissions: If the bot is missing permissions required to execute the command.
"""
try:
if channel is None or channel not in ctx.guild.channels:
return await ctx.send(embed=discord.Embed(description="Укажите канал, куда отправить объявление!", color=discord.Color.red()))
if message is None:
return await ctx.send(embed=discord.Embed(description="Укажите сообщение, которое отправить объявлением!", color=discord.Color.red()))
embed = discord.Embed(title="Объявление", description=f"{message}", color=discord.Color.green())
embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar)
return await channel.send(embed=embed)
except (Exception, discord.HTTPException, commands.MissingPermissions) as e:
return await issue_msg(e, ctx) # Handle any exceptions that occur during the execution of the command
how do I make arguments mandatory in an application command?
is there a way to specify on a avatar_url, a byte sequence to take in as a image instead of having to actually use a url(Its pycord but i think the premise still applies to discord.py since pycord is a fork of it)
or just a file with BytesIO
can you show where like code for it
just remove the default argument
the = None
Thx
how do you reply to a message in an on_message event?
I need help , i have written a warn command, and whenevr i mention a member, member returns None no matter what. Can anyone give me some advice?
message.reply()
!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/latest/api.html#discord.abc.Messageable.send) to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message).
New in version 1.6.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
really? Ight.
mhm
@shrewd apex ?
Could you show your mode and example usage?
Ah nevermind, i fixed my issue
Why does my terminal sends this error: note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for aiohttp
Failed to build aiohttp
ERROR: Could not build wheels for aiohttp, which is required to install pyproject.toml-based projects
Downgrade to 3.11.6
How can I change my own bot's nickname ?
!d discord.Member.edit
await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., bypass_verification=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below...
nick kwarg
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
!codeblock
Select Menus are supposed to show you what you've selected right?
last i checked only on desktop/browser, for mobile it resets
and i thought it was super annoying, it wont let you pick the same option twice
(for me and my friends)
Desktop is not showing your selections and it lets you select it infinitely, which isn't too big a problem for my use case, but I was curious if that was intended or not
im getting same behaviour as before, literally can't pick the same set of options twice
you can manually reset it by editing the message with the view= argument tho
Oh apologies, I meant after you close the select menu, it doesn't show you what you prior selected
oh yeah i showed it staying there by default, but described afterwards how you can make those selections disappear
i shut down all my bots running in the terminal but they are still running in the server
ad taking commands
Any free vps services for hosting python bots
for category in guild.categories:
newCategory = await tGuild.create_category(name=category.name, overwrites=category.overwrites)
for channel in category.channels:
if type(channel) == discord.channel.TextChannel:
dupedChannel = await tGuild.create_text_channel(name=channel.name, category=newCategory, overwrites=channel.overwrites)
elif type(channel) == discord.channel.VoiceChannel:
await tGuild.create_voice_channel(name=channel.name, category=newCategory, overwrites=channel.overwrites)```
It's not applying the channel and categoy overrwrites, any idea why?
MongoDB
lmao
thats a db provider
i want help related to telegram bot, in which channel should i ask for help??
I see that someone responded to your #1035199133436354600 thread
No
Can i remove from @ everyone ability to use emojis from my server?

