#discord-bots
1 messages · Page 1049 of 1
await fetch_webhook(webhook_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Webhook`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook "discord.Webhook") with the specified ID.
Changed in version 2.0: `webhook_id` parameter is now positional-only.
how do i use events and commands at the same time
cuz commands doesnt work if there r events
thats not true, you are doing something wrong
change the decorator of your on_message event from .event to .listen()
umm guys is ther other new hosting for discord bot py?
i tried that
if i use listen then commands doesnt work
besides heroku?
uptime robot with keep alive
thats not a host and see the pins of #965291480992321536
show code
k wait
@bot.event
async def on_message(msg):
embed=discord.Embed(title=">:(", description="Bot angry now", color=0xff0000)
embed.set_author(name="no u")
embed.set_footer(text="dont ping bot")
if '@spice sparrow' in msg.content:
await msg.channel.send (embed=embed)
@slate swan
it will works with that?
oh yes tysm
so if i do client2 = discord.Client.fetch_webhook(974880363572772874)
client2.send('Hello!')
that gives me an error tho
thats not how object oriented programming works
would this work if the emoji isnt in the same servers as my bot?
i think you forgor two awaits
client2 = await discord.Client.fetch_webhook(974880363572772874)
^^^^^^^
await client2.send('Hello!')
^^^^^
i dnt think so
thats not how they use the fetch_webhook method either
await fetch_webhook(webhook_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Webhook`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook "discord.Webhook") with the specified ID.
Changed in version 2.0: `webhook_id` parameter is now positional-only.
they need to use a discord.Client instance, and use fetch_webhook on it, not the class straight
"this is a string".upper() is what they should do
str.upper() is what they are doing
ah okay how else can i get the image of a emoji via the id? i tried what i sent above but i couldnt get it to work
oh yeah that
use fetch_emoji ig
!e discord.Client.fetch_emojo
now that's just sad
:sadge:
lmao
would this not do the same?
the heck does that not exist?
!d disnake.Client.fetch_emoji
No documentation found for the requested symbol.
class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord.
This class is used to interact with the Discord WebSocket and API.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
get_emoji(id, /)```
Returns an emoji with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
aha
how can i get the image from the emoji to then create another emoji from it?
im using snekbox in my discord bot, how can i run a docker command to set it up in my procfile in heroku?
i wanna run this command, but it says docker can't be found docker run --ipc=none --privileged -d 8060:8060 ghcr.io/python-discord/snekbox
Hi my discord bot broke down suddenly
It was running normally before its broke down
This is the error please help me check that
Thank you!
avatar = member.avatar_url_as(size=1024, format=None, static_format='png')
is this correct ?
you are rate limited
Can I do something to solve that
no
You've done something against discord Policies and Agreements
you can read more here https://discord.com/developers/docs/policies-and-agreements/developer-policy
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
can u show code
Thanks lemme check the policy
you were spamming the API
!disnake.Guild.fetch_emoji
!d disnake.Guild.fetch_emoji
await fetch_emoji(emoji_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a custom [`Emoji`](https://docs.disnake.dev/en/latest/api.html#disnake.Emoji "disnake.Emoji") from the guild.
Note
This method is an API call. For general usage, consider iterating over [`emojis`](https://docs.disnake.dev/en/latest/api.html#disnake.Guild.emojis "disnake.Guild.emojis") instead.
lol
Can I try to start the bot later
So who wants to help me collect most frequently asked questions in this channel? 
yes
weird that they made it a guild method even tho it has nothing do with a server other than its usability
Oh ok thanks
bruh that method retrieves custom emojis
common emojis are not even an instance of the Emoji class
they're just unicode code
discord.com/emojis/id is the endpoint for a custom emoji
Yeah but custom emojis are created in guilds
as i said, "other than usability"
why will you even need to retrieve an emoji from an external guild? the bot won't even be able to send it
they want to get its bytes and upload it to their server
to do it the bot needs to be in that guild
GET /guilds/{guild.id}/emojis/{emoji.id} is the endpoint given in the docs
I've never seen the endpoint you said
discord/http.py lines 1344 to 1348
def get_all_custom_emojis(self, guild_id: Snowflake) -> Response[List[emoji.Emoji]]:
return self.request(Route('GET', '/guilds/{guild_id}/emojis', guild_id=guild_id))
def get_custom_emoji(self, guild_id: Snowflake, emoji_id: Snowflake) -> Response[emoji.Emoji]:
return self.request(Route('GET', '/guilds/{guild_id}/emojis/{emoji_id}', guild_id=guild_id, emoji_id=emoji_id))```
So obviously it would be a method bound to a Guild instance
oh makes sense , but isnt the emoji just readable by its url?
That's just like any other URL
i got that wrong because in many libraries its just a client method
@slate swan can I add you on discord and message you privately?
hikari: https://www.hikari-py.dev/hikari/api/rest.html#hikari.api.rest.RESTClient.fetch_emoji
djs does something like client.emojis.cache.find
um, why tho?
to not spam server chat
You'd need access to the guild though
yeah, true
Hi sarth
so they gotta read the emoji using aiohttp
If you want to get the bytes of an emoji, have the emoji CDN url. Make a request, then read the data() of it
hi
Hello I have a question... Is it possible to get a user avatar in current guild and not default avatar
!d discord.Member.display_avatar
property display_avatar```
Returns the member’s display avatar.
For regular members this is just their avatar, but
if they have a guild specific avatar then that
is returned instead.
New in version 2.0.
you will need to pass the member as parameter of your command
no you have no member paramater in that
how to do it?
you can't develop a bot if you don't know python basics
help and spoonfeeding are two different things 
https://docs.disnake.dev/en/latest/ext/commands/commands.html?highlight=command
This is commands documentation
await ctx.send(...)
Let's spoonfeed help!
Discord functions are coroutines, I dont know the details but they are asynchronous
So you have to await when calling, that's why await keyword exists
async and await go together, if you add async to a function you have to await
Thank you, I could no find i anywhere
Does it return the url like avatar_url too or an image object
class discord.app_commands.Group(*, name=..., description=..., parent=None, guild_ids=None, guild_only=..., default_permissions=...)```
A class that implements an application command group.
These are usually inherited rather than created manually.
Decorators such as [`guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only "discord.app_commands.guild_only"), [`guilds()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guilds "discord.app_commands.guilds"), and [`default_permissions()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.default_permissions "discord.app_commands.default_permissions")
will apply to the group if used on top of a subclass. For example...
like this?
async def assignrole(ctx, member: discord.Member, role_id):
role1 = discord.Role.id(role_id)
await member.add_roles(member, role1)```
```Ignoring exception in on_command_error
Traceback (most recent call last):
File "/home/runner/Rolands-Final-Project/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 95, in assignrole
role1 = discord.Role.id(role_id)
TypeError: 'member_descriptor' object is not callable```
Idk what I'm doing wrong still
https://paste.pythondiscord.com/wajuvejuxa Someone help with this code please
Hi, I used it but I get an error.. Member object has no attribute display_avatar
display_avatar only exists in the 2.0 version of dpy since guild avatars hadnt yet existed when 1.7 was released
to get a Role object from an ID you should use the Guild.get_role(id) method, where the guild can come from member.guild
as well, add_roles() doesn't need to take member as its first argument
role1 = member.Guild.get_role(role_id)
await member.add_roles(role1)```
so like this?
the guild attribute of member is lowercase but otherwise thats right
hm actually if that assignrole function is a command, you could use the role: discord.Role converter rather than manually getting it
oh my god thank you, I've been working on that for 3 days
hello. why this for guild in client.guilds:.... for loop can make sure the script could find matching guild.name before printing f'{guild.name}(id: {guild.id})', if I correct understand what he is trying to do?
Thank you
client_id = ""
client_secret = ""
redirect_uri = ""
code = ""
auth = Auth(client_id, client_secret, redirect_uri, code=code)
api = Api(auth)
Guys i installed a unsplash python api wrapper
There is was written that i need to put the following code
So i have to put client id and secret of my bot or api
It's not written in documentation
once that if-statement succeeds and the for-loop breaks, the guild variable will remain assigned to whatever guild you're looking for
this is the feature of python? or just for this discord package
the for-loop variable existing after it's completed is a python feature
It's just for knowing which guild bot is
It's feature of discord.py
Just checked it, it is a bad one
Will anyone here help me at it
but it should be like this? after break ing the for-loop, the program back to that level of scope
scope 2 won't change scope 1 if I understand correctly
in python control structures like for-loops dont create new scopes, so whatever you assign in that for-loop will be in the function scope
id suggest a help channel for your question with the unsplash API since its separate from the discord API that this channel is related to
which units has its scope? context managers? functions?
Does it mean I have to update discord.py
to get that feature yes, but you should read the "migrating to 2.0" page before doing so since there's a lot of breaking changes to be aware of (e.g. avatar_url being removed)
https://discordpy.readthedocs.io/en/latest/migrating.html
bad one?
from what i can think of, functions and classes
there's a bit about it in the python documentation here: https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces
Ok, I'll update and see if I get any errors
Is this correct? (the constant is a list)
if any(role in member._roles for role in GLOBAL_CODM_ROLES):
and also would lambda be more suitable for this, or not?
Your assigning a member decorator in the middle of a role declaration.
@unkempt canyon
!eval if any(role in member._roles for role in GLOBAL_CODM_ROLES):
@muted dagger :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | if any(role in member._roles for role in GLOBAL_CODM_ROLES):
003 | ^
004 | IndentationError: expected an indented block after 'if' statement on line 1
this is correct
correct
and the lambda part, below that question above?
i think the indent error might be because of the chat and its nature
where are you planning to implement that
inside a map/filter?
nope, just for ```py
check member roles
if true: do something
else: else: do nothing
the if statment with "any" is fine ig, no point of making another lambda
sorry, wrong statement
You may wanna provide that as a variable directly in your bots code, and instead of declaring api as a variable, put the api url in the bots command/
YEAA LETS GO
dont argue with sarth trust me he's gonna leave you in a mess 💀
its funny watchin a person just going sentimental at sarth and him not even caring.
I updated discord.py to 2.0 but now no command is working and I dont see any error
Do you have on_message event?
also, message_content intents
its most likely due to the message content intent since updating to the master version "does not create a message event" by itself 😔
Yes, I also call process commands
I use intents too, default
Could it be the issue
Ooh I see
yes, message content is privileged as of discord api version 10 (which the alpha version uses)
Ashley tell me some of the dumbest question you've ever read here
so you will have to explicitly define those
intents = Intents.all()
intents.message_content = True
dont ask questions about dumb questions from dumb people 😔 I may not be the right dumb person to answer that
I got an error, I have to go to developer portal
i'm making an extension for the python bot which answer those dumb questions 
Because I had already enabled intents before
yes, you have to enable the intent from the dev portal - https://www.discord.com/developers/applications
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
would be annoying, how do you plan on answering those questions back?
and i don't think that you're dumb, you're pretty better then most of the people here
whatever
The idea is different btw it is based on sentence similarity
yeah yeah, I understand that but, where does the bot send the message that answers the dumb question
simping in chat rn
excuse me?
i said, simping in chat rn
Just enabled in portal
Lot of stuff changed in 2.0
well in the channel where the dumb question is sent
Yeah i know that people would abuse that, i studied automation so i'm used to release product to ignorant people, there will be some advanced checks
I still get the error, shard id none is requesting..
would be annoying af if it did spam all that shit, good luck though
don't worry i will be accurate 
turn Intents on in the dev portal
over-confidence hm yeah maybe
I'm dumb, I forgot to save changes
zamn

over confidence is everything
i would not come that far if i would not be it
Bot is working, thank you for your time
sheesh
yeah, Blvck is a really nice and busy person yet he spares his time to help people, such a beautiful person :)
is 2.0 released already or is it still in beta?
beta
The only truth there is that i'm a busy person 
He surely is, I didnt want to go to so and you know why lol
no, I said what I said
understandable
doesnt work
welp i mean, if you think so 
What doesnt
none of the commands do
prefix is pepe
weird
what does it do
Ash is not kindly judge others work "weird"
Makes pepe signs, you know the frog ?
I need answers
yeah, so like the emojis and all?
id like to check that out
Yes, there are many commands
It uses pillow right?
Of course
Nice
idk, it should, but the existed is literally out of the gif....
😔
needs some more calculations
Someone on discord makes them manually, he sent me the templates and I started the bot from that
eh, no biggie, its easy to fix.
This is how I learned discord.py
still, as a consumer, I'm disappointed
you should reduce the text size based on the amount of characters for it to not get out of the "board"
lining
poor guy, just let him code in peace
Yes, very long texts appear outside and very short texts dont show well
useless since text in PC and mobile takes different size 
I'm still disappointed
Pasta isn't a mess
bro, just wrap the text.
now i'm offended too
why ae you contradicting eveything hes saying bro, wtf did he do to you

