#discord-bots
1 messages · Page 305 of 1
It's documentation, not examples
Well create_webhook is a method of TextChannel
You need a discord.TextChannel object
It's just basic OOP
You need a discord.TextChannel object first of all
Discord.py isn't catered to beginners unfortunately
that's basic ngl
Objects are one of the most basic concepts you'll need to learn for discord.py
^
Where are you trying to excute the code
...
Like in a command or interaction...
!d discord.Interaction.channel
The channel the interaction was sent from.
Note that due to a Discord limitation, if sent from a DM channel recipient is None.
That'll return the TextChannel object (depending on where it's run)
You'll probably want to ensure it's a channel that you can create a webhook for
Yes, and that's how to create the webhook
Which other parts do you need help with?
^
^
huh
Yeah, you're not supposed to copy and paste it
You can use it, just not the way you were lmao
Normally?
Not sure what the question entails
It's documentation on how to use it, you can't just directly copy and paste the code
You use it as reference
Well create_webhook is a method of TextChannel
name, avatar, and reason are the args it takes
=None means it defaults to None, and is optional
Not sure why you have the * there
Like I already said, you're not supposed to copy and paste the documentation
It's for reference, it's not a guide
To show they're key word only
Have you read the doc?
You have to specify what they are when you're passing them
await create_webhook() won't work as well
Like I said multiple times, it's a method of discord.TextChannel
No?
It's literally a method
Do you know what a method is?
You need to get a channel first and then use create webhook method on that channel
^ This will return your channel object
Do you at least know OOP?
Do you know what an object is
You're not using discord.py?
Why didn't you say so...
Why...
Why in the world would you use requests
Aren’t they on like v10?
That as well lmao
Or v9
Your friend has no clue what he's talking about
It's not better in any way

