#discord-bots
1 messages · Page 209 of 1
Side note: best off not naming a Member object "user", a member is not the same as a user
I got else
I second this
Third
alr, then you know what's wrong, right? your if statement is not True, most likely the
if payload.emoji.name == ":Giveaways:"
what about try except will that work?
It will not
so how do i fix it?
print the payload.emoji.name and see what that puts out
(above the if statement ofc 🧠 )
try:# Don't use
@client.comman# Don't used()# Don't use
async def check(ctx, user: discord.Member):
if user.id in requested.find_one():# Don't use
await ctx.send("User is in the database")# Don't use
else: # Don't use
await ctx.send("User is not in the database")# Don't use
except:
pass
Sending the file alone is ok, but I don't know how to send the image inside the discord.embed, embed.set_image only accepts https, and the attachment url isn't working.
I'd definitely censor that

show current code again pls
try:
@client.command()
async def check(ctx, user: discord.Member):
if user.id in requested.find_one():
await ctx.send("User is in the database")
except:
async def check(ctx, user: discord.Member):
await ctx.send("User is not in the database")
???
I over wrote the == as it is just Giveaways no :Giveaways:
try and see 🤷♂️
@cloud dawn that's your issue now
nah it not works
that worked
good, have fun!
async with self.bot.http_session.get(
document["sprites"]["front_default"]
) as res:
sprite = await res.read()
sprite = Image.open(BytesIO(sprite)).convert("RGBA")
sprite = sprite.resize((2100, 2100))
# Paste the sprite onto the background
x_offset = (bg.width - sprite.width) // 2
y_offset = (bg.height - sprite.height) // 2
bg.paste(sprite, (x_offset, y_offset), mask=sprite.split()[3])
result_buffer = BytesIO()
bg.save(result_buffer, format="JPEG")
result_buffer.seek(0)
file = discord.File(
result_buffer, filename=f"a_wild_{document['name']}_appeared!.jpeg"
)
embed = discord.Embed(
title=f"A wild {document['name']} has appeared!", color=0x05E1E1
)
embed.set_image(url=f"attachment://{file.filename}")
await ctx.send(embed=embed, file=file)
c':
your image is never saved locally, right?
Nope
Getting it from the api c':
you don't need the set_image method
look closely
!d discord.discord.ext.commands.on_command_error It's an error relating with how Discord.py handles commands. Hence we advice you to make a global error handler.
discord.ext.commands.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.
A default one is provided ([`Bot.on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.on_command_error "discord.ext.commands.Bot.on_command_error")).
Oh, I'll check
the attachment:// BS is only needed for local files
you just need to pass your file object
discord py is soooooo weird
can someone help me make a bot that simply says hi when I type hi??? WHy is it so hard?
||that's what she mostly says||
good code examples are key for beginners
@slate swan Look above for some examples. ```py
@Cog.listener('on_command_error')
async def err_handler(self, ctx: Context, error: Any) -> None:
# if command has local error handler, return
if hasattr(ctx.command, 'on_error'):
return
# Get original error instead of a global Invoke error
error = getattr(error, 'original', error)
# Standard debug to log to catch unknown errors
logger.debug(type(error))
if isinstance(error, CommandNotFound):
logger.debug(f"{ctx.author} this command does not exist")
elif isinstance(error, HTTPException):
error.text = error.text.replace("\n", " ")
logger.warn(f"HTTPException: {error.text}")
elif isinstance(error, NotFound):
error.text = error.text.replace("\n", " ")
logger.warn(f"NotFound: {error.text}")
elif isinstance(error, CheckFailure):
logger.debug(f"Check failed for {ctx.author} most likely has no permission to execute this")
else:
logger.error(error)
i have found 0 code examples that work
that's because you're most likely copy pasting
GIT CLONE

Petition for everyone to work with docker so I don't have to set anything up.
is there any good discord py tutorial?
the docs
lol
don't use YT
Il try
What are you trying to do? @languid siren
how do i define a global value?
i tried using reaction_roles = someid
and it says that is not defined
Uhhh
How are you using it? I don't really want to recommend using global since there are way better methods.
I want to use that value in one cog to define that same id 4 different times
if not more
i want to create a bot that gets data from an api and does something similar like this:
edits a specific message every 60 seconds (or another speicific timeframe ill decide)
reactions 😭
you're looking for "tasks" in the docs
the thing is im a total noob and i see things like async/await and decorators for the first time (i used a decorator once was with flask)
thanks a lot. I will check it all out.
yeah, having basic python knowledge is key here
async/await seems cool xD
it is
What should i do?
No idea what you have now..?
reaction_roles == someid
But from where?
a list can't be equal to a single value...
I mean... no sorry I won't sir..

as mentioned earlier
#discord-bots message
for everyone trying to help you
I still don't know how or where reaction_roles is created and compared to an id.
i want reaction_roles to have the id value
Yeah okay but in what context do you want reaction_roles?
How bad is the idea of enabling all intents for a bot? And why?
It isn't necessarily bad it's just that if you have enabled intents for something you aren't using. That's wasted resources, besides, it's good to know what you are using. On top of that some do also need extended privileges beyond 100 servers, what not always will be granted.
I'd definitely opt for "less is more"
-> try to keep resources as minimal as possible
Might as well enable all on development and restrict down based on final feature list
You'd be surprised how much a bot can do without any intents.
I'd keep it as minimal as possible too in development, so you don't have to question "why it works in development but not in prod"
I was wanting the context of it to store the id to be provided when changed at the top
documentation is really helpful indeed. Im so hyped nwo
If you are in a cog just use the self at the top.
on github are examples too which aren't documented on the website
how?
self.reaction_roles?
🎊 Anotherone converted to the ways of the docs.
Yep.
mhm, then your reaction_roles will be an attribute of your cog class
=> you'll be able to access that attribute in different commands / events in the same cog
Yea I'm gonna need all three of those intents
Considering the intensive moderation plugin I'm adding....yea, I'm gonna need them
Well ever since the automod feature they're most likely not going to approve message content for moderation.
Safeguards against deletes and backlogging message on-demand I guess ¯_(ツ)_/¯
I'm not using Carl/Dyno/what-have-you for a reason
Mainly, I hate their dreadful UI/UX
Can't get it to work, it still sends the image outside the discord.embed. I guess I'll just save it on disk :'(
show code
this
Right. Forgot about automod's dreadful POSIX regex engine. I prefer PCRE
More like I wrote too much PCRE regex and I can't get rid of my lookarounds
async with self.bot.http_session.get(
document["sprites"]["front_default"]
) as res:
sprite = await res.read()
sprite = Image.open(BytesIO(sprite)).convert("RGBA")
sprite = sprite.resize((2100, 2100))
# Paste the sprite onto the background
x_offset = (bg.width - sprite.width) // 2
y_offset = (bg.height - sprite.height) // 2
bg.paste(sprite, (x_offset, y_offset), mask=sprite.split()[3])
result_buffer = BytesIO()
bg.save(result_buffer, format="JPEG")
result_buffer.seek(0)
file = discord.File(
result_buffer, filename=f"a_wild_{document['name']}_appeared!.jpeg"
)
embed = discord.Embed(
title=f"A wild {document['name']} has appeared!", color=0x05E1E1
)
# embed.set_image(url=f"attachment://{file.filename}")
await ctx.send(embed=embed, file=file)
Found this question but it haven't been answered yet :') https://stackoverflow.com/questions/74164047/send-a-pillow-image-in-a-discords-embed
To make sure the image is added to the embed before the message is sent, you can try creating the discord.Embed object first, setting the image URL to None, and then adding the image as a file attachment to the message using the add_field() method. Here's an example: ```embed = discord.Embed(
title=f"A wild {document['name']} has appeared!",
color=0x05E1E1
)
embed.set_image(url=None)
file = discord.File(result_buffer, filename=f"a_wild_{document['name']}_appeared!.jpeg")
embed.set_footer(text=f"Image credit: {image_credit}")
await ctx.send(
embed=embed.add_field(
name="Image",
value=f"Here's a picture of {document['name']}!",
inline=False
).set_image(url=f"attachment://{file.filename}"),
file=file
)
I hope this helps! Let me know if you have any further questions.
why'd you comment that set_image line, it's needed
and yeah the method works for sure
check mentions bro
i just came online wait
how do i fix the "ServerSelectionTimeoutError" in pymongo ?
make sure ur ip is allowed
also ur internet has proper ssl certification and stuff
Umm hey suppose i want to install discord.py on host server what should I write in requirements.txt
Just discord.py or...
^^
how do i remove a reaction from a different message?
!d discord.Message.remove_reaction
await remove_reaction(emoji, member)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Remove a reaction by the member from the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji").
If the reaction is not your own (i.e. `member` parameter is not you) then [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") is needed.
The `member` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") instead of `InvalidArgument`.
what about removing all reactions
clear_reactions()
I changed the filename and it worked... The problem was the "!" in the filename... ,_,
tysm ,_,
how do i fetch a message to clear the reactions on
!d discord.Channel.fetch_message
No documentation found for the requested symbol.
!d discord.TextChannel.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") from the destination.
message = await fetch_message(id)
await message.remove_reaction(payload.emoji.name, member)```
like that?
the format is correct, but the rest code is wrong tho
explain
unless you tell what you're trying to do there isn't much to explain
i'm removing a reaction that shouldn't be on the reaction roles
oh
then just disable the permission from discord to add reactions instead of making a long mess
lol it's not that long
and i will but just in case someone with admin perms adds one
ok
you need to specify the channel here first
why do i need to fetch the id
of the channel
you're fetching a msg using its id and channel should be specified
because that's how it works
ok how do i fetch the channel
!d discord.ext.commands.Bot.get_channel Use this to return a channel/thread by ID
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
so how do i format this with fetch message?
if you get the channel inside a variable called x, then it will be:
message = await x.fetch_message(id)```
id being the message id
ok thanks
!d discord.on_member_update
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change...
You can compare the timeout of before and after
idk why I didn't check the docs before asking mb
I will check it
It's ok :)
how would you copy permissions_for a channel to a new temp channel? like each possible role that has access to that channel carries over to the temp channel?
I recommend using interactions.py if youre trying to do slash commands
not responding to anyone, just yknow
Use discord.Channel.clone(), the change the name, description or anything you want.
!d discord.TextChannel.clone
await clone(*, name=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Clones this channel. This creates a channel with the same properties as this channel.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to do this.
New in version 1.1.
This also works with discord.VoiceChannel, discord.StageChannel, etc.
this won't let me make the channel in a specific category though right? i'd have to use the await move to do that after created right?
There's edit() and it allows you to edit most of channel's properties including parent category within a single API call, not a problem
!d discord.TextChannel.edit
await edit(*, reason=None, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the channel.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to do this.
Changed in version 1.3: The `overwrites` keyword-only parameter was added.
Changed in version 1.4: The `type` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead...
The solution with mininum API calls would be just to create a new channel with parsing overwrites from the base instead of cloning it
Any particular reason?
Its pretty easy to work with, other way, I just like how it works honestly
im sorry if thats stupid lol im learning buttons but i dont understand this error
Capital V
discord.ui.View
!d discord.Intents
class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.
Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.
To construct an object you can pass keyword arguments denoting the flags to enable or disable.
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
New in version 1.5.
intents = discord.Intents.default()
intents.message_content = True # required for prefix commands
client = discord.Client(intents=intents)
# OR
bot = commands.Bot(..., intents=intents)
i was also thinking do i really need to add that for the roles buttons work?
You only need this if you want your buttons to work after restarts
oh alr

idek
Hi! When a user types in the bot’s dm, this text appear. From there, they can choose if they want to create a ticket or cancel the interaction. Although, we found a glitch that if you send 2 messages, the text will sent twice and then, you will be able to create 2 tickets at once. Can someone help me to code so that the embed stops resending everytime they type in? My script is: https://paste.pythondiscord.com/yidukekala
did i do anything wrong?
yes, your view is the output of the roles function
you cannot call your view and your command the same thing
name it RolesView or something like that
I have a gamepass on roblox: https://www.roblox.com/game-pass/115752765/Downpayment
I want my bot the say "gamepass purchased" when someone buys it. how can i do this?
Roblox is a global platform that brings people together through play.
please @silver quest me otherwise i wont see
is it possible to use server specific emojis in buttons and selections?
ty!
???
Hi! When a user types in the bot’s dm, this text appear. From there, they can choose if they want to create a ticket or cancel the interaction. Although, we found a glitch that if you send 2 messages, the text will sent twice and then, you will be able to create 2 tickets at once. Can someone help me to code so that the embed stops resending everytime they type in? My script is: https://paste.pythondiscord.com/yidukekala
hi guys if someone can help me out with this problem i would be grateful
https://discord.com/channels/267624335836053506/1082439735961731143
any1 can help w that i have the button appear but it says the interaction has failed
@silver quest
it looks like you're using nextcord, which has button as an argment first and then interaction
so swap those two around
ty:)
how would I include a variable in a .path
Hello What do I have to do to user async in thread
Hey, I need help
Ignoring exception in view <Regenerate timeout=180.0 children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Regenerate' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\ui\view.py", line 370, in _scheduled_task
await item.callback(interaction)
File "C:\Users\berka\Desktop\Eagle Bird GPT\main.py", line 181, in regenerate
await self.update_image(interaction)
File "C:\Users\berka\Desktop\Eagle Bird GPT\main.py", line 177, in update_image
await msg.edit(content="Content generated", file=nextcord.File(image, "generatedImage.png"), view=self)
File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\interactions.py", line 1180, in edit
message = await self._state._interaction.edit_original_message)
code:
class Regenerate(nextcord.ui.View):
def __init__(self, prompt):
super().__init__()
self.prompt = prompt
async def update_image(self, interaction: nextcord.Interaction):
await interaction.response.defer()
ETA = int(time.time() + 60)
try:
msg = await interaction.edit_original_message(content=f"This could take some time, go take a rest and let me do my thing!!! ETA: <t:{ETA}:R>")
except nextcord.NotFound:
# Interaction has expired or webhook has been deleted, create a new interaction object
interaction = await self.bot.fetch_interaction(interaction.id, interaction.token)
msg = await interaction.edit_original_message(content=f"This could take some time, go take a rest and let me do my thing!!! ETA: <t:{ETA}:R>")
async with aiohttp.request("POST", "https://backend.craiyon.com/generate", json={"prompt": self.prompt}) as resp:
r = await resp.json()
images = r['images']
image = BytesIO(base64.decodebytes(images[0].encode("utf-8")))
await msg.edit(content="Content generated", file=nextcord.File(image, "generatedImage.png"), view=self)
@nextcord.ui.button(label="Regenerate", style=nextcord.ButtonStyle.success)
async def regenerate(self, button: nextcord.ui.button, interaction: nextcord.Interaction):
await self.update_image(interaction)
@bot.slash_command(name="describe", description="describe something and I will turn it into a picture!")
async def describe(interaction: nextcord.Interaction, prompt: str):
view = Regenerate(prompt)
ETA = int(time.time() + 60)
msg = await interaction.response.send_message(f"This could take some time, go take a rest and let me do my thing!!! ETA: <t:{ETA}:R>")
async with aiohttp.request("POST", "https://backend.craiyon.com/generate", json={"prompt": prompt}) as resp:
r = await resp.json()
images = r['images']
image = BytesIO(base64.decodebytes(images[0].encode("utf-8")))
await msg.edit(content="Content generated", file=nextcord.File(image, "generatedImage.png"), view=view)```
Everytime I press the button the regenerate a new image it keeps on doing that!
that's not the full error
it's cut off right before the actual error appears
that's what it gave me
check again
Okay!
@smoky sinew
Ignoring exception in on_connect
Traceback (most recent call last):
File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\client.py", line 490, in _run_event
await coro(*args, **kwargs)
File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\client.py", line 2459, in on_connect
await self.sync_application_commands(
File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\client.py", line 2273, in sync_application_commands
await self._connection.sync_application_commands(
File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\state.py", line 807, in sync_application_commands
await self.register_new_application_commands(data=data, guild_id=guild_id)
File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\state.py", line 1014, in register_new_application_commands
await self.register_application_command(app_cmd, guild_id)
File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\state.py", line 1049, in register_application_command
raise e
File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\state.py", line 1045, in register_application_command
raw_response = await self.http.upsert_global_command(self.application_id, payload)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^```
File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\http.py", line 400, in request
raise HTTPException(response, data)
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In name: Command name is invalid
Eagle Bird GPT (Dev)#2353 is now online!
Ignoring exception in view <Regenerate timeout=180.0 children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Regenerate' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\ui\view.py", line 370, in _scheduled_task
await item.callback(interaction)
File "C:\Users\berka\Desktop\Eagle Bird GPT\main.py", line 181, in regenerate
await self.update_image(interaction)
File "C:\Users\berka\Desktop\Eagle Bird GPT\main.py", line 177, in update_image
await msg.edit(content="Content generated", file=nextcord.File(image, "generatedImage.png"), view=self)
File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\interactions.py", line 1180, in edit
message = await self._state._interaction.edit_original_message(
^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'ConnectionState' object has no attribute '_interaction'```
interesting
How could we fix this?
i'm not sure i will look into it
everything sends in x2. my script = https://paste.pythondiscord.com/
My bot is running just once and I only have one python open
i told you yesterday did you see?
oh nvm that's a different screenshot
why are you back to the other code btw
Ah helper from here told me it was better the old way
Idk
why so
Idk ask @hushed galleon
do you have an idea why everything is duplicating?
are you running your bot twice?
**
how do I even see if my bot is running twice?
that can get tough since it could be hosted in the background on your computer or on another computer entirely
so should I restart my pc?
alright
wouldn't connecting every time still be slower because it has to wait for the other transactions to finish before committing
might want to discuss in #databases instead but the point of SQLite waiting is to maintain ACID, and with a single connection you'll immediately violate those invariants unless you put your own lock on it, plus i described the write-ahead log where readers don't need to wait (while having an isolated transaction)
(and with short-lived connections the pause will only be momentary)
(discussing here
#databases message)
why would it break acid? wouldn't one of the transactions just wait for the other?
Hi! When a user types in the bot’s dm, this text appear. From there, they can choose if they want to create a ticket or cancel the interaction. Although, we found a glitch that if you send 2 messages, the text will sent twice and then, you will be able to create 2 tickets at once. Can someone help me to code so that the embed stops resending everytime they type in? My script is: https://paste.pythondiscord.com/yidukekala
^ previously suggested solution
check if the message already exists with a dictionary
if you're struggling to implement it, perhaps your friend could help out?
Hes not available for the next weeks
And hes not really experienced with discord py
He did his best but
when you send the message you can append it to a dictionary with perhaps the userid and either a toggle, or the message id, and when its done remove it from the dict
Should I go check on youtube how to do that?
or you might be able to get away with a list of the user id
if you dont know about dictionaries im sure theres resources, idk any off the top of my head
you might be able to get away with just appending a list
buffer = []
buffer.append(ctx.user.id) # stopping them from making another
do the stuff
buffer.remove(ctx.user.id) # Allowing them to request another
youd just have to run checks on what you need to do
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
ima have a look
Should I try to put that in my script then?
Alright!
this gives a quick rundown, just imagine using the userid
youll essentially check if the userid is in the list, if it is, a simple "you already have one"
if its not youll be adding them to the list and opening a message/ticket
help making a mute command?
can anybody tell me how to make giveaway bot?
Better invite one, why reinvent the wheel
Making a giveaway bot is not a simple task, but here are general steps you need to follow in order to create a giveaway bot:
- Create development basic tools, including bot subclass, database methods and other required things (if you are disnake user you can use my template https://github.com/Exenifix/disnake-bot-template-postgres)
- Add tables into database that will store users who participated in a giveaway and additional data
- Create giveaway system - how users would enter giveaway and how bot would give reward to them
which file is for giveaway bot in your repo?
There's none I hate them
Repo is a template for speeding up development, empty bot so basically
oops
plz tell me how to create giveaway system or provide me material to study
If I hire bot dev to make it , then how much do I pay for that?
quick question tho cuz i cant find anything about that lol for reaction roles i want to make some with select menu is that the same thing of the button so i can js replace that by the good thing or its a whole diff thing?( also if you have the doc would b cool cuz i cant find it
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, 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
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
Best way to learn something is to learn it by yourself
The point of programming is not to find a solution but think of one
Finding applies too but to subtasks
Not a good question to ask in this server
!rule paid
If your goal is learning ofc 💀
u would have to start with basic python learn till oop learn asyncio and about apis and since its a giveaway bot u need to learn about databases
can u introduce some material to study, thx
for up till oop u can look at youtube corey schafer on yt
asyncio and apis u would have to google it up
heyy
ok so the database works in the morning/afternoon
then i get the server timeout error
What database
And how do you connect to it
it goes rouge in the night 
When the database is sus
If you prefer interactive lessons to youtube videos, you can try a learning platform like Stepik
its uh mongodb
Dunno about that much but will try to figure out if nobody else can help
mongodb don't do that 
How do you connect to it
I mean in code
one reason could be ur ip changed and in network acess u are limited
well
Is it on localhost or remote
im using replit, with mongodb atlas
^^
if you can't manage to buy a vps/server, check this out https://signup.oraclecloud.com
Oracle Cloud Free Tier Signup
though iirc you'll need a card
because response isn't the json data
it's a Response object
you can use it's .json() method
although for a discord bot you should be using an async http client like aiohttp instead of requests
zeffo expert in this field 
?
so i did a role slash command that takes the role id and gets it into an embed -
@nextcord.slash_command(name="helpme-role", description="Set the helpme role")
async def helpmerole(self,interaction:nextcord.Interaction,
role_: nextcord.Role = nextcord.SlashOption(name='role', description='Please select a role', required=True)):
if interaction.user.guild_permissions.administrator:
async with aiosqlite.connect("main.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT role_id FROM role WHERE guild = ?', (interaction.guild.id,))
role = await cursor.fetchone()
if role:
await cursor.execute('UPDATE role SET role_id = ? WHERE guild = ?', (role_.id, interaction.guild.id,))
else:
await cursor.execute('INSERT INTO role (role_id, guild) VALUES (?, ?)', (role_.id, interaction.guild.id,))
await interaction.response.send_message(f"Successfuly set the helpme staff role to - {role_.mention}")
await self.bot.db.commit()
else:
await interaction.response.send_message("You need the `administrator` permission to use this slash command!")
when im changing the role it keeps the same role'
because you arent removing it?
send screenshot of SELECT * FROM role;
did that
.
and send code as text not screenshot
i dont have the SELECT * FROM role
wait where
in the command that takes the role or the command that tags it
how do you check the contents of a table?
i did select role_id , language
anyone can maybe help me with my discord bot`? hes supposed to play Music. But he just enters and doesnt play music. In the Terminal i get a message saying " ERROR: '!play' is not a valid URL. Set --default-search "ytsearch" (or run youtube-dl "ytsearch:!play" ) to search YouTube "
I cannot find any help on google so maybe here
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
Yes that's why the feature was disabled on mee6 and several music bots were shut down
i mean only law realistically when money is involved, but it breaks their tos
Money is involved cause playing music from youtube does that without ads
def __init__(self):
options = [
discord.SelectOption(label="Red", description="Red is a colour", emoji=":clashgoblin35:", value="red"),
discord.SelectOption(label="Blue", description="Blue is a colour", emoji=":clashduh:", value="blue"),
discord.SelectOption(label="Green", description="Green is a colour", emoji=":clashhuh5:", value="green"),
discord.SelectOption(label="Yellow", description="Yellow is a colour", emoji=":clashkiss45:", value="yellow"),
discord.SelectOption(label="Purple", description="Purple is a colour", emoji=":clashhappy:", value="purple"),
]
super().__init__(placeholder="Select an option", options=options)
async def callback(self, interaction: discord.Interaction):
await interaction.response.send_message(f"You selected {self.values[0]}")
@discord.ui.button(label="Close", style=discord.ButtonStyle.red, row=1)
async def close(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message("closed the dropdown", ephemeral=True)
self.stop()
if __name__=="__main__":
bot = MyBot(command_prefix="-", intents=discord.Intents.all())
# MESSAGE COMMANDS
@bot.command()
async def dropdown(ctx):
view = discord.ui.view(timeout=60)
view.add_item(Dropdown())
await ctx.send("Select a colour", view=view)```
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'module' object is not callable
But um actually we don't have youtube ads in Russia 🤓👍
Do you still have YouTube at this point
Yes
!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.
Except the images like youtubers PFPs and posts images don't load at all
well nothing a Yt add blocker wont fix lol
But videos are okay and there are no ads

Technically it's against ToS too
Legal way to avoid ads in youtube is get a russian vpn
But maybe yall can help me with this. It says ERROR "!play" is not a valid URL. SO the Bot joins. but thats about it.
its got nothin to do with yt
It's clearly an error from ytdl
Nope sorry, it is still a project that violates ToS
From your previous message
Once we know we know
tos-and-pp is a very good repository
English….
oh shit
They mean full error
yea
wait
File "C:\Users\BADAL NAG\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "c:\Users\BADAL NAG\Desktop\discord\discrdbot\cogs\error.py", line 38, in on_command_error
raise error
File "C:\Users\BADAL NAG\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\BADAL NAG\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\BADAL NAG\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'module' object is not callable←[0m```
How can I add emoji buttons to embed
!d discord.ui.Button
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
You can add emoji attribute
Ohh ok
is it possible that YT dl is out of service ?
i foudnthe error in my code and then it told me that i needed tthe newest verion, So i upgraded it. it still doesnt work. Im not askin for advice about my discord bot im asking if its possible that youtube.dl no longer works?
why do i get error with this code? @bot.command() async def commands(message): if message.content.startswith('!commands'): embed = discord.Embed(colour=0x9B59B6, title="List of Commands", type='rich', url=None, description="Hello", timestamp=None) await message.channel.send(embed=embed)
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
try using " !command"
wait nevermind
check the docs
i think i figured it out wait
you are mixing two concepts
Yeah i figured it out now
waht was it
If I want to add emoji will it be like emoji = <:emoji:id>??
Yes? And why don't just test it
It says syntax error
Send the code
can this make me join different servers my its self?
What
Yes, "Join server for you"
This application let you join other server without you even knowing
can you give me guideline on how smth like this is made?
but how
Oauth2
dm? if u dont mind?
Where is the < and >
??
What
Now it says invalid emoji
.
yeah cuz you have to do emoji="emojiname"
Show the code and the error
Not for custom emojis
nvm
oh yeah i didnt see dat was cstom
I did with I'd too
Then what happened
Same
Yeah I know
it suppose to work if you did that tho
In " " right?
whats this suppose to dO?
Yes?
redirect url
Still not working
Send the code and the error
you could do windows shift S for screenshot lol
Oh right
Is the bot in the server that the emoji is from?
It's a default emoji but yes he is
And why is self not the first argument of that method
📩
What
How did you get its ID then
It has no ID
And the
<:emoji_name:id>
is only for custom emojis
Ohh I think I pasted message id
No I'd still not working
And?
I don't have any code or error to tell what's wrong
And just put the emoji ❌ in if it's a default one
what should i do about this?
i could show you cuz i have the exact same code but its too early n im lazy😂
Got it
Now it's working
great
question about views and buttons.
if i want async def on_button_click:to take the label of the button, change a channel id's channel name, how would that work? i'm like trying to understand discord.ui.buttons and views, but i don't get how they work still x.x
What library is this
discord.ui? Button, View?
That doesn't answer the question
What library is it from? Like discord.py, disnake, ...
oh discord.py
There's no such events as on_button_click
so instead of making a function, i should use discord.Interaction?
I don't know what that means
ok. i'll just explain. so i made an embed generator for 10 names at a time. the 10 names will generate into buttons, i'm trying to convert this to update the name of two channels using dictionary comprehension.
https://paste.pythondiscord.com/cokagiqago
i just don't know where i'm going wrong with the discord.Interaction
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.

thank you.
How do I prevent the timeout from executing when the button is clicked before it?
https://paste.pythondiscord.com/wacocixeti
you'd define the timeout in the init/ super init then when you call the view, timeout = None
class ChannelNameView(View):
def __init__(self, channel_data_dict, channel_id, names, best_name, timeout=180.0):
super().__init__(timeout=timeout)
view = ChannelNameView(channel_data_dict, channel_id, names, best_name, timeout=None)
atleast.. that's how i did it.
i'm sure theres other ways, but this is what i did, 🥲
How can I fetch the channels in a guild
a for loop for the guilds, if statement for the guild in question, then it would be like guild.channels i think.
!d discord.Guild.channels
property channels```
A list of channels that belongs to this guild.
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
@green pivot
!code
!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.
!d discord.Guild.channels
property channels```
A list of channels that belongs to this guild.
from discord_ui import Components, Button, SelectOption, SelectMenu
why this always errors? module 'discord' has no attribute 'StoreChannel'
do pip list and show output
dont use third party libraries
discord-ui is unnecesary, remove it and upgrade discord.py if ui folder is not found.
How to get list of channels of guild in which interaction was performed
!d discord.Guild.channels
property channels```
A list of channels that belongs to this guild.
Being able to understand the docs is a very valuable skill
how do i get the name of both attacks?
as what datatype
My .py file to make my bot up doesnt work to open in python, pls check latest #1035199133436354600
quick question, does restarting your bot resets command cooldown of slash commands (app_commands)?
Yes
async def hi(self, interaction: discord.Interaction, button: discord.Button):
c = []
for channel in interaction.guild.text_channels:
c.append(channel.name)
print(c)
if f"{interaction.user}" in c:
await interaction.response.send_message(content = "channel exist", ephemeral = True)
else:
await interaction.guild.create_text_channel(f'{interaction.user}')
await interaction.response.send_message(content = "channel dosnt exist", ephemeral = True)```
then i need to use a db to restore them right?
i have a channel named interaction.user but still says channel doesnt exist
Write the data on disk
how
Mm you will need custom cooldown first of all most likely
i will use db then
Idk what's it named
I will search for that rq
!d discord.app_commands.checks.dynamic_cooldown
@discord.app_commands.checks.dynamic_cooldown(factory, *, key=...)```
A decorator that adds a dynamic cooldown to a command.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and return a value that is used as a key to the internal cooldown mapping.
If a `factory` function is given, it must be a function that accepts a single parameter of type [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Cooldown "discord.app_commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.
Both `key` and `factory` can optionally be coroutines.
I think its discordapp commands but not sure
oh it is
pip install -U discord-py-slash-command
u did that?
I thought discord_slash was deprecated
Why do you need ctx
Interaction gives all of it for you
Interaction is the same thing
Pretty much
json
oh
do you want them in a list?
have you used for loops/list comprehensions before?
yea kindoff
so you can use a for loop to go over the "attacks" list, and append the names to a list
for attack in attacks:
name = attack["name"]
you could also use a list comprehension; ```py
[atk["name"] for atk in attacks]
Quick question:
Do I need PyCharm to program Discord Bot? Or is Visual Studio Code okay?
you can use whatever you like better
Whichever you're more comfortable with
can u use ephermal messages in 1.7.3
Don't believe so
ok
how can I host my bot free ?
I get this when i try and run my Command but it should be all good. I have everything isntalled and i was just workin on smt else before but now i get this message C:\Users\frede\AppData\Local\Programs\Python\Python311\python.exe: can't open file '
any idea as to why
@sick birch so it's 2.0+ ?
Yeah
Only free hosting method is to self-host really.
sad
Only good free hosting
I'd recommend AWS if you're comfortable with a more complex provider but potentially more services and options
that's not free either actually, electricity bills 😔
Pretty much negligible
true
Heyy, what does this mean? Does that not exist anymore?
Or do I have to get the user object?
avatar_url got changed to avatar.url at some point I think
Np
How can I send message in channel created by button interaction within the same function
i think it's interaction.response.send_message.
i figured it out still thanks
Hey @fair shuttle!
It looks like you tried to attach file type(s) that we do not allow (). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
those are all in venv libs. u'll prolly wanna use try/except blocks to find the error, worst case u can import traceback
Aight then
yes i do
You need to uninstall it
You can only have one discord lib installed
Either nextcord or discord.py
Hey what libraries do you guys suggest for creating discord bots? Didn't the main developer of the main library abandon the project or something?
They did, but then they started again
discord.py, disnake, nextcord are all wrappers for interacting with the discord api
Also pycord
Oh alright thanks, which one would you suggest?
discord.py seems to be the most used, nextcord and disnake are fine though
Ok, thank you.
any1 know how to fix that in libs? im trying to understand the error
Hmmm. And what does your code look like?
Is Role supposed to be a cog?
nope
Why is it in a class?
sm1 told me it was suppose to be in a class lol
If it's not supposed to be part of a cog then it isn't supposed to be in a class
so i need to remove the class?
Yes, and the initializer
? or i need to add something else?
Can we see all code
yeah
Cause idk what’s happening there
Hey @fair shuttle!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
wth are you doing at lines 44-46
the guy who showed me tells me i had to put the self.value[0]
Nah that’s invalid
oh
For ur command decorator
this one?
No. The role stuff
Where is that
Why do u have a command inside of a select. And what do u instantiate the view in the command in the select in the view?
That’s a whole lot of wrong
How do I loop thru a section of a code ?
While or for loop.
Tho u can do a task loop if u wanna look smth with discord
Wdym
not even discord
you can put any code you want if you're using the tasks extension
ls
Hey how would I recode it where after the user pressed an button the code regenerates the same prompt?
code:
@bot.slash_command(name="ask", description="give you a response with the prompt")
async def ask(interaction: nextcord.Interaction, prompt: str):
await interaction.response.defer()
view = Regenerate2(prompt)
openai.api_key = ""
response = openai.Completion.create(
model="text-davinci-003",
prompt=prompt,
temperature=0,
max_tokens=4000,
top_p=1,
frequency_penalty=1,
presence_penalty=1,
stop=["Human:", "AI:"]
)
AI_Message = response['choices'][0]['text']
embed = nextcord.Embed(
title=f"Here is your answer for {prompt}!",
description=f"{AI_Message}",
timestamp=datetime.datetime.now(),
color=nextcord.Color.green()
)
embed.set_footer(text=f"By {interaction.user.name}#{interaction.user.discriminator}", icon_url=interaction.user.avatar.url)
await interaction.send(embed=embed, view=view)```
class Regenerate2(nextcord.ui.View):
def __init__(self, prompt):
super().__init__()
self.prompt = prompt
@nextcord.ui.button(label="Regenerate?", style=nextcord.ButtonStyle.success)
async def Regenerate2(self, button: nextcord.ui.button, interaction: nextcord.Interaction, prompt):
openai.api_key = ""
response = openai.Completion.create(
model="text-davinci-003",
prompt=prompt,
temperature=0,
max_tokens=4000,
top_p=1,
frequency_penalty=1,
presence_penalty=1,
stop=["Human:", "AI:"]
)
AI_Message = response['choices'][0]['text']
embed = nextcord.Embed(
title=f"Here is your answer for {prompt}!",
description=f"{AI_Message}",
timestamp=datetime.datetime.now(),
color=nextcord.Color.green()
)
embed.set_footer(text=f"By {interaction.user.name}#{interaction.user.discriminator}", icon_url=interaction.user.avatar.url)
await interaction.send(embed=embed)```
Who is well versed in pythone, please write to me in the bos.
need help
Hey how can I send a custom role in an embed?
Tried this but it just returns none
emoji = str(discord.PartialEmoji(name="128zie", id=1082804342421209171))
also tried this
print(client.get_emoji(1082813090929840211))
and this
embed.add_field(name="Interact with buttons to get your roles!", value=f":128zie: - Select your townhall level
just pip install it? and what does this even do
You can send it as a string like "<:emoji_name:emoji_id>"
that should display it right
You can get that by typing your emoji like usual in Discord, then putting a backslash before it
ok thank you ill try
their error is their extension is not loading
Do what
have a custom emoji in the label of the button
Yes
something like this
class StrategistRoleButton(discord.ui.Button):
def __init__(self):
super().__init__(style=discord.ButtonStyle.green, label=f"Strategist :128zie:")
async def callback(self, interaction: discord.Interaction):
role = discord.utils.get(interaction.guild.roles, id=strategistRoleId)
await interaction.user.add_roles(role)
await interaction.response.send_message(f"You gained the {role.name} role", ephemeral=True)
exept this does not work
Check this out
for some reason it changes the long <:name:id> thing to just the name but you get what i mean
let me check
Huh?
whats wrong?
why do u have a nested clas
and why do u have a command inside of your nested class
which is inside of a select
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(style=discord.ButtonStyle.red, label="Red")
async def red_color(self, interaction: discord.Interaction, button:discord.ui.Button):
red_role = discord.utils.get(interaction.guild.roles, name="Red")
await interaction.user.add_roles(red_role)
if __name__=="__main__":
bot = MyBot(command_prefix="-", intents=discord.Intents.all())
@bot.command(name="selfroles")
async def self_role(ctx):
await ctx.send("Give your self a role",view = SelfRoles())```
command not found
i want to know if its possible to remove a role when we click on it via select menu if any1 has the doc would b apreciate iont find it
import discord
from discord.ext import commands
from discord.ui import Select
class SelectView(discord.ui.View):
def init(self, *, timeout=None):
super().init(timeout=timeout)
self.add_item(Select())
class role(commands.Cog):
def init(self, bot):
self.bot = bot
@commands.command()
async def role(self, ctx):
await ctx.send("pick a role")
view = SelectView()
await ctx.send("View created.")
Regarding the "command 'role' not found" error, it could be because you have not loaded the role cog in your bot. You need to load the cog using bot.add_cog(role(bot)) before running the bot. Don’t know if your problem already solved. If not then try this maybe
!d discord.ui.RoleSelect
class discord.ui.RoleSelect(*, custom_id=..., placeholder=None, min_values=1, max_values=1, disabled=False, row=None)```
Represents a UI select menu with a list of predefined options with the current roles of the guild.
Please note that if you use this in a private message with a user, no roles will be displayed to the user.
New in version 2.1.
And just remove the role in the callback
yeah i fixed all that
how do i use a list of ids if those id's aren't in the list do something
!d in
6.10.2. Membership test operations
The operators in and not in test for membership. x in s evaluates to True if x is a member of s, and False otherwise. x not in s returns the negation of x in s. All built-in sequences and set types support this as well as dictionary, for which in tests whether the dictionary has a given key. For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y is equivalent to any(x is e or x == e for e in y).
For the string and bytes types, x in y is True if and only if x is a substring of y. An equivalent test is y.find(x) != -1. Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True.
!e
ids = list(range(100))
print(ids)
print(99 in ids)
print(100 in ids)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
002 | True
003 | False
ok thanks using MinimalHelpCommand and I can't figure out how to hide a command. How do I do so?
How do I make the bot only accept button interaction from the interaction user?
https://stackoverflow.com/questions/71795093/how-to-make-a-discord-button-work-only-for-command-user
thank u
https://paste.pythondiscord.com/disuzejusa
SyntaxError: positional argument follows keyword argument```
how can i fix this
error
, in <module>
client = discord.Client()
TypeError: __init__() missing 1 required keyword-only argument: 'intents'
source
import os
import googleapiclient.discovery
import discord
intents = discord.Intents.default()
intents.members = True # Enable the Members intent
client = discord.Client(intents=intents)
# Set up Discord client
client = discord.Client()
remove the unnecessary line:
# Set up Discord client
client = discord.Client()```
Read the error
You have problems in the lines speace
speace ?
ok np
i'm still stuck on this >.< ... so wait, how does one add the callback if i made the for loop in the view? do i need to define it in an async function then do the for loop?
Not really, you can set it by setting the attribute
so like
button.callback = self.on_button_click ?
Yup
awesome.
then how would I be able to pass the name of the button to the interaction?
would that be like button.label = name? then in the on_button_click I'd be able to define it like var = button.label?
Yes, but you can just set it in the button constructor
which the button constructor would be the for loop. right?
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
await interaction.guild.get_channel(voice_channel_id).edit(name=button.label)
AttributeError: 'property' object has no attribute 'get_channel'
but a method would be guild.get_channel to edit a channel name...
cause I see interaction has a guild param, so it should be able to edit it like so... no?
also, the docs recommend not using custom_id for conflicts? should i remove it if label is defined?
how is interaction defined?
interaction=discord.Interaction? i tried interaction:discord.Interaction but it said that
TypeError: ChannelNameView.on_button_click() missing 1 required positional argument: 'interaction'
interaction=discord.Interaction is incorrect, that would explain the error
can you share the code for on_button_click?
ill just send the whole view...
https://paste.pythondiscord.com/amahatitej
async def on_button_click(self, button=discord.ui.Button, interaction=discord.Interaction):
``` should be ```py
async def on_button_click(self, interaction: discord.Interaction, button: discord.ui.Button):
: is a typehint, = gives it a default value
you can remove the typehints entirely if you want
on_button_click exists on dpy?
it's just a defined callback function xD
I thought of event 💀
so then why was i getting TypeError: ChannelNameView.on_button_click() missing 1 required positional argument: 'interaction' when i had it
It's a custom function breh
Oh yeah, that's why you should define it in the init
so in the init i should define both?
button=discord.ui.Button
interaction=discord.Interaction
i'm lost now 💀 i thought defining was defining a variable or a def function
I have a plan
i'm all eyes and ears >.<
Uhhhhh
!d discord.ui.View.interaction_check
await interaction_check(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.
This is useful to override if, for example, you want to ensure that the interaction author is a given user.
The default implementation of this returns `True`.
Note
If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.on_error "discord.ui.View.on_error") is called.
I wouldn't use that, too much trouble for a simple things
I'd do something more simple like
class ViewSubclass(ui.View):
def __init__(self, ...):
...
for num in range(10):
btn = ui.Button(...)
async def acallback(interaction: discord.Interaction):
# use the btn var that was previously defined
btn.disabled = True
...
btn.callback = acallback
self.add_item(btn)
Though this defeats the whole point of subclassing the view and weird looking
ohhhh. so wait. u can make functions inside for loops?
I used to do that all the time
o.o 🤯
Or maybe you can use functools.partial to avoid doing this thing
Yeah, works too
Hello sory for noob question , how can i run an infinite loop when the bot starts
examples/background_task.py lines 13 to 25
async def setup_hook(self) -> None:
# start the task to run in the background
self.my_background_task.start()
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
@tasks.loop(seconds=60) # task runs every 60 seconds
async def my_background_task(self):
channel = self.get_channel(1234567) # channel ID goes here
self.counter += 1
await channel.send(self.counter)```
how tf you sent that so quickly
I already has a discord.py github tab open, so I just use that
thanks alot!
how can i implement this to non class?
from discord.ext import tasks
@tasks.loop(seconds=30)
async def atask():
print("meow")
oh thansk!
Then call the start meth somewhere in an async function
start the function?
!d discord.ext.tasks.Loop.start
start(*args, **kwargs)```
Starts the internal task in the event loop.
Not preferred, but you can
oh okay!
i tried this and got it to work! ty 🙂
now i just need to make adjustments so i don't get rate limited... again xD
@client.command()
async def loop(ctx):
while True:
#Stuffs
```When you execute the command 2 times there is 2 instances but is it possible to overwrite like this when you execute one more time it breaks the last command
hi guys, i need my bot sends a message when my activity is playing a current game, how i can do this?👉🏼 👈🏼
!d discord.ActivityType
class discord.ActivityType```
Specifies the type of [`Activity`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Activity "discord.Activity"). This is used to check how to interpret the activity itself.
Is there a way to make it so if a user leaves a guild (while having the muted role) it'll give it back? So that they stay muted (even if they're tempmuted that it'll remove it after that time even if they left the guild)
Or if the bot restarts that it'll remove the role after a tempmute
Yes. U store their roles in a database. Then u can check every member when they join and give them the roles back
and u have a time
if its a tempmute
how do u even cache
using redis or?
Because all I know is that you can cache using redis, but i've never used it and have no idea how it would work
u can cache locally with a dict or redis (i havent used redis so i dont know specifics)
there are many methods of caching
remote and local
!e
base_mmr = 1300
num_wins = 14
num_losses = 6
mmr_delta = (num_wins - num_losses) * 25
return base_mmr + mmr_delta```
@young dagger :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 5
002 | SyntaxError: 'return' outside function
Is that a database aswell? Or something for a database?
Because rn im using psql and asyncpg
i havent used redis so idk. i just know its used for caching commonly
Yeah that's what I know too
but that's ab it
guess ill ask my friend for more info and how it works cus he does use redis

!e
def calculate_mmr(base_mmr, num_wins, num_losses):
mmr_delta = (num_wins - num_losses) * 25
return base_mmr + mmr_delta
mmr = calculate_mmr(1300, 14, 6)
print(mmr)```
@young dagger :white_check_mark: Your 3.11 eval job has completed with return code 0.
1500
? do u have a question?
It's pretty much an in memory database
Very fast but limited in capability
Perfect for a caching layer
Good luck!
thanks mate
We are currently using a Discord bot that allows people to set up their League account using elo from whatismymmr.com to balance the teams for custom games. However, the website has not been updated for the past 5 months, and we are looking for a new system to determine the elo for each player. How would you determine the elo for each player?
What is elo
The Elo rating system is a method for calculating the relative skill levels of players in zero-sum games such as chess. It is named after its creator Arpad Elo, a Hungarian-American physics professor.
The Elo system was invented as an improved chess-rating system over the previously used Harkness system, but is also used as a rating system in as...
I dont think that is a bot specific question 😅
There's a size limit on how large of an integer you can input
You can't slash commands does not support them you should use str type
code?
Yep
to save an api request, simply do
user = discord.Object(id=user_id)
await guild.unban(user, ..., ...)
you’ll have to find another api then
Hi, when I start my bot on my laptop it works but when I start it on my raspberry pi to keep it online I have this message when I use a command: ```Traceback (most recent call last):
File "/home/#####/.local/lib/python3.9/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self.callback(interaction, **params) # type: ignore
File "/home/#####/edt/emploiDuTemps.py", line 542, in edt
await ctx.response.send_message(embed=m.embed, view=view, ephemeral=True)
File "/home/#####/.local/lib/python3.9/site-packages/discord/interactions.py", line 769, in send_message
await adapter.create_interaction_response(
File "/home/#####/.local/lib/python3.9/site-packages/discord/webhook/async.py", line 218, 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:
Traceback (most recent call last):
File "/home/#####/.local/lib/python3.9/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/#####/.local/lib/python3.9/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/#####/.local/lib/python3.9/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'edt' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
Did you ever see this error?
What is a good ping_timeout and interval for the discord gateway because currently it disconnects after every 55.xxx seconds
how long does it take you to respond to the command?
probably a few seconds
defer it
hi
sup
you have to respond in less than 3 seconds
anybody have any idea
if it takes longer you need to defer it
wdym?
I tried this but it didn't change anything
Discord tells you in the initial HELLO payload
Its not something for you to decide
Yeah i know but like
show code
It's somewhere around 40-45 seconds
45
You should use the interval in the hello payload
Instead of just picking some arbitrary one on your own
what about timeout, just dont set timeout?
Can I send it to you in dm?
why?
after setting it to 45, after like 100sec it turns off, not the gateway connection but the bot itself
It's a bit long
!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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
also i only want the command itself
Tell me if you need more
and where is the defer part?
What defer part?
first of all its not indented into the function body
second thing you need to await it
how about the callback function
maybe its all about this one
and you need to defer it too
but can I send ephemeral message with this?
yes
await ctx.followup.send(embed=m.embed, view=view, ephemeral=True)
Because when I do that it's a regular message not an ephemeral
Returns the follow up webhook for follow up interactions.
!d discord.Webhook.send
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message using the webhook.
The content must be a type that can convert to a string through `str(content)`.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects to send.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.11)") instead of `InvalidArgument`.
Naming an Interaction object "ctx" isn't the best idea if you want to avoid future confusion in my opinion.
ctx typically represents a commands.Context object, not an Interaction, but of course it's entirely your choice.
I agree lol
It was a command context before and I didn't rename the argument
🙃
so like that? await ctx.followup.send(embed=m.embed, view=view, ephemeral=True)
looks right
That doesn't look like ephemeral 😭

It's working I had to put it in the defer too
Thank you very much, I think it wasn't working because I wanted to do it too quickly so I deleted wrong things
But now it works!
Is it possible to add a group command into an already existing group command?
Yes
bot.group(pass_context=True)
async def First(ctx):
if ctx.invoked_subcommand is None:
await bot.say('Invalid sub command passed...')
@First.group(pass_context=True)
async def Second(ctx):
if ctx.invoked_subcommand is Second:
await bot.say('Invalid sub command passed...')
@Second.command(pass_context=True)
async def Third(ctx):
msg = 'Finally got success {0.author.mention}'.format(ctx.message)
await bot.say(msg)
``` something Like this
ok that worked, but it doesnt appear in my subcmds section in my help cmd embed
custom help command? u will have to get the subcommand from the group
!d discord.ext.commands.Group
class discord.ext.commands.Group(*args, **kwargs)```
A class that implements a grouping protocol for commands to be executed as subcommands.
This class is a subclass of [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") and thus all options valid in [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") are valid in here as well.
the above has a commands property
wait ill show u what i mean
It shows my sub commands of my group command, right?
But I just made it so that ,role humans remove is a subcommand of ,role humans. Only this subcommand does not show in the subcommands of the role group subcommands
so im tryna make it so that it adds ,role humans remove to the subcommands of the Group Command: role embed
dont think it's possible to have subcommand of a subcommand
It is tho apparently
Unless that subcommand is also a group then yes.
yeah the ,role humans remove is a subcommand of ,role humans
can u stack the group deco and the command deco?
and ,role humans is a group cmd of ,role
No clue but I know whit prefix command you can have nested groups.
For masochists.
lmfao
why you always come up with these shit ideas
btw FYI no, you can't stack them, it'll Raise a TypeError saying that the callback is already registered
how do i make an embed that sends a picture of the interaction.user.id profile picture?
why specifically ID? the id is just an integer
!d discord.User.display_avatar
property display_avatar```
Returns the user’s display avatar.
For regular users this is just their default avatar or uploaded avatar.
New in version 2.0.
the display_avatar is probably closer to what you want since it returns default avatar too
nah its fine man i fixed it already
this is the error:
line 58, in <module>
client.loop.create_task(schedule_videos_check())
File " File ", line 140, in __getattr__
raise AttributeError(msg)
AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook
this is the source im getting my error from
os.environ['LAST_VIDEO_ID'] = video_id # Update last video ID in environment variable
# Event listener for when bot is ready
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
os.environ['LAST_VIDEO_ID'] = '' # Initialize last video ID as empty string
# Schedule the check_new_videos function to run every 10 minutes
async def schedule_videos_check():
await client.wait_until_ready()
while not client.is_closed():
await check_new_videos()
await asyncio.sleep(600)
client.loop.create_task(schedule_videos_check()) <------- this is where the error is coming from.
does anyone know the fix
as the error suggests maybe try starting the task in setup_hook instead
!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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
im trying to detect a user's rich presence and send them a message if they are playing a game between a range of time
currently have this ```py
async def game_detect():
game = None
for activity in disnake.Member.activities:
if isinstance(activity, disnake.Game):
game = activity
print(f'Game detected: {game}')
if game is None:
return print('not playing game')
# if user ID matches '---' and game is being played, send message to user
if game is not None and '---' in game.author.id:
await message.channel.send('Game detected')
return
# We have the return here because we don't want the command to go any further
but I cant figure out how to get the 'author' of the presence, to then send a message to them in DM
instead of Disnake.Member.activities you need an actual Member object
yeah i realise that, i think i got it to work
hmm, unrelated issue
my token isnt valid but i just regnerated it
it has a different format than before
some previously generated tokens all started with NjExMzAz.. whearas now it starts with ODkwNDA..
did discord update their token generation format??
anyone know why i cant gen a url for my bot in the dev portal /
They always do 🤷
what do you mean?
can I just, not use my bot now?
im so confused its the right token in the right string format no trailing whitespace
Discord changing token format is not a big deal
doesn't that break all new bots though
No
ok, cool, then why do i get this error if the token is 'valid'?
You entered it wrong