I did, but the gif makes the sign go up and down
hes using a metaphor chucklenuts
Bruh?
Yea, bit messy aye?
So I had to make changes to x y for each frame
I need more answers, the whole text doesnt even fit inside the gif
OH FKJFIF
That wouldnt even show
um what
it would just be an string argument for python, he just writes the string on an image using pillow, how does that relate to a user's client device
If you upload it as an emoji
its the image that resizes not the text,
still, why would it care about your device?
@digital mason just a suggestion, in your pepecry command, it deleted the user message and doesnt respond when no text is provided, you can send a "please provide some text" message or something so the user doesn't stays confused what happened
All the commands call the same function
Depending on which mood, so I'll have to make some changes
anyone else just sit and stare at print outs while people use their bot like 
do you mean errors by "print outs" ? or some kind of command loggings
yeah just logging the state of the game at each interaction, much easier to trace back solutions any bugs that might happen
Is it possible to hide a command from help
yeah just add a hidden kwarg which accepts a bool to the command decorator
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
If you’re collecting information like guild names, user names, any IDs, or really any other data make sure your users know and consent to it
but still
Yes, but the question itself is not
^
@client.command()
async def image(ctx,image):
image = requests.get(f'https://source.unsplash.com/720x600/?{image}')
await ctx.send(image)
Guys my command is not working
Can anyone help me?
obviously need all of that for save files to remember players and for the game to function?
Right, still make sure you explicitly say that
@client.command()
async def image(ctx,image):
image = requests.get(f'https://source.unsplash.com/720x600/?{image}')
await ctx.send(image)
Guys my command is not working
Can anyone help me?
I did
If they play the game, they accept to that data being collected
i emailed discord about data collection a while back to clarify for my first bot and got a form response
I gave you such a big example of aiohttp and you're just like using requests again 😭
Cool, do what they said then and generally just be respectful of others data
“Not working”?
Ik but aiohtto is going up of my brain
i see no other bots do this in a way that's explicit?
of course, i follow common sense
Ye
They’ve probably got it in their terms if service on their website
I made that Pokemon command with you help
Either that or they’re not collecting data
Thank u
....uh
why do u need to send a request, just send the url. Discord will render the image
Hmmm ok
isn't a TOS a requirement when your bot gets over a certain amount of guilds now?
Not sure about that
in the developer portal for each bot rn, heard from others that you're required to fill it at some point
Ah yeah
either way sounds like a good idea
Does your bot have a dashboard?
If so I’d create a page there for terms of service and link it
it is required at time of verification now
i just use my bot's github wiki page
That’s probably what I’m gonna do if I decide to go commercial with my bot
Yeah, a web dashboard to manage your bot from online
Guys how to fix this
I’d recommend next js which is what I use 😊
you are using 2.0, intents kwarg is required
Hmm how to
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
Ok
How do people actually code on their phones. That gots to be so painful.
Thank you, it worked. I also showed messages like provide a text when no text was given, but if the command arg is strong typed, like doscord.Member for example, an exception is thrown and caught by discord, so the command stops and I dont have a way to show the error message
similar but you don't need the .members if you don't need it
tempted to build it all in python 
The backend? Sure
people get so mad if you say you'll do the front end in python 
pyscript~
is message_content in default intents? he probably gonna need it too
good point.
A dashboard is not very static, so you’re gonna need a JavaScript framework
huh? wdym? what are you typehinting the parameter as which accept the argument?
nope, its privileged
😤 gonna have to learn it properly aren't i
Because if I dont by default that message is a string and if I tag someone I get the id like <@xxxxxxx>
i have a phobia of curly brackets
add some checks?
I am getting this error now
Gotta get used to it
Oh
Remove the ()
But how
arg is str
Wait I think I have already made checks
Dammit I hate if elses 
shakes his fist at python's keywords
use RegEx as an alternative, its still faster than conditionals
!pip regex
@client.command
async def image(ctx,image):
await ctx.send(f'https://source.unsplash.com/720x600/?{image}')
My command not working
wait
....? uh
what the heck is that command
What's error in it
I have functions that match channels, user mentions
he probably needs message_content intent now
how do you even expect users to match the same names to the images 😭
@robust fulcrum if that may the issue be
Hmm
@client.command() You forgot parentheses
Hi lieing Im Vanni
hm?
im giving him right information
I'm going blind every passing second
you're right
and there we go again
Someone said it before
again?
Then you will miss all the hilarious thing that happens here
you forgot to call client.commad
no
I'm too lazy to get my glasses 😭
command doesnt have any phone no. cant call
-_-
lmao
Btw can we use code of @unkempt canyon in our bot?
it does have a phone
its a callable🤙
can u give me ill dial
It’s FOSS, so yeah
sure its ||never gonna give you up||
Can you tell how to set-up it there no setup guide for it
i cant see its black
press the button
You just need docker and the proper env vars
Whats docker?
see
i should learn about containers and envs
Popular DevOps tool
Ok
yes
I just need to fill env?
And run docker compose yeah
doctor?
At least I think it’s docker compose
Robin is a doctor yes
wow
I have a doctorate in discord bots
Dr robin
see
"trust me, I'm a doctor"
Dr. Robin
and you nurse?
yup
MIss. okimii
Nah he’s a desk clerk
ok
Miss. hunter