At least in your situation
yeah. Though v6 is still the default iirc
You have to put the actual guild ID in there
And I’m sure you’d need a channel ID somewhere too, because webhooks go to a specific channel
Oh hi
Fancy seeing you here
You come here often?
no comment
!d discord.TextChannel.create_webhook
await create_webhook(*, name, avatar=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a webhook for this channel.
You must have [`manage_webhooks`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_webhooks) to do this.
Changed in version 1.1: Added the `reason` keyword-only parameter.
I've been going in circles with this for like 20 minutes
Already showed him how to create it, how to get it's url and how to get the TextChannel object
Apparently he's using a mix of discord.py and requests
For some reason
Wat
My reaction
if you're already using discord.py you may as well use the methods it gives you
Both??
I've told you to use 1 library this entire time
discordpy uses something similar to requests under the hood anyway
I can understand only requests, I’ve done it myself
But both is madness
Your friend doesn't know what he's talking about
Sure, but there's no point in using requests to make requests to discord itself
It makes sense to use requests for other stuff, though
Yeah, like if you're already introducing the extra processing with discord.py you might as well consistantly use it lol
Share the code
Can you show us those 20 lines?
!paste
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.
That's just over-complicating it for no reason
Just use discord.py
20 lines isn't much
Shouldn't be a big deal
Requests is harder to use than discord.py, since it's lower level. A lot more room for errors as well
It would serve you well to switch early on
With discord.py it'll probably be condensed down to 15 lines anyway
That's what we're here for
Not knowing how to do something is one of the easiest technical problems to solve 😉
It's not any faster than using discord.py, and using requests make it easier to make mistakes. it's also harder to read
We don't know what stuff if you don't show us.
Well, that's easy to fix
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.
Then we can work from there
for role in guild.roles:
await role.delete()
Where is it? In a command, on_message event etc
That's the point
Where are all the roles going?
Nuke bot?

Bro literally just share the code
Where are you calling the function?
Yes, where
Okay, so let's convert it into a command
Share your entire file
We need to see what we're working with
!paste
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.
Share your main file with your Bot/Client instance
Somewhere you've either defined client = discord.Client or bot = discord.ext.commands.Bot
One of those, it's important to know which
You said you were using a mixture of discord.py and requests, what are you using discord.py for
Alr im done with this
Too much effort, too much time
@willow crystal see here for an example of a basic bot
You can set it up so that you have a command, which when invoked, deletes the roles
discord.py (and the API) is an advanced library so it would be very useful to be comfortable in Python and how REST APIs work before making a Discord bot
it's all documented. you can usually find what you need by searching keywords on the docs
Registers the function as a command handler. discord.py will call that function when a user sends that command
how I can get content from embed?
message = await ctx.channel.fetch_message(1154290052432678922)
await ctx.send(message.content)
like this its consider it as empty message
!d discord.Message.embeds give you a list of embeds in the message
A list of embeds the message has. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
!d discord.Embed.description gives you the description of an embed object
The description of the embed. This can be set during initialisation. Can only be up to 4096 characters.
Anyone wish to help with testing a discord.py ext.commands alternative?
(Entirely seperated command logic, context, etc
guys i am making a discord.py rank system bot, what db structure shouldi follow? i using sqlalchemy
I made the music bot watching this tutorial it works but idk why but it joins plays the audio for a few seconds then disconnects and says
ffmpeg process 13012 successfully terminated with return code of 0
!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)
In addition to !ytdl
THIS IS NOT LEGAL ADVICE
If you're making a "music bot", you should probably consider the implications on the terms of service you have agreed to.
- Redistributing copyrighted material (such as music) without the permission of the copyright holder violates international copyright law.
- Essentially all popular streaming services (YouTube, Spotify) explicitly forbid in their TOS any redistribution of the content they host without their permission.
- Discord developer TOS (which you have agreed to) forbid you using your bot to violate law or break the terms of service of other platforms, which applies to points 1 and 2 above.
- Discord has been taking increased action against bots violating these terms and has said this is not allowed in no unspecific wording.
Do with this information what you will, but consider the fact that organizations with far more money and power will put mounting pressure on discord if people continue to use bots to violate their copyrights.
#python-discussion message reference
You'll have to learn how to code btw
Simple answer, don't declare a commands.Bot and then a discord.Client
Just declare commands.Bot and that's it
What the hell is this
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
its against Discord TOS
Also self bots are banned by discord. Discord will hunt you down and ban your account
What you call a wall of text that covers the entire Discord overlay? Excessive texting?
Can someone help me override discords error handler entirely? when i went from on_error to error_handler for an entirely custom error handler, and its not catching the errors at all for some reason now
i dont get why it isnt running
What's wrong with on_error anyway? 
uhh, can i call it outside of the bot class?
like how im trying to call my own?
Yes?
for some context, im not using ext.commands, i wrote my own version of it, so i figured i'd do my own error handler in the command logic
can you point me to some docs for it?
!d discord.on_error
discord.on_error(event, *args, **kwargs)```
Usually when an event raises an uncaught exception, a traceback is logged to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.
The information of the exception raised and the exception itself can be retrieved with a standard call to [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info).
Note
`on_error` will only be dispatched to [`Client.event()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.event).
It will not be received by [`Client.wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for), or, if used, [Bots](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#ext-commands-api-bot) listeners such as [`listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen) or [`listener()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.listener).
Changed in version 2.0: The traceback is now logged rather than printed.
It's an event, in fact
how do i get context from that?
Good question
back to square one again LOL
i'd need to be able to send message back so the bot doesnt just ghost the user, and i implemented my own context, command handler, etc, so i dont think the on_error would be able to use it without monkeypatching
unless i can pass things through it, and call it myself while handling the invoking
!d discord.ext.commands.on_command_error is probably what you want if a context object is ever to exist
No documentation found for the requested symbol.
!d discord.ext.commands.Bot.on_command_error
await on_command_error(context, exception, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default command error handler provided by the bot.
By default this logs to the library logger, however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
Changed in version 2.0: `context` and `exception` parameters are now positional-only. Instead of writing to `sys.stderr` this now uses the library logger.
derp
i'd imagine so if you're using your own commands extension
yeye
said fuction that errors
i messed up the on_error in the ss but its just me trying every combination possible lol
just made sure so i could be 100%, still doesnt work when i change the on_error to error_handler
If cantreachapi is exception you should create instance of it
would that affect it?
What is the different between Excessive texting and text wall? I thought most of the Discord bot developers used the term "Excessive texting" or am I wrong?
👍
A wall of text is usually one very long message. The other kind of excessiveness is sending consecutive messages with a short delay between them. A long delay, let's say 10-30 seconds, is not as excessive/spammy because that rate is within Discord's rate limits for sending messages (a total of five messages in every five seconds). If it comes to that, you will see windows of time/five second buckets where five messages are sent each time window/bucket
So in my case it would be proper way to call it "Large text/Wall of text" as for the reason?
if len(content) >= 500: # Check if message has 500 characters or more
try:
await message.delete()
modlog_message = "Large text/Wall of text"
await send_modlog(channel_id, message, modlog_message)
return # Skip the rest of the processing for this message
except discord.errors.NotFound:
return```
Ye
By the way is the discord.errors.NotFound handling a thing because the bot might have left the server, can't view the channel it's in or the message was deleted? You can take your time in startup_hook to try to fetch all these stuff from Discord (what your database inquires) and remove entries that are no longer up to date
The last two things might still be problematic during the bot's uptime but you could do that every now and then with a discord.ext.tasks loop or at least remove these entries in this command or whatever whenever you get that error
how can I ignore threads? It doesn't work
if ctx in ctx.guild.threads:
return
You can check the type of ctx.channel using isinstance
thanks
I am just starting to use the slash command and I am getting an error with this code. Can you please tell me how to improve it?
@bot.tree.command(name="test")
async def test_command(interaction: discord.Interaction,location:str):
data = {"locate": {str(interaction.guild.id): location}}
with open('data.json', 'w') as json_file:
json.dump(data, json_file, indent=4)
result = get_weather_info(location)
if result:
data = result[1]
print (data['name'])
get_map_image(lon = data['coord']['lon'], lat = data['coord']['lat'])
await interaction.response.send_message("aa")
else:
await interaction.response.send_message("bb")``````
Traceback (most recent call last):
File "C:\Users\zarus\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "d:\Other\DJKK\main.py", line 33, in test_command
await interaction.response.send_message("aa")
File "C:\Users\zarus\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 801, in send_message
await adapter.create_interaction_response(
File "C:\Users\zarus\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
Hey I think you should use app_commands instead of whatever ur using, it's easier in my opinion
but it is app_commands ?
It is?
yes
issue is he is taking longer than 3 seconds to respond
plus some more sync shit that is prone to causing trouble like a sync http request and json file io
Does this mean that the bot is taking too long to respond and is timing out? Is there any way to fix this?
defer it then send a followup
Thank you so much! It worked!
np
though you should consider using a proper database with some sort of async driver instead of JSON in the future
Thank you! I'm a beginner in programming, and I was using JSON without knowing anything about databases. I'll do some research and make the necessary changes!
sup
You would want to use asqlite or aiosqlite for this btw
How do I create a function that filters out unrelated requests in my LFG channels on my gaming Discord server? I'd like the bot to be able to determine if a message is posted in the correct channel or not
You can compare channel objects like usual
I was considering a 'bad word filter,' but are there more sophisticated approaches like with AI?
sure. But that's beyond the scope of this channel
Pretty sure discord has a built in one though
Not really. I actually want to take further action by sending the user a message/redirecting them to the correct chanel etc when they post in the wrong channel
Yeah you can do that. Up to you
Do you know any tools to do it?
Are you asking about the detection part or the redirecting users to the right channel part?
Both
Detection is up to you. I don't have enough information to suggest much. The latter is straightforward, message.delete to delete message, and ctx.send to send an info message
What about Spacy?
Never heard of it
or scikit-learn
AutoMod. Discord's AutoMod is also AI powered + you can use regex if you would like
Ai, Regex and/or string processing would be your best bet
You'd probably have to train your own model though
And unless you have a ton of data, you'll need to create some
Which model could I use for this purpose?
I need help figuring out why i get this error
) -> None:
try:
await coro(*args, **kwargs)
except asyncio.CancelledError:
pass
except Exception:
try:
await self.on_error(event_name, *args, **kwargs)
except asyncio.CancelledError:
pass
line 441 is await coro(*args, **kwargs)
print(f"{username} said: '{user_message}' ({channel})")
if user_message[0] == '?':
user_message = user_message[1:]
await send_message(message, user_message, is_private=True)
else:
await send_message(message, user_message, is_private=False)
if user_message[0] == '?': is line 34
whats user_message?
!e ""[0]
@shrewd apex :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | ""[0]
004 | ~~^^^
005 | IndexError: string index out of range
basically you are trying to index an empty string
🤦♀️
just why are people constantly saying they need help after watching yt tutorials for how to make a bot using dpy...

That's not something that is either related to discord bots or python in general
This exists for some reason
That's what I'm saying
Instead of asking us here u should rather ask your friends
If they are willing to help or not
Ask your friends instead
demn, new helpers in discord-bots channel
Gl
There is something called vpn and proxy
also why would some random stranger run some code 24/7 for some random guy in discord who sent some unknown code
hi sry for late reply, i just wana make the bot for my self a fun project not for public can i do that?
ahh so that means i can't use yt-dl anymore? and it wont get any updates either?
well can you just tell me how i can play audio in a voice channel? if i dont use youtube or spotify that breaks discord terms?
Even though that's the case, I still strongly recommend you to not continue with your bot at all
I can not help you with that, sorry.
okk, thanks for the info
no problem thanks for your support
When the

All ogs busy with bobux (no)
Old helpers are replaced by new except for catty :3
:3

hello people
probably more patient
facts
Maybe it becomes vertical??1!1!1
pro
Why is 2023 in the start?
Marks start of year?
Tho the spike fo aug-sep is awesome
yup
hey guys if anyone's good with ffmpeg and python can i ask for help? i'm trying to make a discord music bot but ffmpeg keeps terminating the song before it even plays.
!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)
And instead of using ffmpeg u can use wavelink especially if you use discord.py
does this work for windows too?
Yes
ah ok thank u!
how do I call the popup input interaction using discord.Ui?
What's popup input interaction? 
wait let me get an example
Modals?
like theres a screen that pops up and tells you to input
Yeah, that's modals. Here's the example of it
thank you!
catty catty :3
is it possible to get pronouns from profile using discord.py?
right now, no
I see
!d discord.User
class discord.User```
Represents a Discord user.
x == y Checks if two users are equal.
x != y Checks if two users are not equal.
hash(x) Return the user’s hash.
str(x) Returns the user’s handle (e.g. `name` or `name#discriminator`).
actually i am not sure 💀 lemme check up
i dont think the discord api provides that information at all, same with the about me
maybe we can fetch with identify scope only?
ahh that sucks
oh nvm actually 
Hi 🐈⬛
sup 
how am I supposed to use await interaction.response.send_modal() after responded to the interaction using await interaction.defer()?
Impossible i guess
i see
a workaround could be to send a view with a button which triggers the modal
how I can check if category exists by name?
just did that!
thank you
use .get util function
!d discord.utils.get
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...
!d discord.utils.find
discord.utils.find(predicate, iterable, /)```
A helper to return the first element found in the sequence that meets the predicate. For example:
```py
member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
``` would find the first [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) whose name is ‘Mighty’ and return it. If an entry is not found, then `None` is returned.
This is different from [`filter()`](https://docs.python.org/3/library/functions.html#filter) due to the fact it stops the moment it finds a valid entry.
Changed in version 2.0: Both parameters are 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.
or this
Can confirm it's not currently possible to get the about me or gender from a user profile. I wish you could though it'd be useful
thx
Where i can find documentation for tree commands, cuz i want to look how to make tree commands with getting the arguments
how to set permissons for new channel?
I mean the bot makes a chennel and set its permission
!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) or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#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). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#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) to do this...
@client.event
async def on_message(message):
# Check if the message is from the bot
bot_admin_role = discord.utils.get(message.guild.roles, id=1154792822562635876)```
bot_admin_role = discord.utils.get(message.guild.roles, id=1154792822562635876)
^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'roles'
what should i change in it so it will work properly
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
You can use this
!d discord.Message.guild
The guild that the message belongs to, if applicable.
This attribute will be None if the message is sent in DMs
Or if the role id is invalid
But in your case it is because of message.guild returning none
What?
Welp that is irrelevant I read the error statement wrong
so it should look something like this
bot_admin_role = discord.get_role(role_id, 1154792822562635876)
?
im kinda dumb brother
Welp get_role is an attribute of guild
And discord is not a guild
Instead there needs to be a guild there
i found it, ye sorry for time wasting
And no need to write role_id why are you even doing it?
Mb bro sorry found it now
So what did you do?
bot_admin_role = discord.Guild.get_role(role_id=1154792822562635876)
class ticket_buttons(discord.ui.View):
def __init__(self):
super().__init__()
self.Value = None
@discord.ui.button(label=" إغلاق التذكرة 🔒.", style=discord.ButtonStyle.danger)
async def close(self, interaction: discord.Interaction, button: discord.ui.button):
await interaction.channel.delete()
@discord.ui.button(label="كيفية الشراء 👌.", style=discord.ButtonStyle.green)
async def close(self, interaction: discord.Interaction, button: discord.ui.button):
await interaction.response.send_message("""للشراء ، يجب اتباع الخطوات التالية.
أولاً ، اكتب سعر أمر الشراء ، واكتب نوع الأعضاء ، واكتب الرقم الذي تريد شراءه.
مثال على شراء 10 أعضاء اوفلاين:
the class have 2 buttons but its only showing 1 button in the message
Same function name
ah
In your case it should be message.guild.get_role
Since message.guild returns a guild object
But if the message is in dm then it will throw an error
The message is not on dm, but still it throw error
Is it the same error?
^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'get_role'```
yep
Can you show the whole function where you are using this code
@client.event
async def on_message(message):
# Check if the message is from the bot
bot_admin_role = message.guild.get_role(role_id=1154792822562635876)
if message.author.id != client.user.id and (bot_admin_role not in message.author.roles) and message.author.guild_permissions.administrator:
# Delete the admin's message
await message.delete()
# Send the same message from the bot
await message.channel.send(message.content)
# Save the message to the adminlog.txt file
log_message = f"User: {message.author.name} Message: {message.content} Date: {datetime.datetime.now()}\n"
with open('logs/adminlog.txt', 'a') as log_file:
log_file.write(log_message)
Weird it shouldn't throw this error
Ye, i think i will just change it to using command for replies
Try printing the guild id
Add ```py
print(message.guild.id)
Right above bot admin role variable
Guild is None if it's in a dm
AttributeError: 'NoneType' object has no attribute 'id'
its not in dm
Skill issue I think
Yup for some reason your bot is unable to get the guild
nvm i will change the code to a command tho, cuz i rethink it and command would be better
What are your intents
intents = discord.Intents.all()
But i have other question how to send message that it will be not as response to user that used the command?
await interaction.response.send_message(f"{reply}")
You can just use interaction.channel.send
how to stop bot.wait_for if another one started?
This sounds like a question for #async-and-concurrency. But I'd make a function that handles that
You get the idea
discord bot
!e like this (let the second task finish)
import asyncio
# Pretend that this is a bot object
class Bot:
def __init__(self):
self.curr_task = None
async def task_handler(self, coro) -> None:
if self.curr_task is not None:
self.curr_task.cancel()
print("Cancelled the running task")
self.curr_task = asyncio.create_task(coro)
bot = Bot()
async def work(id: int, time: int) -> None:
print(f"[{id}] Work started")
await asyncio.sleep(time)
print(f"[{id}] Work ended")
async def main() -> None:
await bot.task_handler(work(0, 1000))
await asyncio.sleep(0.5)
await bot.task_handler(work(1, 0.1))
await asyncio.sleep(0.5)
asyncio.run(main())
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | [0] Work started
002 | Cancelled the running task
003 | [1] Work started
004 | [1] Work ended
It involves asyncio to make that possible 🤷
In the way that I'd do it, at least
can you give me example that uses bot.wait_for cause Im not understanding this
Just replace the work coros with it?
I can't write examples for everything
(you probably want to set the curr_task to None when the task finish, by the way)
ok
You explain to me
It's not going to move forward if you don't provide an explanation on where and how it is breaking and the full traceback
U probably do
No if you refuse to provide the tracebacks
You basically made it where I can't even help you bc you have zero clue on what you are talking about
K
async def reply(interaction: discord.Interaction, reply: str):
try:
# Save the message to the adminlog.txt file
log_message = f"User: {interaction.user} Message: {reply} Date: {datetime.datetime.now()}\n"
with open('logs/adminlog.txt', 'a') as log_file:
log_file.write(log_message)
await interaction.channel.send(f"{reply}")
except Exception as e:
print(f"An error occurred: {e}")```
Message is sending on channel but still i have info that app is not reacting any idea ?
maybe cause you named your function the same as its argument
this would be the issue in the future anyways
ye i didnt saw that tbh
what do you mean by app is not reacting
in order to respond to interaction you need to use interaction.response.send_message method
I know but i want to send message to channel as bot without responding to user
well you could somehow delete the interaction but i dont remember tbh
!d discord.Interaction
class discord.Interaction```
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
New in version 2.0.
!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) in case you do not want to fetch the message and save an HTTP request.
try this
it just deleting hole message
I mean i can make like it will detele response and then send to channel
ye mb i think it will work
Yep worked thanks for help, it's kinda annoying tho that i can't just turn the response off and i must delete it ;/
There is no way to force response as done ?
Hello How to when i Click Luse He change Embed i know all But i do not know Change EMBED
button1 = Button(label="Louse", style=disnake.ButtonStyle.danger, emoji="⚰️",)
button2 = Button(label="Link: Towers",style=disnake.ButtonStyle.link,url="https://docs.disnake.dev/en/stable/api/ui.html#disnake.ui.ActionRow.add_button")
async def button_callback(ctx):
es= disnake.Embed(
title="⚰️ Louse:",
description="I'm sorry for the preview because I'm not 100/100 right I'm not Premium.",
color=0xef1414,
timestamp=datetime.datetime.now(),
)
await ctx.send(embed=es)
button1.callback = button_callback```
This is code
@slate swan Hello!!
I don't understand that sentence
But why? 
Man
Because you've never defined where button_callback is used
he did 
Well not in that code
I'm lazy to scroll 

And ig it's because it takes an interaction and not a context
But if people never share the error(s) they get ¯\_(ツ)_/¯
I need help with handling errors upon python printing an eror if not having a role anyone know how i can make it so it can just send a message apon the error (im making it so you have to have a role to run a command and the error crashes the bot so i just want to make an error handler)
why
why what
so your intention is to check for roles?
yea but if u dont have it, it just doesnt respond and gives a 100 line error
is there a way to just make it respond with a message
gonna have to set up some error handling
..
i wouldnt ask for help if i didnt need it
did you not read the docs on this?
what docs
the dpy docs
no. i didnt know there were docs
took me less than 10 seconds to get to that link
next time this server should tell me to
read the docs first, and if you have any questions or issues, ask your questions or issues either here or on the dpy server
how add checking permmisions in command
@buoyant echo
If you want help with code, you have to share the code. Put it in a pastebin
!pastebin
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.
@remote bough ^^
!pastebin
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.
@proud vector ^^
lmao actually laughting out loud rn
@remote bough please read the box about how to use the pastebin to share your entire program.
that doesn't seem respectful...
`import discord
from discord.ext import commands
client = commands.Bot(command_prefix = "!")
@client.event
async def on_ready():
print("Royal Utilities is ready to be used!")
@client.command()
async def hello(ext):
await ctx.send("Hello, I am the official Royal Practice bot.")
client.run('Token')`
nah it's really obvious and i wanna see if this guy gets it or not
please stop. there's no need to mock people.
ok then
@proud vector here is the code
i'll just tell you it's a very small mistake that is leading to the error
your last line has ctx, but your second-to-last line has ext. Is that right?
can u please be more specific
yera
yea
should they be the same?
and if yes which one should i keep
bingo you finally found it
tbh, i'm not sure. what resource are you using to learn how to write this bot?
almost
im watching a youtube tutorial
can you give us a link to the video at the time it shows this code?
wait i think i fixed it
point is, ctx: commands.Context is always passed in as an argument for commands
It's really important to pay attention to all the details.
thats the error im getting now
idk why
forgetting intents
can you link us to the video you are watching, at the point where it shows this code?
Looking to create a Discord Bot for your server? Well then, this is the first video in my new series in where I should you how to create a fully functioning bot in Python for your server.
In this video, I go over how to setup your discord bot on your server and how to make a basic command.
►Please consider joining my discord server: https://di...
yea this tutorial is outdated by 2 years
the code in the video won't work?
does not. discord now requires message_content intents for all prefixed commands
is there any tutorial for that thing?
no
here's your primer on intents:
What are intents?
As of 2020-10-28, discord requires users declare what sort of information (i.e. events) they will require for their bot to operate.
This is done in the form of intents.
You can read more about intents here: https://discordpy.readthedocs.io/en/latest/intents.html
By default some intents such as members and presences are disabled as they are what is referred to as privileged. Meaning you'll need to take some extra steps to support them.
If you use on_member_* events in your code, without changes your bot will not function anymore!
As of 2022-04-30, discord will require the use of a new message_content intent.
On discord.py 2.0 messages outside of DMs which do not mention your bot will not have message content, embeds, attachments or components without the message_content intent
Read up on privileged intents here: https://discordpy.readthedocs.io/en/latest/intents.html#privileged-intents
so what do i have to change?
include the intents ofc
what about this tutorial
doesn't include intents
it does
where
did you just link another tutorial?
yeah
also misspelled intents (should be discord.Intents.all())
is there the only thing i gt change?
yes, and then make sure that all 3 intents on the discord dev portal dashboard for your bot is enabled
@proud vector @quick brook thank you so much guys
after 7 hours i managed to make it
7 hours?
As mentioned before no. Also, it just has bad practices in general
- Calling the commands.Bot instance, client
- Using requests instead of an async driver
- Adding pass_context in the commands decorator
- Not adding else statements into error handlers, therefore silencing errors for that command
- Changing the bots presence in on_ready
- Using a non-async driver for his database
There are honestly worse ones around, but I haven’t seen any good ones
Between the docs, this server, discord.py server, the hundreds of tags in the dpy server and the GitHub examples there should be more than enough for somebody to learn dpy
The tags in the discord.py server are crazy, there’s so many of them and they’re super useful
This. I pretty much learned more about dpy on the dpy server and the tags alone
Maybe we should make a proper video guide or bot mega guide
Proper implements, proper styling, follows convention and pep8
Like as a collective channel
Probably
How do you ban a VPN?
They're specifically designed to be anonymous
If you're using a proper one it will be
I mean depending on how big the code is, and over how many files it's spreadover it could still be unknown. All it takes is 1 malicious function, that could even be disguised in thousands of lines of code to compromise a system
!d discord.TextChannel.create_webhook
await create_webhook(*, name, avatar=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a webhook for this channel.
You must have [`manage_webhooks`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_webhooks) to do this.
Changed in version 1.1: Added the `reason` keyword-only parameter.
!d discord.Webhook.url
property url```
Returns the webhook’s url.
?
Python?
What other syntax would it be
Well create_webhook is a method of discord.TextChannel
You need a TextChannel object
Well actually more objects have a create_webook method, I'm just assuming you're using a text channel
So this then
No
create_webhook is a method
What isn't
It's right here
discord.TextChannel.create_webhook
method of TextChannel
Explicitly says it's a method
???
I never even linked that
Please show me where I linked it lmao
This is not that lmfao
It's completely different
Okay, but that's not what it's linked to lmfao
You can see the path in the url
And that links to create_webhook, just like the embed
^
create_webook will return a discord.Webhook object
This webhook object has a url attribute which will return the webhook url
Well for the 4th time, create_webhook is a TextChannel object
If you use that code it'll say create_webhook isn't defined
Do you know what objects are
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Oh you're that guy
Yeah this is useless, we're just going to go around in circles again
You're going to just go around in circles with everyone else as well
Objects are one of the most basic parts of coding a discord bot
Most things you're using are objects, with methods and attributes
In this tutorial, we will learn about Python classes and objects with the help of examples.
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
All good reads
I don't spoonfeed
All 4 of those show how objects work
This doesn't
This doesn't
This doesn't
3 should suffice
realpython doesn't force me to create an account either, but I've heard sometimes it does
1 article should be enough anyway, they're all fairly large and objects are one of the more easier concepts in python
YouTube? Right
I mean for more broad python topics youtube isn't bad
Tech With Tim is good
Attributes and Methods at this level wouldn't be that complicated to explain anyway
Wait have you been trying to do this for 10 days
Are these the first OOP resources you've read or have you been given other ones before
how to add user to dict()?
Like any other objects
also how
🤷
some_dict[key] = value
when I run this command ```py
@bot.command()
async def ss(ctx):
pending_tasks = dict()
channel = bot.get_channel(1130900936198475856)
if ctx.author in pending_tasks:
pending_tasks[ctx.author].close()
pending_tasks[ctx.author] = await bot.wait_for(lambda m: m.author == ctx.author and m.channel == channel)
print("hello")
else:
pending_tasks[ctx.author] = await bot.wait_for(lambda m: m.author == ctx.author and m.channel == channel)
print("hi")
this error happen
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'function' object has no attribute 'lower'```
!traceback always send full 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.
[2023-09-22 23:30:12] [ERROR ] discord.ext.commands.bot: Ignoring exception in command ss
Traceback (most recent call last):
File "C:\Users\Hadi\PycharmProjects\pythonProject3ss\venv\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Hadi\PycharmProjects\pythonProject3ss\main.py", line 22, in ss
pending_tasks[ctx.author] = await bot.wait_for(lambda m: m.author == ctx.author and m.channel == channel)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Hadi\PycharmProjects\pythonProject3ss\venv\Lib\site-packages\discord\client.py", line 1947, in wait_for
ev = event.lower()
^^^^^^^^^^^
AttributeError: 'function' object has no attribute 'lower'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Hadi\PycharmProjects\pythonProject3ss\venv\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Hadi\PycharmProjects\pythonProject3ss\venv\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Hadi\PycharmProjects\pythonProject3ss\venv\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'function' object has no attribute 'lower'
The first argument of wait_for should to be a string, not lambda
ah
I forget to put message and check=
also
is that a way to cancel wait_for?
its not working but maybe I should edit something
Create a task from its coroutine, let the task run, cancel the task
how to create task?
!d asyncio.create_task
asyncio.create_task(coro, *, name=None, context=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task) and schedule its execution. Return the Task object.
If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name).
An optional keyword-only *context* argument allows specifying a custom [`contextvars.Context`](https://docs.python.org/3/library/contextvars.html#contextvars.Context) for the *coro* to run in. The current context copy is created when no *context* is provided.
The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError) is raised if there is no running loop in current thread.
Note
[`asyncio.TaskGroup.create_task()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.TaskGroup.create_task) is a newer alternative that allows for convenient waiting for a group of related tasks.
In like what way you wanna use that
I just want if the command used another time the first wait_for cancel and I not understanding asyncio tasks
In situation like "send message with certain text or press cancel button" I would use modal tbh
Generally in situations requiring free input I'd use modal
or just check for an abort message. but i would recommend using modals if you can
the thing I do not working with modals
hi, im new to python and im trying to make an editsnipe command, which basically snipes the last edited msg and i get an error and idk why, my code is below
@bot.event
async def on_message_edit(before,after,message):
global old
global new
global author
old = before.content
new = after.content
author = after.author.id
bot.edited_messages[message.guild.id] = (message.content, message.author, message.channel.name, message.created_at)
@bot.command(aliases=['edit'])
async def editsnipe(ctx):
try:
contents, author, channel_name, time = bot.edited_messages[ctx.guild.id]
except:
await ctx.respond("couldnt find an edited msg to snipe")
return
embed = discord.Embed(description=f'**before**={old}\n**after**={new}')
embed.set_author(name=f"@{author.name}",icon_url=author.avatar)
await ctx.channel.send(embed=embed)```
Not learning new = never progressing
I know how to use modals
Common problem of beginners here is they are scared of classes for some reason
but the bot wait message from another bot not from user
why have it wait for a message from another bot? seems like bad design imo
Error is pretty clear
im aware, but idk how to fix it
also how to cancel the wait_for?
Just fix the indents!
learn python first and then come back to dpy. dpy is a highly advanced library which expects you know multiple advanced concepts (such as asyncio, OOP, etc)
The red marked lines do not match any previous indentations
ohhh i see, thank you
can you give me example?
just fixed it
!e
import asyncio
async def func():
print("Running")
await asyncio.sleep(1)
print("Ended")
async def main():
await func() # cannot be cancelled, with the only exception of KeyboardInterrupt
task = asyncio.create_task(func())
await asyncio.sleep(0.1)
task.cancel() # cancel the task
print("Cancelled")
asyncio.run(main())
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Running
002 | Ended
003 | Running
004 | Cancelled
# instead of this
whatever = await bot.wait_for(...)
# do this
task = asyncio.create_task(bot.wait_for(...))
# to cancel
task.cancel() # i forgor if it's async tho, prolly not
🥄
I want to specify the user
Comically large
make a check func and pass that in to the check kwargs
🦶
Wait, didn't we talk about this yesterday already? 
you can't specify a user to wait for fyi
You're stuck in eternal cycle
I want if the same user of command use it another time the wait_for cancel for the past use
Yea, use max_concurrency
no
then you dont need that wait_for. either max_concurrency or figure out a new design
Aw heck didn't know it exists so I made a fricking decorator from scratch
I know it
but I want to cancel the wait
poggers raw impl
not make the user wait until the first wait ends
def session_restricted(coro: commands.InvokableSlashCommand | None = None):
"""
Applies session restriction to the command. **Must be above command decorator**
:return:
"""
async def before_invoke(_, inter: disnake.ApplicationCommandInteraction):
name = inter.application_command.qualified_name
if name not in _cmd_sessions:
_cmd_sessions[name] = set()
_cmd_sessions[name].add(inter.user.id)
async def after_invoke(_, inter: disnake.ApplicationCommandInteraction):
name = inter.application_command.qualified_name
try:
_cmd_sessions[name].remove(inter.user.id)
except KeyError:
pass
def check(inter: disnake.ApplicationCommandInteraction) -> bool:
try:
if inter.user.id in _cmd_sessions[inter.application_command.qualified_name]:
raise CommandSessionViolation()
return True
except KeyError:
return True
def deco(_coro: commands.InvokableSlashCommand):
_coro.before_invoke(before_invoke) # type: ignore
_coro.after_invoke(after_invoke) # type: ignore
_coro.add_check(check) # type: ignore
return _coro
if coro is None:
return deco
return deco(coro)
😭
spawn task -> store task somewhere -> cancel if it exists for next invoke, max concurrency is better than this hassle tbh

That's exactly what I made for an example yesterday 
the example not specify user
then how does the user plays into this
I just give you the idea and a pseudo code of how it can be implemented
Then you can implement it in your code on your own
exen the spoon feeder pls spoon feed me
great news i'll work on #198 today

spoon feeder are cool
Can't tell
Some people can pretty much learn from code they are provided while some just take it and don't give a f what it does
Spoonfeeding first type ain't even spoonfeeding
ikr they're everywhere
fr
?
oh mb
not me lol
alg
ur pronouns distracted me lol
?
"sssssssssssssssssss" xd
thats for pronouns?
yeah?
oh it is
hmm
Disable the buttons after you've clicked once if that's your question
Button.disabled = True
In the callback duh
In the callback.... and what is even that code that I just saw
1 space indents 
IN the callback
And do you even understand OOP
If not consider learning it before using a library like discord.py made for advanced developers
Yeah then learn python
No you don't
At least not what you should know to use an advanced library like discord.py
Then do you know ALL of these concepts?
- Primitive data types
- Operators
- Data structures
- Importing
- Variables, namespace and scope
- String formatting
- OOP
- Control flow
- Exception handling
- Function definitions
- Classes, objects, attributes and methods
- Console usage, interpreters and environments
- Decorators
Useful to know:
- Asyncio basics
- What is blocking?
- Logging
- knowing how to read docs properly
``` for more details see <https://gist.github.com/scragly/095b5278a354d46e86f02d643fc3d64b#required-knowledge>
pro
Is there any way to send a message when a member is boosting the server?
wdym?
There is, but no direct event related to it
one approch is using premium_since
and dispatch a custom event 'boost'
!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.
With on_member_update?
@client.event
async def on_member_update(before, after):
if not before.premium_since and after.premium_since:
# Member started boosting
channel = client.get_channel(710249741791002686)
if channel:
await channel.send(f'{after.display_name} started boosting the server!')```
Yeah for example
How would you do it instead?
yes
check if before premium since and after is not equal
if after premium since is none then he/she stopped boosting
!d discord.MessageType.premium_guild_subscription # only if you're sending the default system messages somewhere the bot can see
The system message denoting that a member has “nitro boosted” a guild.
thats a bad approach tbh
Asked how I would do it. That's how I'd do it. Don't care if it's good or bad
oh nvm didnt see
I also wouldn't use @client.event
a. Because it may block other events, so listen is better
b. client
But again, that's also how I'd do it
Why?
if you dont have system channel enabled then its completely useless
or bot dont have permission to view system channel
True
Same for that, I'd also wouldn't do it like that, but rather check if before.premium_since and not after.premium_since to keep consistency. Though there again, how I would do it.
So that's the only negative thing you find about it?
That's why people would set it up.
Though what if the bot doesn't have access to the guild member intent 
you can always do
if after.premium_since is None: or just simplify it using if not after.premium_since why would you add and when you can just finish it off like this way
thats a problem though
but pretty sure every bot needs it [verified]
Remember, the event is triggered for lots of things
You don't want random false positive spam, which you would definitely get 
before.premium_since == after.premium_since easily handles that
what starting point?if you categorize it using cog, its cleaner
no need to clog up all stuff in one listener
Never talked about cogs
"what starting point?" i asked it too
lets no argue over it, every people has their own likings
Also for that, you'd tell them using event is bad at least
(Regardless of cogs that were never talked about)
who said its bad? its pretty good for basic usages, its just bad when we want to use multiple listeners
it was a code from chatGPT anyway [maybe xd] so 💀
i cant expect more from it
Which is what I've responded to, yes 
oh nvm i didnt see you replied to that message 💀 i said to use multiple listener anyway, in cog its always recommended using listener()
but idk what is he even using
it doesnt contain self so prob a normal usage purpose
Can I use if not before.premium_since: as this?
@client.listen()
async def on_message(message):
if message.type == discord.MessageType.premium_guild_subscription:
if not before.premium_since:
channel = client.get_channel(710249741791002686)
if channel:
await channel.send(
f'{message.author.mention} Thank you for boosting the server! :jinx_love~1:')
return```
I want to ensure that the message is only sent if the user is not currently boosting or boosting twice
Maybe check if they have the default booster role that discord assigns
@shrewd fjord @slate swan Sorry for the ping. What do you guys think?
Where do before come from here?
Hmh, should I just use if not message.author.premium_since: maybe?
The type of message. In most cases this should not be checked, but it is helpful in cases where it might be a system message for system_content.
check system content
What do you mean?
print up the message.system_content
You mean message.system_content instead of if message.type == discord.MessageType.premium_guild_subscription:
Nope
not sure how system messages works 

It's just message.author
So just check the message type, then use that
here ^ you can just get the user by using message.mentions[0]
Again no
mhm could be, docs dont say
Use message.author
unlss you tried personally
I tried, and it's like that in discord.py's source as well
mhm nice
So I could use if not message.author.premium_since: to check if they already have boosted?
@bot.event
async def on_member_update(before, after):
if after.premium_since and (not before.premium_since or before.premium_since != after.premium_since):
Found this
No, since the message is sent only when a user boosts
So you just need to check the message type, that's it
I only want send the message once even if they boost the server twice
Boosting = Don't send message
Not boosting = Send message
Then you can use it ig yeah
So this should work?
@client.listen()
async def on_message(message):
if message.type == discord.MessageType.premium_guild_subscription:
if not message.author.premium_since:
channel = client.get_channel(710249741791002686)
if channel:
await channel.send(
f'{message.author.mention} Thank you for boosting the server! ')
return```
Yep
Well that is not what I want
give it a try actually
not sure
premium_since could be either None or it could be not None based on when 'message' dispatches
!paste
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.
You need to respond to the interaction
!d discord.InteractionResponse.edit_message
await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=..., delete_after=None)```
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.
bro is it InteractionResponse?
If you want to edit the message, use this method
oh yeah 
🤷
await interaction.response.edit_message(content="Read the docs")
Is there any way to check that?

how to fix this error discord.player ffmpeg process 2448 successfully terminated with return code of 4294967294.
!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)
i only play a audio file
oh alright
how to fix its sir
not really a ffmpeg expert but you can either wait for someone to answer here, or make a post in #1035199133436354600 for quick help
Could you show the code?
It just looks like an info log. What issue is it causing?
Such a weird return code for success.. Why not zero
That's not a success but a "successful termination". The return code is that weird either because it's windows or process broke and gave unclear exit code
I think
That question is on stackoverflow without answer https://stackoverflow.com/questions/76862540/using-discord-ffmpegpcmaudio-with-youtube-dl-results-in-file-not-found-from-ff
But that's ytdl
async def play(ctx, filename):
voice_client = ctx.guild.voice_client
if not voice_client:
await ctx.send("I'm not in a voice channel. Use `!join` to join one first.")
return
try:
if not voice_client.is_playing():
voice_client.stop()
print(f"Playing audio from: {filename}") # Debugging line
voice_client.play(discord.FFmpegPCMAudio(filename))
else:
print("Bot is already playing audio.") # Debugging line
except Exception as e:
print(f"Error while playing audio: {str(e)}") # Debugging line
await ctx.send(f"An error occurred while playing audio: {str(e)}")
And that filename is what
Music.mp3
You'd better add a check like
if not pathlib.Path(filename).exists():
await ctx.send("This file does not exist")
return
You sure that file exists in your workdir
Yes
Anyways add that check and see
Ok
And yeah to my knowledge is_playing() always returns False, idk if works now tho
What can I used to play sir
Vc.play
?
is_playing() is not for playing, but for checking if it's playing
It's not playing
You added the check?
Okok i will do it's sir right now showdown my pc so I will do it's in morning sir it's 1am in
In morning will contact to you sir
Hi, is there a way to reset a View's timeout?
Such as if it timeouts.. there a way to send it again with timeout reset?
Why not set its timeout to None
is the documentation updated for slash commands? I tried to follow a tutorial for slash commands on youtube but im getting the
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'toggle' raised an exception: AttributeError: 'InteractionResponse' object has no
attribute 'send'
even tho thats what the tutorial said
It never had send method
!d discord.InteractionResponse.send_message
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.
i might have had a brainfart
Not sure what tutorial you're using but it's definitely wrong
i put send.message instead of send_message 😭
i am currently working on that w/ nanika
Nonetheless, here is a slash commands guide:
Here is a short example of how to use discord.py's slash commands as well as general information on them:
https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f
This currently covers free commands and groups at the Bot level, as well as within Cog classes.
It also includes information and gotchas relating to syncing and whatnot.
NOTE: This will be migrating to https://about.abstractumbra.dev/ as soon as I can be bothered to finish it.
My site for random things and stuff. Including a custom pip index and walkthroughs, both for discord.py!
Pr for the slash command guide if you are curious: https://github.com/Rapptz/discord.py/pull/9557
is there a replacement to commands.has_role for slash commands?
!d discord.app_commands.checks.has_role
@discord.app_commands.checks.has_role(item, /)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_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.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingRole) if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.NoPrivateMessage) if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure).
New in version 2.0...
Github examples
Docs will help a lot
Beginners ignore the docs like the plague, don't do that
They're extremely useful
You'll learn
In the discord.py server you can use the r. danny bot to search for shit
Let me show you an example
have a look at github examples page, also you should learn Python in principle
Links to the docs
Very useful if you don't know the path for stuff
Hmm?
The official discord server for discord.py
dpy
It's linked in the docs as well
Just saying, depending on how you act you might potentially get clowned for being a beginner at python
This discord server is aimed at all stages of learning
Beginners are especially welcome
Well they help new people, but sometimes people get a little frustrated
Anti spam shit
What are you trying to search for
I usually use playground
Anyway, delete_role isn't a thing
You'd need to use
!d discord.Role.delete
await delete(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the role.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles) to do this.
I agree with them
If you don't know how to set an attributes value you're going to get stuck doing anything else
There's 3 of us trying to explain to you how to set an attribute for 25 minutes now
Just learn OOP for 2 weeks and this will be infinitely easier for you
dedication
you just check the possible cases where create_role should exist, like you can ONLY create a role within a guild, so you might check out the Guild object in the docs, thats how i used to find it, like create_thread exists in two cases, one channel and two message, so create_thread exists in both channel and message objects
Does discord.py not have full support for buttons?
it has?
It does
robinn :
It doesn't shows how to use callback function
!d discord.ui.Button.callback
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.
^
Ohh thanks
np
robin, mastered rust? 💀
Turns out I only looked at models not
Ty
!d
you know... #bot-commands exists
ok
Can someone help me with this code please? I made it a while ago and it was working completely fine until i moved it into a cog. Here's a summary of the error TypeError: argument of type 'Interaction' is not iterable I haven't coded for a while so i can't remember how to fix it 😅
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='!', intents=discord.Intents.all())
class math(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print("math cog loaded\n-----")
@client.tree.command(name="math", description="Evaluates any math expression")
async def math(interaction: discord.Interaction, expression: str):
symbols = ['+', '-', '/', '*', '%']
if any(z in expression for z in symbols):
calculated = eval(expression)
embed = discord.Embed(
title="Math Expression",
description=f"`Expression` {expression}\n`Answer` {calculated}",
color=discord.Color.red())
else:
await interaction.response.send_message("This isn't a math problem")
await interaction.response.send_message(embed=embed)
async def setup(bot):
await bot.add_cog(math(bot))
You forgot the self argument for the method math
btw remember that with your current code anyone can do anything with your pc - stole data, destroy it, etc
because you gave an ability to run any python code
once I made a Bot go offline 5 times with this input: 240**240**240
this is not even the worst
You should look into using a math API to be on the safe side
240^240^240?
that just, works?
i've made it so it ignores everything that's not a number
i just tested it
mh depends on the machine power but that wasn't working for that Bot, even the python interpreter takes a lot, you know CPU bound
btw eval is not thread safe
its very easy to sneak in a expression or symbol like that
at the very least use ast.literal_eval
okay
.
Really?
!e
import ast
ast.literal_eval("1+1")
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 2, in <module>
003 | ast.literal_eval("1+1")
004 | File "/lang/python/default/lib/python3.11/ast.py", line 110, in literal_eval
005 | return _convert(node_or_string)
006 | ^^^^^^^^^^^^^^^^^^^^^^^^
007 | File "/lang/python/default/lib/python3.11/ast.py", line 109, in _convert
008 | return _convert_signed_num(node)
009 | ^^^^^^^^^^^^^^^^^^^^^^^^^
010 | File "/lang/python/default/lib/python3.11/ast.py", line 83, in _convert_signed_num
011 | return _convert_num(node)
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/LT75ZVUMFPJ6LYGUULKBUB5ZTI
240**240**240, not 240^240^240
there is no way your python can calculate the first one fast
yeah i know, i was just confirming that it was "to the power of"
mh my local python is not even able to calculate the former fast
yeah, tested that and crashed my bot, like you said
i meant the first one, second is easy to calc
that's because eval is not thread safe
how would i make it thread safe?
the eval is blocking the event loop and your Bot is not able to send heartbeats to discord, hence discord assume that your Bot is dead and kill the connection
!d asyncio.to_thread maybe this
coroutine asyncio.to_thread(func, /, *args, **kwargs)```
Asynchronously run function *func* in a separate thread.
Any \*args and \*\*kwargs supplied for this function are directly passed to *func*. Also, the current [`contextvars.Context`](https://docs.python.org/3/library/contextvars.html#contextvars.Context) is propagated, allowing context variables from the event loop thread to be accessed in the separate thread.
Return a coroutine that can be awaited to get the eventual result of *func*.
This coroutine function is primarily intended to be used for executing IO-bound functions/methods that would otherwise block the event loop if they were run in the main thread. For example:
okay thanks 👍
would this also work?
@client.command(name = "math", aliases = ["calculate", "solve", "calc"])
async def math(self, ctx, *, expression: str):
try:
answer = numexpr.evaluate(expression)
await ctx.send(f"{expression} = {answer}")
except:
await ctx.send("That isn't a math expression!")
scrapped slash commands, id rather have prefix commands
i guess that thing is not thread safe
is numexpr a blocking package?
i don't know, all that i know is that numexpr.evaluate is made specifically for mathematical expressions
i only skimmed through the docs
It probably wouldn't block so long that it would be a problem anyway
i'll see if i can run console commands through the command
i tried running a basic print command and it didn't work
nothing outputted to the console
yes
depends on the input
so is it safe? can anything malicious be run?
in that sense no, i haven't personally used it but most likely it doesn't evaluate invalid math expressions
but if you put it like that your Bot will still crash / fall back in the connection
why this return None?
message = await interaction.response.send_message("جاري صنع التكت ...", ephemeral=True)
Because it doesn't return something
isnot should return the msg object?
then, how to get the message
!d discord.Interaction.original_response
await original_response()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Fetches the original interaction response message associated with the interaction.
If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message) or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).
Repeated calls to this will return a cached value.
thx
Did you read?
need help with this, it worked until i moved it into a cog, pretty sure because there's no asynchronous main function in the cog. i can't add one because there's already one in main.py, any ideas on how to fix it?
class guess(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print("guess cog loaded\n-----")
@client.command(name="guess", description="Guessing Game!")
async def guess(self, ctx, max_guesses: int = 5, max_number: int = 10):
number = random.randint(1, max_number)
await ctx.send(
f"The guessing game has started!\nPlease guess a number between **1-{max_number}**\nYou have **{max_guesses}** guesses"
)
def check(m):
return m.author == ctx.author and m.channel == ctx.message.channel
for i in range(max_guesses):
guess = await client.wait_for('message', check=check)
try:
int(guess.content)
if guess.content == str(number):
await ctx.send(
f"You guessed correctly! It took you {i+1} tries.")
break
elif guess.content >= str(number):
await ctx.send(f"Lower!\nYou've guessed {i+1} times")
elif guess.content <= str(number):
await ctx.send(f"Higher!\nYou've guessed {i+1} times")
except:
await ctx.send("That isn't a number!")
else:
await ctx.send(
f"You Lost! You ran out of guesses\nThe answer was **{number}**")
Here's the error: AttributeError: loop attribute cannot be accessed in non-async contexts
i'm sure it's something really simple but i'm stupid
full error
!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.
@discord.ext.commands.command(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command) or if called with [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.group), [`Group`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Group).
By default the `help` attribute is received automatically from the docstring of the function and is cleaned up with the use of `inspect.cleandoc`. If the docstring is `bytes`, then it is decoded into [`str`](https://docs.python.org/3/library/stdtypes.html#str) using utf-8 encoding.
All checks added using the [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
i can copy the error but it won't be exact because i'm not on pc because i'm not home
instead of client.command
in which line the error occured, do you know?
i'm using client.command because i'm not familiar with commands.command
its the same
just replace it
yeah it's guess = await client.wait_for('message', check=check)
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). 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) 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) 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 ran out of ideas
hmmm use await ctx.bot.wait_for(....) instead
i forgor abt the breaking chages about asyncio in dpy lol
since client isnt defined under async context thus it raised the error
also rename your cog to Guess
There's a lot wrong there, see the examples here: https://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html
Then compare with your code, you should see quite some issues
there shouldn't be anything wrong since i cut it straight from my main.py
it's called guess
There is
nope
i just changed client.wait_for to ctx.bot.wait_for and it worked