I ain't capable of getting one lol
@nova summit decorator
ok setattr
tf, didnt mean to ping
Uh
😔
lol
The name is Hunter
it didnt ping in the preview anyways, moving on
🤔
Cool
hi im okimii
Hello, why all parameters are marked optional, when one of them is required?
пользователь = Option(
name = Localized(
"пользователь",
data = {
Locale.en_US: "user",
Locale.ru: "пользователь",
Locale.pl: "użytkownik"
}
),
type = Member | User | int,
description = Localized(
"рецидивист",
data = {
Locale.en_US: "user to ban",
Locale.ru: "рецидивист",
Locale.pl: "przestępca"
}
),
required = True
),
время = Option(
name = Localized(
"время",
data = {
Locale.en_US: "time",
Locale.ru: "время",
Locale.pl: "czas"
}
),
type = str,
description = Localized(
"время бана",
data = {
Locale.en_US: "time of ban",
Locale.ru: "время бана",
Locale.pl: "czas banu"
}
),
required = False
),
причина = Option(
name = Localized(
"причина",
data = {
Locale.en_US: "reason",
Locale.ru: "причина",
Locale.pl: "przyczyna"
}
),
type = str,
description = Localized(
"причина бана",
data = {
Locale.en_US: "reason of ban",
Locale.ru: "причина бана",
Locale.pl: "przyczyna banu"
}
),
required = False
)

я <-- this letter is pronounced "ya"
english pls
@sick birch me not understanding docker can you pls tell
i dont know french
stop spamming
😂
all yours robin
+3 (optional)
stop spamming lemons
It’s used for containerization of applications and easy set up
All parameters are getting marked optional, but one of them has required = True
bro call me okimii(num="+3")
There is a file called dockerfile
Is it that file?
its positional argument
!e
Print(hi i hate everything/n * 100 +10 lambda x ; [1=1 s1])
@nimble plume :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | Print(hi i hate everything/n * 100 +10 lambda x ; [1=1 s1])
003 | ^^^^
004 | SyntaxError: invalid syntax. Perhaps you forgot a comma?
yes i forgot a comma

That's instruction for docker on how spin up a container
im writing newthon
Hmm so where do I fill env
u will not understand
@sick birch I'll send you my repl invite link will you help me there?
I'll not take much time
!e
print("A man, a plan, a canal - Panama"[::-1])
@heavy shard :white_check_mark: Your eval job has completed with return code 0.
amanaP - lanac a ,nalp a ,nam A
https://www.pythondiscord.com/pages/guides/pydis-guides/contributing/bot/#configure-the-bot see here
A guide to setting up and configuring Bot.
Double checked it, everything is correct, but that parameter is getting marked optional for some reason
🗿
role = discord.utils.get(guild.roles, name="Muted")
is this correct to add a role to the member?
No, that’s how you get a role tho.
shouldnt use utils
Id use utils if I don’t have a role id
i would only use it only in your case but if you do have the id you should use Guild.get_role
since in its base it would be O(1) but can be O(n) which utils always iterates through all of the roles it will always be O(n) while Guild.get_role uses dict.get()
ctx.guild.roles
utils.get is exponential
Now it's really annoying, all parameters on all slash commands are getting marked optional
since it supports nested attribute lookup
Even if they have keyword argument require set to True
or member.guild.roles
is it?
O(n) is best case, worst case is indeterminate
mhm
Can someone help me?
is there any way to run an infinite while loop thats updating a certain embed completely parrallel to a bot?
пользователь = Option(
name = Localized(
"пользователь",
data = {
Locale.en_US: "user",
Locale.ru: "пользователь",
Locale.pl: "użytkownik"
}
),
type = Member | User | int,
description = Localized(
"рецидивист",
data = {
Locale.en_US: "user to ban",
Locale.ru: "рецидивист",
Locale.pl: "przestępca"
}
),
required = True
),
время = Option(
name = Localized(
"время",
data = {
Locale.en_US: "time",
Locale.ru: "время",
Locale.pl: "czas"
}
),
type = str,
description = Localized(
"время бана",
data = {
Locale.en_US: "time of ban",
Locale.ru: "время бана",
Locale.pl: "czas banu"
}
),
required = False
),
причина = Option(
name = Localized(
"причина",
data = {
Locale.en_US: "reason",
Locale.ru: "причина",
Locale.pl: "przyczyna"
}
),
type = str,
description = Localized(
"причина бана",
data = {
Locale.en_US: "reason of ban",
Locale.ru: "причина бана",
Locale.pl: "przyczyna banu"
}
),
required = False
)
you can use tasks
Tasks, otherwise you're going to get ratelimited
ok
i was gonna say it can block your bots heartbeat but you can just create a task with the loop attr in the bot which is literal to a AbstractEventLoop
gosh i love saying that word
youre welcome
Can someone guide me in making a discord bot with discord.py?
im actually new to the library
also not much experience in following docs
We can help with specific œuestions or errors
well sure
A tutorial to help you make better Discord bots.
what is that letter and how did i make it
œ œ œ
ctrl+c
œ ah option + q makes that letter
That's for nextcord and disnake, he uses discord.py
^
?
Not quite, especially the slash / app commands are implemented differently
just check examples on main lol
good to know that my examples at least help people
The concepts are the same, just apply them to discord.py
oh no they make me wanna delete github

In programming the concepts are more important than any library or language, since most of the time they all use the same base concepts, but just reskinned
thank you, that's the effect I was going for 😄
@client.event decorator
this question is about the implementation of decorator.
why we can use this decorator in such way to override event handlers in a Client class definition?
the definition of @client.event:
https://github.com/Rapptz/discord.py/blob/master/discord/client.py#L1104
some example implementation of it:
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$alert'):
await message.channel.send('https://www.tradingview.com/pine-script-reference/v5/#fun_alert')
if message.content.startswith('$ta.wad'):
await message.channel.send("https://www.tradingview.com/pine-script-reference/v5/#var_ta{dot}wad")
discord/client.py line 1104
def event(self, coro: Coro, /) -> Coro:```
I should make more 
😡
Is it possible to make money by creating a discord bot?
im a bit confused on whats your question😅
Sure
Yes
Working as an individual contractor to make bots for people, donations for your bot, paid content, etc
why are u angry
ok
Is this right?

One look at the error logs would indicate the answer to that question
The IDE is literally saying "I wanna punch you. I wanna punch you but i can't"
nah its saying i wanna restart
😭
fyi, you should link tutorial.vcokltfre.dev, that redirect won't be around forever, I'm probably going to put a blog on the apex :P
#discord-bots message then edit your message without the redirect
it was edited yes, but the link wasnt changed
do u guys ever get confused between what to use? discord.py pycord nextcord
not really it really depends on what fork you like the most!
I use disnake
im a pure beginner with these libraries 😂
i mostly like disnake because of their implementation lol
Don't like any of their implementations
Including discord.py
I feel like registration of application commands should be decoupled from application command handlers (your actual code)
honestly disnake has implemented very well application commands
the only thing that is missing is a deco for both application and user commands but tbh is not really necessary
Tbh all of them feel the same to me
with disnake you can just disable syncing commands
nah i tried the most used
That's a step in the right direction
I think if beginners had to register their commands themselves it would discourage people from using it entirely
disnake is absolutely more user friendly
That's a hella lot of friction to make a bot
They had to weigh beginner friendliness with practicality - that's a difficult one
We do at some point want to make it not sync by default, we just need to convince ourselves the fallout is worth it lol
It probably is but that's like asking which js framework is better when you have experience with 2 or 3. Some are gonna have some nice quirks or handling but ultimately not that complicated to learn if you know one or two
just for me that is
wHy mY cOmMaNdS nO wOrK aNyMoRe
PTSD from when message intents were introduced
mmmm that was fun
The era of no traceback but bot no work
anyone have a boilerplate TOS for a bot?
how do I create a command to log off the bot?
so i can limit multiple instances when i forget and am coding on the go
!d discord.ext.commands.Bot.close
await close()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Closes the connection to Discord.
close is not defined
and im using disnake
did you literally just write
await close() and expect it to work
yep lmao oops would i put await bot.close
ok lol I feel so dumb rn
How do I check if the person running the command is the bots owner
!d discord.ext.commands.is_owner , its a check decorator , same for forks too
@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the person invoking this command is the
owner of the bot.
This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.is_owner "discord.ext.commands.Bot.is_owner").
This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived
from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Is it different for disnake?
!d disnake.ext.commands.is_owner
@disnake.ext.commands.is_owner()```
A [`check()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.check "disnake.ext.commands.check") that checks if the person invoking this command is the
owner of the bot.
This is powered by [`Bot.is_owner()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Bot.is_owner "disnake.ext.commands.Bot.is_owner").
This check raises a special exception, [`NotOwner`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.NotOwner "disnake.ext.commands.NotOwner") that is derived
from [`CheckFailure`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.CheckFailure "disnake.ext.commands.CheckFailure").
i literally wrote in that statment....
oh lol i ddnt see that apparenty
Possibly due to pylint
Disable it if it's on
I got over a 1000 errors on a 150 line code because of it
Maybe but I got over 1000 errors when it was enabled
that's a lot
And it worked fine when disabled
Ik
Lower the pylint levels in settings
Idk I'm dumb
Disabling it is the best way
whats the error handeling?
I am saying these are not issues by pylint, they're by pylance if you take the closer look
Ah it might be pylance
And those are syntax errors caused by space + tabs in code
I get mixed up
It is pylance
Ahhh I'm dumb
Then pylance is extremely annoying
I accidentally turned it on
I mean, those are actual syntax errors
Basically when you do something else than just printing traceback on error
It made me delete vscode
Those are actual syntax errors and the code will not work until they are fixed
Said several times
Basically custom error msg
Alr
whats the code in the documentation for errors
Nope not that one
on_error is more low level
No
Quick question what's the difference between client.commsnd and bot.command?
Can you not provide misinformation please
Or is it preferance?
Depends what client and bot are
None, as long as you’re using a Bot object
Names mean nothing to computer
wait is it "pcr" thats a command
@pcr.error
async def pcr_error(self, ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
Ah u beat me to it
Oh god why not use global handlers
Screw local handlers
!d discord.ext.commands.Bot.on_command_error listen to this event
await on_command_error(context, exception, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default command error handler provided by the bot.
By default this prints to [`sys.stderr`](https://docs.python.org/3/library/sys.html#sys.stderr "(in Python v3.10)") however it could be
overridden to have a different implementation...
uhhh does this go in a command ?like:
@commands.commands(name="e")
async def e(self, ctx)
await ctx.send("e a sports")
await on_command_error(context,exception)
#BeDRY
no
it's an seperate func
@commands.Cog.listener()
async def on_command_error(ctx: commands.Context, error: discord.CommandError):
if isinstance(error, commands.MissingRequiredArgument):
...
elif isintance(error, commands.BadArgument):
...
...
else:
raise error```
Very basic error handler
@bot.event
async def on_command_error(ctx, error):
try:
await ctx.send(error)
except BaseException:
print('Error has occurred in error handler! All hope is lost! You may panic!') # hope this code never executes```
it legit happened to me once, an error in the handler
BaseException 😳
We're making the mother of all handlers here jack, can't fret over every exception!
@vale wing :white_check_mark: Your eval job has completed with return code 0.
sus.py:69: Warning: yes
Oof disnake has no
Attribute commanderror
exception disnake.ext.commands.CommandError(message=None, *args)```
The base exception type for all command related errors.
This inherits from [`disnake.DiscordException`](https://docs.disnake.dev/en/latest/api.html#disnake.DiscordException "disnake.DiscordException").
This exception and exceptions inherited from it are handled
in a special way as they are caught and passed into a special event
from [`Bot`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Bot "disnake.ext.commands.Bot"), [`on_command_error()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.disnake.ext.commands.on_command_error "disnake.disnake.ext.commands.on_command_error").
^^ commands.CommandError
!d disnake.ext.commands.Command
class disnake.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.
These are not created manually, instead they are created via the
decorator or functional interface.
hm
hey guys can someone explain me how i can safe id’s in a json datei with a command? And i need to check if a member’s id who sends the bot a dm is in the datei
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "whitelist" is not found
why tf is this happening although its literally a command
is it @bot.commands or @bot.command
@bot.command
async def whitelist(ctx):
bot.command()
fr?
yea
how to get the sent message time
!d discord.Message.created_at
property created_at```
The message’s creation time in UTC.
Does ctx.author.mention not work in embeds?
It does
it does, it will just not ping the member
It just does this... instead of actually pinging
< @317342921739206656> (without the space)
You need to put them in formatted strings
Yeah I tried that as well
Ok, is the member in the server?
note that that won't happen in author, title, field names and footer.
Only in certain fields
Its in a field one
Don’t think it works in field titles
Wont work for the "name", but will for "value"
Okay thanks
Yeah
👀
embed.set_footer(text=("Created on {})".format(ctx.message.created_at.strftime("%d %b %Y %H:%M" ))))
which timezone is this set to ?
property created_at```
The message’s creation time in UTC.
The message's creation time in UTC.
ohk ty

Thank you 🙂
it works in the description, but it doesn't ping
oh yeah I know
you're kinda late HRL
O
Hello. Can anyone send me official discord.py server
Pls ping Me or send me in dms
Can anyone please send me some coding related server in my dms
Thanks
has anyone coded a ai chat bot for discord if so what ai did they use? and was it any good?
I'm wondering why am I getting a "discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0: The specified component type is invalid in this context" while trying to add a TextInput to a view...?
Am I missing something about how to use TextInput like adding them to a form or so ?
async def callback(self, interaction : Interaction):
embed = discord.Embed(color=0x39fe16)
embed.add_field(name="Créer un pari", value="Renseigner les champs ci-dessous", inline=False)
view = View()
view.add_item(TextInput(label="Test"))
await interaction.user.send(embed=embed, view=view)
await interaction.response.defer()
Hey quick question guys: If i have a string that looks like this for example Fhttps://temporaryimport.ams3.digitaloceanspaces.com/metadata/6848.json is there a way ( besides something like link = link[1:71]) to cut out the link by saying start with https and end with .json? So its easier scalable
How to make a link in an embed title?
embed.set_title(name)
embed.set_url(buyNow)```
thanks you
just embed.set_url
You are very welcome
TextInput is not an Item
You need to add TextInput to the modal (the form)
!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...
That's what you need to use, not View for your form @gaunt mortar
Oh ok, thanks a lot 🙂
You can either burn your eyes and use some regex or the good old if str.startswith(string) and str.endswith(string)
!e
link = "https://google.com/yes/no"
print(link.split('/')[2])```
@vale wing :white_check_mark: Your eval job has completed with return code 0.
google.com
Since when can we use !e here 👀
!e
link = "https://temporaryimport.ams3.digitaloceanspaces.com/metadata/6848.json"
print(link.startswith("https://") and link.endswith(".json"))
@stone beacon :white_check_mark: Your eval job has completed with return code 0.
True
always
Although wrong channel mb
the more uk
yup
the world is so huge, there's nothing on it that wouldn't exist
Did discord just break image embeds or something? I didn't change anything here and the images arent in the embeds anymore... The code is retrieving the image just fine; I'm having it print it out in the output, but its just not putting the image into the embed, any ideas? I'm going to try to undo a bunch of stuff I just did to see if thats why, but I really don't think it is
how do you set it
Like this, the same way I was setting it 30 minutes ago when it was working
embed.set_image(url=currentWinner.attachments[0].url)
did you print currentWinner.attachments[0].url ?
seems good
someone just told me its supposed to be .png
even though Idk why png is uppercase
yeah i dont either
I think its cause of the caps, my friend just sent a .png instead of .PNG and his worked just fine
try
embed.set_image(url=currentWinner.attachments[0].url.lower()) then
well maybe not, my .PNG is working now, I think discord just had a really temporary problem lol

So i'm wanting to put info into an embed, but i want to get the information from the databse about that specifc trade, i tried this but it didnt work:
py trade = mycursor.fetch(f"SELECT trade FROM t_info WHERE channelID = {message.channell.id}")
I think this is more related to #databases
you misspelled channel
, its been a hard day at school
what db is this?
mysql
nah then you don't need my note which would've been using parametrized queries
!tags
!repl
Read-Eval-Print Loop
A REPL is an interactive language shell environment. It first reads one or more expressions entered by the user, evaluates it, yields the result, and prints it out to the user. It will then loop back to the read step.
To use python's REPL, execute the interpreter with no arguments. This will drop you into the interactive interpreter shell, print out some relevant information, and then prompt you with the primary prompt >>>. At this point it is waiting for your input.
Firstly you can start typing in some valid python expressions, pressing <return> to either bring you to the eval step, or prompting you with the secondary prompt ... (or no prompt at all depending on your environment), meaning your expression isn't yet terminated and it's waiting for more input. This is useful for code that requires multiple lines like loops, functions, and classes. If you reach the secondary prompt in a clause that can have an arbitrary amount of expressions, you can terminate it by pressing <return> on a blank line. In other words, for the last expression you write in the clause, <return> must be pressed twice in a row.
Alternatively, you can make use of the builtin help() function. help(thing) to get help on some thing object, or help() to start an interactive help session. This mode is extremely powerful, read the instructions when first entering the session to learn how to use it.
Lastly you can run your code with the -i flag to execute your code normally, but be dropped into the REPL once execution is finished, giving you access to all your global variables/functions in the REPL.
To exit either a help session, or normal REPL prompt, you must send an EOF signal to the prompt. In *nix systems, this is done with ctrl + D, and in windows systems it is ctrl + Z. You can also exit the normal REPL prompt with the dedicated functions exit() or quit().
!sql-fstring
SQL & f-strings
Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.
Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.
For example, the sqlite3 package supports using ? as a placeholder:
query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)
Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.
See Also
• Extended Example with SQLite (search for "Instead, use the DB-API's parameter substitution")
• PEP-249 - A specification of how database libraries in Python should work
uh this is unexpected
I thought it was only asyncpg?
No it's every sql library.
oh
Every coding language
so what should i do?
Fine in this case
don't make a typo
on channel
Best to just do it the right way so you never need to think about it.
that isnt my error
AttributeError: 'CMySQLCursor' object has no attribute 'fetch'
maybe fetchone or fetchall
Hey,
I'm currently testing around a bit on slash autocompleting, and I run into this problem:
https://i.imgur.com/XZgakum.png
The code is (obviously) supposed to send the embed, and not the object. I don't really know what I did wrong, as I also can't await it before which I think would fix the problem. This is my current code:
This is the ruleclass, I'm following the docs where they mentioned to subclass it:
class ruleclass(str, Enum):
RuleOne = disnake.Embed(title="1) Follow the Discord ToS (https://discord.com/terms)", color=disnake.Colour.random())
This is the command:
@commands.slash_command(description="Send a specific rule into the channel.")
async def ruletest(
inter: disnake.ApplicationCommandInteraction,
rule: ruleclass
):
await inter.response.send_message(rule)
it's embed=rule
Use the embed kwarg
Bruh, sometimes I think I'm missing the half of my brain
that's unfortunate
I'm missing all 3 halves of my brain tbh
that's interesting
i tried both but both dont work
At least you had 3 to begin with...
What library are you using?
database or python wise?
py
same error? no such attribute?
pycord
yes
bru he didn't mean the discord library
oh
so why did you say py not database lol
python wise doesn't mean discord wise
I mean sure but like, isnt database the only option there for the db lib anyway lol
ill try and see if it works
no because I thought he would say MySQL
not this
even though I don't think the answer he got makes sense
in databases
And they all suck.
Does anyone know how to go back to other python versions as my bot only runs on 3.8.12?
!e
print("hello".hellobello())
@heady sluice :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | AttributeError: 'str' object has no attribute 'hellobello'
wdym only runs on 3.8.12?
attributeerror
Python Version
if it runs on 3.8.x it should run on any further versions released up till now
nope
what, what makes you say that?
You can't really look at it like that.
Do you use git?
As it runs on replit fine but on iDle 3.10.4 it does not and replit is 3.8.12
Nope
you need to pip install libraries before using them, did you do that?
yes
what errors do you face?
look in #help-cherries
You have SQLite?
I have asyncpg and it's working pretty damn well
I made a social media platfrom in JS
Meh

Also used JS to start my first public website
svelte is cool for that
It wasn't too bad in JS
In:
@commands.Cog.listener()
async def on_command_error(self, ctx: commands.Context, error: disnake.ext.commands.CommandError):
try:
await ctx.send(error)
print(Fore.RED + '[Error]' + Fore.WHITE + f"{error}")
except BaseException:
print('Error has occurred in error handler! All hope is lost! You may panic!') # hope this code never executes
How can I push a help dialog for the command with an issue so they can see the syntax
it's what was reccomended to me earlier. ¯\_(ツ)_/¯
Like
$cmd {argnamehere}
On an error.
So they run $cmd but forget the arg so it sends the syntax to remind them
hm, all you need is the Command object which I'm trying to see how you get with the Error
!d discord.ext.commands.Context.command
The command that is being invoked currently.
!d discord.ext.commands.Command
class discord.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.
These are not created manually, instead they are created via the
decorator or functional interface.
these are the attributes of ctx.command
you could send ctx.command.usage
it seems useful
So
await ctx.send(ctx.command.usage)```
@commands.Cog.listener()
async def on_message(self, message):
if not message.channel.category:
return
if message.channel.category.name != self.categoryName:
return
if self.botPrevention and message.author.bot:
return
for channel in self.channels_to_send(message):
if len(await channel.webhooks()) < 1:
await channel.create_webhook(name="test")
webhook = (await channel.webhooks())[0]
await webhook.send(message.content, username=message.author.name, avatar_url=message.author.avatar.url)```
hey guys, i have this code that essentially sends the same message a user sent in multiple channels using a webhook. it all works but when people spam there is some pretty major delay between someone sending the message and the webhook sending it in the other channels. is the bottleneck in discord's servers due to too many requests? is it on my end? if i host it on a beefier server will it be faster?
Welp what I said didn't work
Could you format that I can see how it looks in code. Cause my brain just hit a 404 brain not found
Too many api requests likely.they will be delayed
so is there anything i can do?
Nope. What's it for anyways lol
oh nothing haha, im just experimenting with webhooks for the first time👍🏻
so what do really huge bots do (like MEE6) and so on
surely they are doing more than 50 API requests / second (which is the limit i think)
Huge bots have higher limits
ah ok
is there a formal proccess to increasing your bots limit?
like once you reach x servers you get x requests/s
Other than just growing larger, no
I don't know myself but it must be automated
The only formal thing you gotta do with your bot is to verify it on 100 guilds
await ctx.send(ctx.command.name + ctx.command.clean_params)
I just checked dev portal and it turns out limit of 50 requests per second is global tho
Weird I have other information
I have a function in a cog file, that i need to call with data from another file thats not apart of the bot.
Problem is, it has self. And using @staticmethod doesnt work as in the function in the bot file i need to use client.
How can I call the function without self?
What part of cog object do you use in your function
Could you show the whole function
async def crisp_chat_received(self, channel_name, raw_data):
WH_guild = self.client.get_guild(0000000000000000000)
try:
send_to = discord.utils.get(WH_guild.channels, name=channel_name)
await send_to.send(f"From: {raw_data['data']['user']['nickname']}\n {raw_data['data']['content']}")
except Exception as e:
print(e)
print("Channel not there, will make!!!!")
print(channel_name)
oops, sorry
The file thats calling the function doesnt have client, its not apart of the bot core (the file with the image code)
# file1
async def crisp_chat_received(client, channel_name, raw_data):
...
# cog
await crisp_chat_revived(self.client, ..., ...)```
Its the other way around
# external file
asyncio.run(crispAPI.crisp_chat_received(channel_name, data))
# cog
async def crisp_chat_received(self, channel_name, raw_data):
WH_guild = self.client.get_guild(0000000000000000000)
try:
send_to = discord.utils.get(WH_guild.channels, name=channel_name)
await send_to.send(f"From: {raw_data['data']['user']['nickname']}\n {raw_data['data']['content']}")
except Exception as e:
print(e)
print("Channel not there, will make!!!!")
print(channel_name)
Why the heck is there asyncio.run
because its an async function
I don't get the purpose of it
It’s the recommended way
Why wouldn't you just await it
i dont think that would help
To help with that I need to know the project structure
If you have no access to the Bot abstraction, you’ll have to use the REST api manually. Seems like you have the proper IDs anyways to make that work
Pretty sure you are able to make the whole thing awaitable without usages of asyncio.run and other utilities to run coro from non coro context
okay
bot {
cog.py (has crisp_chat_received function)
}
@webserver-event (needs to fire crisp_chat_function)
}
Ah API integration?
yes
Personally I just put the whole API into a cog
Wait, no im not sure i meant that
its processing a webhook
^ But you could possibly refactor your code to work
If it’s a webhook you won’t need the bot either
You can bring the function out of the cog to a separated module
the webhook has the json data the bot needs to do my thing
But I am guessing you are having issues specifically with API integration
the issue im having is getting the data from the webserver passed to the function in the cog
So the solution is
-
Bring the function out to a separated module
-
Put your API into another cog so you can access the bot from it
Outdated tutorial don't watch it
I cant really bring the function out (i dont think) because i need to interact with discord, like creating channels/sending messages as the bot with the json response from the webserver
Everything > 1 year old is outdated and the other part is mostly incorrect
Proper way to get a channel*
If you have the bot token and the channel IDs just use the REST api without abstraction 😔
!d discord.Guild.get_channel (bot has this method as well)
get_channel(channel_id, /)```
Returns a channel with the given ID.
Note
This does *not* search for threads...
Yes
ill keep this as an idea, if the docs are anywhere for raw requests?
You can
Just parse client arg to there
You can always bring a piece of code to a function
client arg from where tho? I dont have it in the external file that im passing from
There are no exceptions
From cog
To function
That's called refactoring
that doesnt seem to solve the issue if i need client from the cog to pass to another external file
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
its not an API, its a webserver
Same thing
The create message endpoint is just POST channels/channel_id/messages then you pass the payload
Authorisation headers r needed as well but you I’m assuming have the token
The only other thing you need is an aiohttp session
currently / (what i would like):
external file (has data needed in cog) -> cog (has client to interact with discord, uses data from webserver in a function in the cog)
Do you start the bot and the web server in the same file?
