#discord-bots
1 messages · Page 1102 of 1
commands.Cog.listner()
😳
Wanna get rejected at runtime?
listener*😔
||getattr(crush, 'okimiis_love', True)||
Thanks
bro😔
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
🔥
🙏
@commands.Cog.listener()
async def on_guild_join(guild):
pass
hunter can i initiate you😳
you need to call it
Thanks
what
the deco @commands.Cog.listener()
oh mb
@slate swan can i __call__ you?😳
i think u should take some time to cool down 🤣
lmao
im going to eat breakfast at 1pm, bye now
👋
no thanks ..., ill pass
ic
What is happening
👋
brad you saw nothing
Runtime
😳
Lets bring it back around to #discord-bots
Ok
Our lovely ot channels are open all the time for tomfoolery
(Especially #ot2-never-nester’s-nightmare currently)
yes sir
This channel is ot4 never on topic
thats True😔
pfft
I'd like to make a folder called commands where each command will have its file called command.py since each command is a big chunk of code.
First question: Is this a good way to organise my code?
Second question: Do I need to learn about __init__.py and use it for that purpose?
Third question: Is it something that could be learnt and executed in less than two hours?
Uve turned into a python interpreter, congrats 
Help me in this intend always getting stuck here🤯
Learn about cogs they will help you spread out ur commands across files, they are not that hard as well
dont make me raise a syntax error😳
what the dog doing🐕
exit()
🗿
Hlp how to fix this
are cogs related to python in general or to discord.py lib?
Learning from previous mistakes ic
🙂 you know it
Someone pls help me brooo
cogs are just a subclass of a Cog class
Is there a specific URL that dictates to discord that a bot is adding a role to someone? Ik things like guild ID, member ID and role ID would be dynamic values but could I conceivably manually manipulate this URL and store it statically?
think of it as an extension of ur bots code like u are plugging in an pendrive in a computer
it's not dynamic
https://discord.com/developers/docs/resources/guild#modify-guild-member with an array of roles
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
so its less of the url, but the json params actually
Well the values such as member ID, guild ID and role ID would be, wouldn't they?, otherwise how do you specify which member in which guild gets which role?
def check(reaction ,user):
return str(reaction.emoji) #and reaction.message == suggestion_embed
reaction = await interaction.client.wait_for('reaction_add', check=check)
if reaction and str(reaction.emoji) == '':
print('Approved ')
suggestion_embed.set_footer(text='Status: Accepted\n')
elif reaction and str(reaction.emoji) == '':
print('Rejected')
suggestion_embed.set_footer(text='Status: Rejected\n')
'tuple' object has no attribute 'emoji'
I printed reaction and it does have emoji so Im confused
guild Id -> member id -> roles -> [roles]
Thanks sarth
is await channel.send('Welcome {0.mention}.'.format(member)) the equivalent of await channel.send('Welcome {member.mention}.' ?
or f"Welcome {member.mention}.", yes. but you should not be using that.
it's same as once u create a discord acc ur userid is fixed it won't keep changing think of it as a json or dict as sarth said
why not?
iirc it's prolly due to some injection problems
Ik member/guild/role IDs are static, but the input to the endpoint/URL will be dynamic otherwise it would only modify 1 role of 1 member in 1 guild
hey, how can I get the response out of a modal that I send?
mymodal = disnake.ui.Modal(title="Create Tag",
custom_id=f"tag-{str(inter.id)}", components=[CustomColorTitleInput(inter, self.user), CustomColorHexInput(inter, self.user)])
await inter.response.send_modal(modal=mymodal)
no like u link a message in this channel it will be domain/guildid/channelid/messageid
How to find out the number of bots on the server (discord.py)
No, that's related to SQL + python. Not normal str formatting
ic
!d discord.Member.bot
property bot```
Equivalent to [`User.bot`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.bot "discord.User.bot")
Modal.on_submit is called when the modal is submitted ```py
from discord import ui
class Questionnaire(ui.Modal, title='Questionnaire Response'):
name = ui.TextInput(label='Name')
answer = ui.TextInput(label='Answer', style=discord.TextStyle.paragraph)
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message(f'Thanks for your response, {self.name}!', ephemeral=True)
so do I have to define the modal as a class to be able to do this?
that's not how I'm doing it currently
Imagine filling a discord modal to apply for a job
ah disnake. its eaisier
hi everyone. I wanted to know if it was possible to have a discord bot that everyone could use to play a game on a separate window, by using commands to interact within the game, which could be an easier way to make multiplayer ?
modal = disnake.ui.Modal(...)
async def callback(inter: disnake.Interaction):
# use inter.text_values to get responses
modal.callback = callback
ah, perfect
Open a window on their computer though discord? No, it might be possible but it surely would be against tos
make a custom channel ig
use inter.text_values to get responses
how would I do this for two text_inputs?
Discord bots can't open seperate windows, you could send them to a website link you made however
nvm
nah, have them launch an app, that they could interact with through the bot, not launch one
that defeats the purpose of game on discord bot tho
so if I wanted to add this servers voice verified role to myself it would behttps://discordapp.com/api/guilds/267624335836053506/members/365262543872327681/{ "roles": [764802720779337729],}ik a bot account would have to call the URL, with a token(?) but not ure where that would go in the URL
not quite how discord api works
i was just telling u thats ids are static send an req link one sends a req and returns a form of response
Simple multiplayer games like tic tac toe you can do with buttons, but it's hard to make more complex games on discord
to get stuff done u have to use other fields like headers data files payload requests have a lot of fields
Considering discord is a social media platform rather than a gaming platform
you told me it's possible to interact with a website tho, are there existing things I can check for this ?
I keep forgetting that discord was originally made for gamers to chat xd
By interacting with a website I mean that your bot can send a link to a website, and your users can click on it
ooh
nevermind then, thanks still
ur bot just redirects or send the website link actual stuff is still on the website
AttributeError: 'Modal' object attribute 'callback' is read-only
Who cares lol
that sounds like a problem unless I did something wrong
then you need to use the subclass method 👍
u can create a channel for the user or use dms that's prolly the best u can do
you mean defining the modal as a class?
yeah dpy 2.0 some interaction methods don't work without subclassing
and is there maybe a way I can use a bot to read a file on someone's pc to get some game data ?
speaking from experience
yeah, or another way round will be this ```py
class Modal(disnake.ui.Modal):
...
modal = Modal(...)
async def callback(inter: disnake.Interaction):
use inter.text_values to get responses
modal.callback = callback```
no way that definitely breakes all tos
maybe, cause this works for slots
what about this? That seems to be what the ss is implyinghttps://discordapp.com/api/guilds/267624335836053506/members/365262543872327681/roles/764802720779337729
I mean, someone uploads a file and the bot gets its informations
yeah that can be done
No, the bots don't run client side which is why things like opening windows aren't possible
it's easy
If that user voluntarily sends some files over discord, then yes you can do things with that
suppose they send file as attachment
u can just post a request to the attachment link and fetch it
Ask yourself if you can do something, if the answer is no, then the bot can't do it either, most of the time. Can you access my files that are on my computer right now through discord? No. Can the bot? No.
Can you open a window on my computer to play a game through discord? No. Can the bot? No.
You get the point
i'm trying to get this to work through a button. So users click the button and the bot adds/removes the role. Do I need to append the bots token or somehting to auth it to perform the action?
even if it were possible i wouldn't want to authorise a third party bot to
just like asher answered, I just wanted to fetch the infos from an uploaded file
Then you can do that using message.attachments
why not just use the dpy functions
add a button callback
this sounds very similar to what I'm doing right now
I'm assigning roles from a list and allowing users to create their own roles
through a button click
that would be the better way to do that I agree, however it doesn't work for my very specific use case
Which is?
A really dumb faq bot. I found it on GitHub and it doesn't support the button callbacks in the right way. I am going to write a new version at some point but I a) don't have the time rn and b) need it up and running asap
wdym dosent support button callback in right way
view = View()
button = Button()
async def button_callback(interaction):
#stuff
button.callback = callback
view.add_item(button)
await ctx.send('message', view=view)
thats all u need to do
mostly in a way I understand lol, this particular bot is using raw API calls and what appears to be a fully custom interaction handler
Help please
@commands.Cog.listener()
async def on_guild_join(guild, self):
name = discord.guild.name
id = discord.guild.id
owner = discord.Guild.owner_id
members = discord.Guild.member_count
bots = discord.Member.bot
servers = len(self.client.guilds)
embed=discord.Embed(title="Бот был добавлен на сервер!", description="", color=0x292B2F)
embed.add_field(name="Название сервера:", value=f"{name}", inline=False)
embed.add_field(name="Владелец сервера:", value=f"{owner}", inline=False)
embed.add_field(name="ID сервера:", value=f"{id}", inline=False)
embed.add_field(name="Участников на сервере:", value=f"{members}", inline=False)
embed.add_field(name="Ботов на сервере:", value=f"{bots}", inline=False)
embed.add_field(name="Серверов у бота:", value=f"{servers}", inline=False)
channel = self.client.get_channel(986593661259227196)
await channel.send(embed=embed)
Ignoring exception in on_guild_join
Traceback (most recent call last):
File "C:\Users\yura0\AppData\Local\Programs\Python\Python310-32\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "E:\Discord\SparkleBot\cogs\onguildjoin.py", line 17, in on_guild_join
name = discord.guild.name
AttributeError: module 'discord.guild' has no attribute 'name'
Something wrong, can you fix it?
you have the params the wrong way round. it needs to be (self, guild).
Thanks
Ignoring exception in on_guild_join
Traceback (most recent call last):
File "C:\Users\yura0\AppData\Local\Programs\Python\Python310-32\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "E:\Discord\SparkleBot\cogs\onguildjoin.py", line 17, in on_guild_join
name = discord.guild.name
AttributeError: module 'discord.guild' has no attribute 'name'
Another bug, please help me fix it
it's guild.name since guild is an instance of Guild
And what should be done?
Remove discord.
yep
just guild.name
i didn't read the whole thing gives me adhd without `
this ^ lol
it shouldn't be required in this case tho
hm, are decorators in red colour or yellow colour in the discord formatting?
alright... this one is probably quite easy, I just don't know what I'm doing
Red
oh ok... thanks
I'm sending a modal and have a callback
but the modal doesn't close when I hit submit
what do I need to put in the callback to close the modal?
Thanks
discord issue
it has nothing to do with your backend
no I think it's a skill issue lol
restart the client
reading docs now
skill issue?
yeah I'm pretty sure I did something wrong lol
no.....the submit button is handled by discord itself smh
I'm dumb but not a whole lot
well, no comments
What do you guys think about this organisation? Is it good?
In main.py I used from ressources import embeds as emb, commands as cmd, requests as rq
looks good to me
aw ! cool !
I wouldn't do it differend
I have task.loop which i want the name of a channel to be edited every 5 seconds but after the 1st update, it stuck. Why's that?
can someone give me an example of button pagination
A walkthrough on action based pagination in discord.py - Pagination_walkthrough.md
that is with reactions, not buttons.. i think discord-ext-menus support buttons but idk how to use it
wait nvm it covers that too
thanks ill have a look at it in detail
There are a lot of sites that can cover you up
i did a simple google search and third party libs were brought up like discord-components
it can be your code, or ratelimits
Not even my code
-seconds=5
-get channel's id
-await channel.edit(name=f"{data})
ok? then its ratelimits lol
Is this fixable ?
no
just make api calls later on
maybe 10 seconds would be fine
Guys I have an issue where from discord import Button, View Button gets important, but View doesn't import. Curious thing is that this happens on a specific file, but the others import it just fine
cz it's discord.ui not discord
ooooooh thank youuu !
Button gets important 😳
|-commands
| |-__init__.py
| |-search.py
|
|-embeds
|-__init__.py
|-greeting.py
In search.py i'd like to import greeting.py how can i do it?
tried from embeds import greeting
console returned : ModuleNotFoundError: No module named 'embeds'
Had the same issue, seems like discord has a hidden ratelimit for channels name editing. 5 seconds is indeed a small interval, I recommend at least 5 minutes
Oh ok. Did you fixed it like that?
did somebody has the link to send code ?
Yeah I just set the update interval to like 30 minutes
But I think 5 is enough
Ok thanks
I even contacted discord support that time
iirc it would be
from parent_folder_name.embeds import greetings
Depends on the file the bot is being ran from
In search.py i'd like to import greeting.py
Still depends
depends on what?
Entrypoint script
wut
Idk I call it that
🗿
Basically the script you run
Usually named main.py
But not necessarily
The folder the file is in is considered project root and the imports can be done only from its insides
what
https://paste.pythondiscord.com/onoluhanom Hello, i have a "mathematic" bug/error with my code, i use SQL / thats a gamble command
Dear. please tell me how to add custom emoji to the server. there is an emoji picture in the folder
could you THEORETICALLY, create a bot client, where you log in with bot credentials?
thats not the appropriate channel
hey, i remember seeing you a few months ago
With the help of a bot, you need to add
!d discord.Guild.create_custom_emoji
await create_custom_emoji(*, name, image, roles=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a custom [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji") for the guild.
There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the `MORE_EMOJI` feature which extends the limit to 200.
You must have the [`manage_emojis`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_emojis "discord.Permissions.manage_emojis") permission to do this.
ОООО
thats possible
So if you have it like this
some_folder
| - main.py
| - module
| - | - __init__.py
| - | - file.py
| - another_module
| - | - script.py
So if you have main.py as entrypoint to import file.py from module you have to do this (literally anywhere)
from module import file```
And if main.py is outside of `some_folder` it would be this `from some_folder.module import file`. In projects and not packages this is the strategy cause there can be only one entrypoint
yeah but i never forget a name
Thank you baby, but is there the same only to delete?
i see that lol
!d discord.Guild.delete_custom_emoji
!d discord.Guild.delete_emoji
await delete_emoji(emoji, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the custom [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji") from the guild.
You must have [`manage_emojis`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_emojis "discord.Permissions.manage_emojis") permission to do this.
Changed in version 2.0: `emoji` parameter is now positional-only.
bruh
anyway did you know the origin of my problem ? @quaint epoch
nope
❤️
no need for custom as it would accept an Emoji object which when you make a emoji with the create_custom_emoji it returns an Emoji object
not always
Unless you use relative imports it is always like that
if youre trying to import script.py from file.py it would still be from some_folder.another_module import script.py iirc
that is so.
(<Reaction emoji=<Emoji id=986643084718796810 name='Yes' animated=False managed=False> me=True count=2>, <Member id=232236405466595328 name='DarkEssentials' discriminator='0001' bot=False nick=None guild=<Guild id=981034070421155850 name='Bot Testing Center' shard_id=0 chunked=True member_count=4>>)
How would I get emoji from this, I've tried reaction.emoji and reaction[0] but it still gives me an error that tuple has no attribute emoji
thats a tuple of a few objects
manage_emojis. oh how do i download it?
OMG
First of all, how do you even get this
I DID IT !!! Thank you guys !!!!
I LOVE YOU ALL SO MUCH !!! THANK YOUUUU ♥️ ♥️ ♥️ ♥️
def check(reaction, user):
return str(reaction.emoji) #and reaction.message == suggestion_embed
reaction = await interaction.client.wait_for('reaction_add', check=check)
print(reaction)
you dont download it, your bot would just need the permission for that guild
So I need to do reaction.emoji[0] or something?
!d discord.on_reaction_add
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Reaction.message "discord.Reaction.message").
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
Note
This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
i dont know and i dont want to know
Is my way inefficient
i didnt help but thats nice
clear. but how to get it?
You need to unpack the result
reaction, user = await bot.wait_for(...)```
o
well your bot would need to be invited with such permissions for the intergrated bot role to have it
Also why do you make your check function return str(reaction.emoji)?
Return is supposed to be bool
I was checking it here
if reaction and str(reaction.emoji) == '':
print('Approved ')
suggestion_embed.set_footer(text='Status: Accepted\n')
elif reaction and str(reaction.emoji) == '':
print('Rejected')
suggestion_embed.set_footer(text='Status: Rejected\n')
it would still be true
reaction.emoji is suppose to be the emoji id
since its not an empty string but thats not really your point
It just gives me an error when writing the command
The check function is supposed to tell the wait_for what event is "correct" and should be returned
def check(reaction, user):
return str(reaction.emoji) #and reaction.message == suggestion_embed
reaction, user = await interaction.client.wait_for('reaction_add', check=check)
print(reaction)
print(isinstance(reaction, tuple))
if reaction and str(reaction.emoji) == '':
print('Approved ')
suggestion_embed.set_footer(text='Status: Accepted\n')
elif reaction and str(reaction.emoji) == '':
print('Rejected')
suggestion_embed.set_footer(text='Status: Rejected\n')
So this is the whole thing basically, aren't I doing that with
reaction, user = await interaction.client.wait_for('reaction_add', check=check)
``` except I didnt include the user
you would need an instance of the Guild class
since its a method of the Guild class as show in the documentation
So I would check the user and emoji inside that function?
Context has a guild property if thats what youre looking for
str(reaction.emoji) will basically always be true as okimii said
!d discord.ext.commands.Context.guild
Returns the guild associated with this context’s command. None if not available.
o
So would that mean after reaction goes through the check it would return whatever the check returns, so I should be able to if reaction then its true
hey, is there a way to get the guild name right from the start when someone adds my bot?
the check kwarg in the Bot.wait_for would need a function object which then it would call it internally and it would use the check function to check all upcoming given event names
on_guild_join has a guild object just use Guild.name
The guild name.
found this website but I don't understand how to use it'
the documentation?
well its a reference for all the stuff in the library dpy
pardon?
what the heck u saying ! You gave me so much docs and tips since yesterday !
good to hear😅❤️
wait_for starts listening for the events of the specified type and parses the event's arguments to check function. If it returns True, the wait_for returns arguments of the received event, if False it just keeps listening until it finds a matching event or a timeout exceeds
😳
something like this but it's not quite right
async def on_guild_join()
server = guild.name
I am studying pedagogy so don't judge yourself
you forgot the guild argument that will be passed to the function when called
end = datetime.datetime.utcnow() + datetime.timedelta(seconds = mins*60)```
where I live is the time UTC + 2 hours, how should I fix that?
thats nice
oh I think I got it, I'll check
If you use utc for everything there shouldn't be any problems
but when i write the commands it says that the giveaway stops in 2 hours back
Then try using now()
So how would I edit a message footer, because it's not apart of discord.Embed and just setting a new footer didn't seem to work
!d discord.Embed.remove_footer
remove_footer()```
Clears embed’s footer information.
This function returns the class instance to allow for fluent-style chaining.
New in version 2.0.
ah
@slate swan I got this error: TypeError: on_guild_join() missing 1 required positional argument: 'guild'
for this code: ```py
@client.event
async def on_guild_join(ctx,guild):
server = guild.name
print(server)
games_in_progress[guild.name] = False
print("Server added to the list")
await ctx.message.send()
tried to add (guild=None): but then I got this error: AttributeError: 'NoneType' object has no attribute 'name'
ctxisnt a valid argument
the event doesnt have Context
you would need to remove it
@commands.command(aliases = "123")
async def counter(sefl, ctx: commands.Context, filename: str):
"""Starts a counter for pressing."""
with open(filename, "rb") as image:
img_byte = image.read("./Железо.png")
await ctx.send('Press!', view=Counter(ctx.author.id))
await ctx.guild.create_custom_emoji( name = "name", image = img_byte, reason=None)
Dear please tell me what is wrong
cant u re-call it?
it has to be a list
I tried to but it didnt work
@commands.command(aliases = "123")
you need put the string in a list @slate swan
to async def on_guild_join()? how do you get the guild name then?
can u show me how u tried
Your bot token is in that image
it accepts only a Guild instance object so just use that
sure gimme a sec
k
👀
client = commands.Bot(command_prefix ="!")
@client.command()
@commands.has_role("Developer")
async def gstart(ctx, mins : int, *, prize: str):
embed = discord.Embed(title = "Giveaway!", description = f"{prize}", color = ctx.author.color)
end = datetime.datetime.now() + datetime.timedelta(seconds = mins/60)
embed.add_field(name = "Slutter kl:", value = f"{end} UTC")
embed.set_footer(text = "Slutter om {mins} minutter!")
my_msg = await ctx.send(embed = embed)
await my_msg.add_reaction(":tada:")
await asyncio.sleep(mins)
new_msg = await ctx.channel.fetch_message(my_msg.id)
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(client.user))
winner = random.choise(users)
await ctx.send("Tillykke! {winner.mention} du vant {prize}!")
client.run(TOKEN)```
Why doesn't the bot send the winner after the end time?
suggestion_embed.set_footer(text='Status: Pending\n')
suggestion_embed.set_author(name=interaction.user, icon_url=interaction.user.avatar)
channel = interaction.guild.get_channel(986468534391545976) or await interaction.guild.fetch_channel(986468534391545976)
await interaction.response.send_message('Prompt submitted.', ephemeral=True)
suggestion_msg = await channel.send(embed=suggestion_embed)
await suggestion_msg.add_reaction('')
await suggestion_msg.add_reaction('')
def check(reaction, user):
if str(reaction.emoji) == '':
suggestion_embed.remove_footer()
suggestion_embed.set_footer(text='Status: Accepted\n')
return True
elif str(reaction.emoji) == '':
suggestion_embed.remove_footer()
suggestion_embed.set_footer(text='Status: Rejected\n')
return False
reaction, user = await interaction.client.wait_for('reaction_add', check=check)
Well this is what Im doing now, before I just didnt have suggestion_embed.remove_footer() but it doesn't work either way so I prob messed something up lol
i dont get errors tho so
you forgot the f before the string
oh
asyncio.sleep() takes the number of seconds, just so you know. Not minutes
ok
how do you use Guild object?
@commands.command()
async def counter(sefl, ctx: commands.Context, filename: str):
"""Starts a counter for pressing."""
with open(filename, "rb") as image:
img_byte = image.read("./Железо.png")
await ctx.send('Press!', view=Counter(ctx.author.id))
await ctx.guild.create_custom_emoji( name = "name", image = img_byte, reason=None)
Dear please tell me what is wrong
you can use the property name
I am new to python so where? I can't find it
well youre missing the filename argument
You forgot the filename argument when calling it from discord
await ctx.send("Tillykke! {winner.mention} du vant {prize}!")
here, in f strings you must add an f before the string to make it an f string so before the quotes
!strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
await ctx.send(f"Tillykke! {winner.mention} du vant {prize}!")```
ah so like this?
ok after setting ur embed footer, overwrite it as another em footer.. in ur case, it'd be: ```py
suggestion_embed.set_footer(text='Status: Pending\n')
rest of the code...
def check(reaction, user):
if str(reaction.emoji) == ':Yes:':
suggestion_embed.set_footer(text='Status: Accepted\n')
await suggestion_msg.edit(embed=suggestion_embed)
return True
elif str(reaction.emoji) == ':No:':
suggestion_embed.set_footer(text='Status: Rejected\n')
await suggestion_msg.edit(embed=suggestion_embed)
return False
await ctx.send(f"Tillykke! {winner.mention} du vant {prize}!")
like so, you see the f before the quotes
well thats how you make a string an f string
thank you
ah ok
nevermind i fixed it sorry
Im not able to use await inside the def check bc of some its not in a async function even tho it is
im trying to make pagination for my help command using discord-ext-menus and im getting this error (given in screenshot)
code: https://paste.pythondiscord.com/uwugesikuz
make it async def
lol
🥺
@commands.command()
async def counter(sefl, ctx: commands.Context, filename: str, name: str):
"""Starts a counter for pressing."""
with open(filename, "rb") as image:
img_byte = image.read("./Железо.png")
name = "123"
await ctx.send('Press!', view=Counter(ctx.author.id))
await ctx.guild.create_custom_emoji( name = name, image = img_byte, reason=None)
you should set the footer AFTER the check, not inside
make the check only return a boolean, don't change embed stuff in there
oh alright, so would I just do
if reaction == True then:
else:
return str(reaction.emoji) == "Yes"
hmm it still doesn't end the giveaway but
can it have something to de with the utc and my time is utc + 2?
same for you
#discord-bots message
you forgot the invoke the command with the filename argument
and the argument use for class instances is named self not sefl
so theirs a typo
if i have a slash command in a cog do i still need to use the self arg? disnake
yes so its in the cog
i dont really understand
great thanks
I indicated (
async def counter(sefl, ctx: commands.Context, filename: str, name: str):
with open(filename, "rb") as image:
img_byte = image.read("./Железо.png")
yes and you invoked the command without the 2 arguments so it was invoked like so <prefix>counter
def check(reaction, user):
return str(reaction.emoji) == ":Yes:"
#if str(reaction.emoji) == ':Yes:':
# suggestion_embed.set_footer(text='Status: Accepted')
# await suggestion_msg.edit(embed=suggestion_embed)
# return True
#elif str(reaction.emoji) == ':No:':
# suggestion_embed.set_footer(text='Status: Rejected')
# await suggestion_msg.edit(embed=suggestion_embed)
# return False
reaction, user = await interaction.client.wait_for('reaction_add', check=check)
if reaction == True:
print("True")
else:
print("False")
Well here's what I tried, I commented everything else out just to keep it simple but it doesn't print anything
So what to do?(((🥺
you invoked the command with the arguments <prefix>counter <filename> <name>
as shown in your parameters
print inside the check
Oh now it prints I guess I was just crazy or forgot to rerun, It just prints false so I just gotta fix the formatting
I tried "
" and "Yes" but I guess I have to use the id
how can I make an argument to suit a string like "like this"
what is "this"?
a string consisting of spaces
async def my_command(ctx, arg1, arg2, *, rest_of_input):
Or, you can use "" around the arguments
Damn, it says here that it’s necessary, but I don’t understand how to write it to work (
its only necessary in your case to open such file, so you would need to provide the name
Still an error
@commands.command()
async def counter(self, ctx: commands.Context, image):
"""Starts a counter for pressing."""
img_byte = image.read("./Железо.png")
name = "123"
await ctx.send('Press!', view=Counter(ctx.author.id))
await ctx.guild.create_custom_emoji( name = "name", image = img_byte, reason=None)
😅
youre calling the command as <prefix>counter
so youre forgetting the image argument and it wont work
image must be a bytes object and not a string
I'd like to make a form using a bot, where the bot will ask a question, and wait for an answer.
Since it's all based on async functions I go pretty lost.
Usually I'd have done things like declaring all my functions, and then:
data = dict()
data = question_n(question_3(question_2(question_1(data))))
or just something like:
data = dict()
for i in range(questions): # where questions is the list of questions
print(question[i])
input(data[i])
or anything like that
But with async I can't do all this, it's still confusing me
!d discord.ext.commands.Bot.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
you can use this and wait for a message
Mmmh... what about buttons?
you can use buttons yes
Okie I'll see what I can do
i recommend to not hard code it much and check the documentation before doing anything its good to know what resources you have on hand!
Hey everyone. How do I edit a message by pressing the button attached to it? according to the Discord API this seems like a proper type of response, but I can't seem to find a way to do it with discord.py. I tried Interaction.edit_original_message but that gave me an error, and the only thing that worked so far is editing the message normally and then deferring the response
@slate swanFinally I did it. works. thank you so much for suffering so much with me
@commands.command()
async def counter(self, ctx: commands.Context):
"""Starts a counter for pressing."""
with open("Железо.png", "rb") as image:
f = image.read()
b = bytearray(f)
await ctx.send('Press!', view=Counter(ctx.author.id))
await ctx.guild.create_custom_emoji( name = "name", image = b, reason=None)
youre welcome
what was the error?
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
well Interaction.edit_original_message did not raise that error, a method that can return a Webhook object is Interaction.followup
which returns a Webhook object and then you can use Webhook.send ive seen this error many time, do i know the problem well maybe you tried to use the Webhook many times or your bot got disconnected from the gateway not sure
From the traceback it was definitely that method. Interactions are just webhooks under the hood so it does make sense
well not quite
iirc you can only respond to and interaction once which is a discord limitation and the other response's are just Webhooks created yes
!d discord.Guild.delete_emoji
await delete_emoji(emoji, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the custom [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji") from the guild.
You must have [`manage_emojis`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_emojis "discord.Permissions.manage_emojis") permission to do this.
Changed in version 2.0: `emoji` parameter is now positional-only.
/ and * Why are they?...
/ makes all arguments before positional only and * makes all arguments after keyword only
So im trying to dm the user
await interaction.response.send_message(user, 'Test')
And it says it only takes 1 to 2 positional arguments but 3 were given
Idk if it works the same way with interaction
@jaunty sparrow a good solution is to pass Context to the view class
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
You don't pick the user, it'll send it where the original message is
and then just using Context.Message to get an instance of a Message object and then using Message.edit
So what would I use to dm a user
user.send
if you want the user of the interaction it would be Interaction.user
I was going to do that but .send didn't autocomplete which is usually a sign it wont work 😅
ty
Thats what I needed :D
yep, like I mentioned editing normally and deferring the response does work, but it's an extra API request and editing the message as the response should be possible
async def yes_callback(message, client, data, interaction):
if interaction.user == message.author: # checks if clicker is asker
await interaction.response.edit_message(content="Selected Yes", view = None)
data['response'] = 0
await next_step(message, client, data) # triggers next question
return True
async def select_anonymous(message, client, data):
select_yes = Button(label ='Yes', style = discord.ButtonStyle.green)
select_yes.callback = yes_callback
view = View()
view.add_item(select_yes)
await message.channel.send('Do you love me?', view = view)
This is a trigger for a command. The bot will ask a question, and the user that ran the command has to answer.
You see how the next question is triggered? It's a bit sus I'd like to change that. I'd like to put both these functions in a bigger one, and make it return True is user clicks, and False if users writes 'cancel'. So then I can call that one big function to make the questionnaire.
Can someone help me?
await delete_emoji(emoji, /, *, reason=None)
emoji then how to write? ID: 123: 986743768231321621
yeah
the emoji argument must be a Emoji object
What is it like?😳
@jaunty sparrow sorry i about the confusion, i thought you had an issue editing the message so that was my mistake, your real issue as i checked again is sending a follow up message which you can use Interaction.send which it checks if the Interaction can be used or a Webhook https://github.com/DisnakeDev/disnake/blob/master/disnake/interactions/base.py#L285-L292 if the 404 http error gets raised it means the api has probably closed the webhook
disnake/interactions/base.py lines 285 to 292
def followup(self) -> Webhook:
""":class:`Webhook`: Returns the follow up webhook for follow up interactions."""
payload = {
"id": self.application_id,
"type": WebhookType.application.value,
"token": self.token,
}
return Webhook.from_state(data=payload, state=self._state)```
I am trying to edit the message 😄
😵💫
I used interaction.message.edit and then interaction.response.defer, and that achieved what I wanted, it's just that from my understanding there should be a way to do it in one go
and if you dont defer the response the issue is the 404?
If I don't defer the interaction just fails
The 404 is when I try to use interaction.edit_original_message
well thats not really raising the error the real 404 is only raising by Interaction.followup
ive seen such a problem many times but ive never really seen solutions over using defer
More of the traceback if it's any help
File "...\pydis\bot\bot\exts\info\help.py", line 69, in callback
await interaction.edit_original_message(embed=embed, view=subcommand_view)
File "...\lib\site-packages\discord\interactions.py", line 438, in edit_original_message
data = await adapter.edit_original_interaction_response(
File "...\lib\site-packages\discord\webhook\async_.py", line 214, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
await interaction.user.send(self.title, "test")
Says send() takes from 1 to 2 positional arguments but 3 were given and all I've really learned from that is that usually its because I need to add some kind of embed= or check= or something but I don't think that works here
I see. Thanks for the help!
@commands.command()
async def automessage(self, ctx, message = None, time = None):
if message is None:
await ctx.send("Please choose a message")
if time is None:
await ctx.send("Please choose a time")
time_string = time
date_time = datetime.strptime(time_string, "%H:%M:%S")
seconds = datetime.strptime(time_string, time)
await ctx.send(f"Set to {seconds} from now")
while True:
await asyncio.sleep(seconds)
await ctx.send(message)``` How can I make it so that when you choose a time (Example: 4:20) every day at 4:20 military time it sends a message?
@stiff fernLook back to this signature. It takes one positional argument which is the content, the rest is by keywords
await ctx.guild.delete_emoji(discord.Emoji(), /, *, reason=None)
what to write there?
So the content would be the text and the keyword would be the user?
tell me pleace
The user is already supplied because you do user.
o
?
So the question is why are you trying to use both self.title and "test". You want them both to be in the message?
I got rid of self.title and it worked, I didn't realize user in the statement would already translate to that actually being the user, I thought I had to put their tag or something so it would know who to message
thank ya:)
The way I would do this is by creating a task that loops at the designated time with https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html?highlight=loop#discord.ext.tasks.loop
Hmm you could call loop() within the command and supply it the function that sends the message
well im not sure the root of the problem, i would need to check the source code more, because i really dont see how defer would help it, because it cant find the Webhook as shown but maybe Interaction gets overwritten by a Webhook object im not really sure😭
of course, this assumes your bot is always up. Otherwise you'll need to store the time in a database for it to persist across restarts
e = ctx.emoji.id("123")
Dear, how to find out emoji id?
No worries, I'll settle for a roundabout solution for now 😄
Thanks again
sorry if i confused your problem with another because ive seen this same error with users using Interaction.followup which makes a webhook and its the same issue and the same thing solves it
time to dig into dpys source😔
Yeah I asked on the dpy server as well and people weren't sure there either
Hey, im just wondering if theres any way to edit a message twice. normally i could just make the msg a var and then message.edit but the org message is outside of the button, and the message gets edited twice inside the button so im not sure what to do, as you cant use response.edit_message twice
interesting maybe its the api or the wrapper
looks different.. there didn't used to be color at least
is that replit or?
def button_check(m):
return m.content.lower() == cancel
async def button_callback(message, client, data, interaction):
if interaction.user == message.author:
clicked = await interaction.response.edit_message(content="Clicked !", view = None)
cancel = await client.wait_for('message', check=button_check)
if clicked or cancel:
if clicked:
return True
else:
return False
So... I guess this will return True if the button is clicked, and False is the word 'cancel' is written before the button gets clicked right?
I don't really know how to test it
actually
I'll edit it, hang on
I guess this is it?
Your button callback as way too many arguments
what?
Assuming this is a regular button callback from discord.py
Yeah I'll delete some :o
Someone had this problem on windows it works normally but not on linux?
Button callbacks take self, the view, button, the actual discord.ui.Button instance, and interaction, a discord.Interaction instance
Can you post your code?
Also what fork is this? Not familiar with it
I didn't get what you mean
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
The function being decorated should have three parameters, self representing the discord.ui.View, the discord.Interaction you receive and the discord.ui.Button being pressed.
source: https://discordpy.readthedocs.io/en/latest/interactions/api.html?highlight=discord ui button#discord.ui.button
can you print the full exception by doing raise e?
?
The current exception doesn't tell us much
We need the full traceback
and the way you have your error handler set up doesn't allow viewing entire traceback (which you should always do, by using traceback library)
what else can I write, the bot works without a problem on windows but the problem appears when I want to run it on linux and I am not able to locate the error
I can't write anything else ;/
Try raise e to get the full traceback
except Exception as e:
raise e
print(f"\n>> Something went wrong, please check the error!\n>> Error: {e}")
input()
wait
that would never print
remember raise is like the return keyword it ends execution
Yes, but it gets the job done
We get the actual traceback which is important in this case
@sick birch yes?
Using traceback library and setting up properly error handling can come later
yes
run linux?
yes but why the useless print if its never going to be reached😭
Yes
Because we're just troubleshooting/debugging
i get that, but why the print and input?
So I think my bots wait_for('reaction_add' is reacting to its own add_reaction methods? Idk why it just started doing it all of a sudden is that like a normal thing that happens
Dunno, was already there, didn't mess with it
That would happen if you add the reaction after your wait_for
you couldve said that😭
Did you run that on linux?
Doesn't look like it unless your SSHing from command prompt
yes
use ssh
Well I have it = to it no?
def check(reaction, user):
if str(reaction.emoji) == "":
return 'True'
elif str(reaction.emoji) == "":
return 'False'
reaction, user = await interaction.client.wait_for('reaction_add', check=check)
if check(reaction, user) == 'True':
elif check(reaction, user) == 'False':
# The code here is firing before any reaction role is used (Except for the ones the bot adds)
Why all time i have this problem?
🤔 never seen that error before
me too
You're uh, not doing that right
there is nothing on the internet either....
Replit
o
You're getting ratelimited/blocked from discord
Popular editors/IDEs include vscode, pycharm, atom (deprecated), sublime text, vim, emacs, etc
Maybe, not sure though since it's not an issue with your code
This is why you usually dockerize your applications so you don't run into issues like these
i want online coding site
and u know Alternative?
i tried on another linux and it has the same problem....
Why online?
Editors/IDEs are infinetely better than any online code platform as you're still gonna have the same issues
How am I suppose to do it 
Return a boolean from check, not a Literal['True', 'False'], and don't call the check directly
Oh, well no I tried that but it didn't work for some reason
And I dont know how else you would get the return value without calling the check directly
I tried doing if reaction but that didnt work either
Not really a discord bot, but uses the discord API so I'd imagine this is the best place to ask, I'm working on this app it uses discord OAuth, anybody know how to detect when someone deauthorizes from the app through discord?
I was guessing there'd be something on the INTERACTIONS ENDPOINT URL but I set that up and don't seem to see any requests when I deauth.
this is not really the channel as you said, but you can ask here #965291516031549500
Ah alright thank you!
👍
I think this is the first time I've used a thread lol
def check(reaction, user):
if str(reaction.emoji) == "":
return True
elif str(reaction.emoji) == "":
return False
reaction, user = await interaction.client.wait_for('reaction_add', check=check)
if reaction == True:
elif reaction == False:
@slate swan do you by chance know how Im suppose to do this
Because this doesn't really work 😬
Oof it's awfully quiet there lol
dang😭
well you cant really compare an object to boolean
remember Bot.wait_for returns objects of the given event
So how would I get the result of check if not referencing it directly
the result is really the variable reference to the coroutine
because the check function is just use to check upcoming events which then it would return the object if the passed function in the check kwarg returns True meaning that is the object that youre looking for
so I have to use some format kwarg thing
your thought process of what wait_for does is not completely correct
not at all you would need to check the object so just make it a string and check the format of it and do what ever
wait_for returns a tuple of some random properties when the event reaction_add is fired and then uses the check to return a value based off whatever Im checking in that tuple?
thats how im thinking about it
Bro, When i creating my bot in the visual studio code. where is monitor link ? for hosting
@sick birch
vsc doesnt have a host option like replit
Would reaction.emoji be the object in question?
And When i creating bot with visual studio code. then i cant hosting?
yeah that was a given from the start haha
use github
push files
i use vscode and can host (not from vscode)
vsc isn't for hosting, only text editing. See #965291480992321536 pins for more on hosting
free?
yes
yes as reaction is the result of the Bot.wait_for which returns a Reaction object
Some have free tiers, yes
and what's next 🤔
Maybe consider dockerizing your bot?
async def add(message, client):
data = dict()
tasks = [
await select_subject(message, client, data),
await select_reporter(message, client, data)
]
for task in tasks:
if not task:
await message.channel.send('Cancelled')
else:
await message.channel.send(task)
task.cancel()
await message.channel.send('Finished !')
It's not working correctly, I'm not achieving the result I want :(
@sick birch free hosting?
Reputable cloud service providers have free tiers, yes, e.g oracle, aws, etc
So should I put the if statement inside the check then
Or else why return it ?
no outside of it
I wanted it on a raspberry pi :/
just return str(reaction.emoji) == ":Yes:", that's all you need
Still useful to dockerize it
discord won't let me paste the actual emoji but you get the point
You can and should still dockerize it
That's going to return True but I'm not connecting how I actually get that "True" to the if statement,
Like for functions I would do
local function Add(Num1, Num2)
return Num1 + Num2
end
And then I could just do
if Add == 4 then
print('Pass')
end
But it doesn't seem like it works the same way here bc you said not to reference it directly
The only thing you should do with the check function is pass it into the wait_for, after that don't mess with it, don't touch it or call it manually
You were calling the check function manually which is the incorrect way to use it
right, so what do I put in the if statement
if something == True:
Well I guess what I'm asking is what it returning to lol
you don't even need the if statement, the check function can be done in one line
return str(reaction.emoji) == "your emoji here"
That goes in the check
Yes:
def check(reaction, user):
return str(reaction.emoji) == "your emoji here"
simple as that, nothing needed
heck you can even pass it in as a lambda if you want
But then how would I do the portion of code that relies on what emoji was used
So im looking at this right, so where it has await channel.send is what Im basically trying to do
the wait_for only returns if the check passes
wait_for returns the exact same args as your check function takes
so you can assume if you've gotten past the wait_for the emoji was the one you expected
So that code basically stops at that point till you get the reaction
That's what I was confused about, I was thinking it would just continue past it or something
Yes, and only goes on if check returns True
👍
try:
reaction, user = await interaction.client.wait_for('reaction_add', check=check)
except:
suggestion_embed.set_footer(text='Status: Accepted')
await suggestion_message.edit(embed=suggestion_embed)
suggestion_channel = interaction.guild.get_channel(986755419894579261) or await interaction.guild.fetch_channel(986755419894579261)
suggestion_message = await suggestion_channel.send(embed=suggestion_embed)
await suggestion_message.add_reaction('')
await suggestion_message.add_reaction('')
else:
suggestion_embed.set_footer(text='Status: Rejected')
await suggestion_message.edit(embed=suggestion_embed)
await interaction.user.send("Your request was denied.")
So here's what I'm trying
Im trying to make it where you can basically react to the request to approve or deny it, right now it'll reject it if I press the check and do nothing if I press the x
If I put the portion of code that would react to True inside of the try: it'll accept regardless because it's just trying it right so Im tryna figure out how I can get it to work with both basically lol
Hey @stone talon!
It looks like you tried to attach file type(s) that we do not allow (.svg). 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.
try:
reaction, user = await interaction.client.wait_for('reaction_add', check=lambda reaction, user: user == interaction.user and reaction.emoji in ['', ''], timeout=None)
except asyncio.TimeoutError:
print('Timed out request for suggestion modal.')
else:
if reaction.emoji == '':
suggestion_embed.set_footer(text='Status: Accepted')
await suggestion_message.edit(embed=suggestion_embed)
suggestion_channel = interaction.guild.get_channel(986755419894579261) or await interaction.guild.fetch_channel(986755419894579261)
suggestion_message = await suggestion_channel.send(embed=suggestion_embed)
await suggestion_message.add_reaction('')
await suggestion_message.add_reaction('')
elif reaction.emoji == '':
suggestion_embed.set_footer(text='Status: Rejected')
await suggestion_message.edit(embed=suggestion_embed)
Well I tried doing this but it also doesnt work
can someone help me with my very very last struggle in #🤡help-banana pleaaase? 
alright... I need to send a view with 'Yes' and 'No' buttons, and then I need to perform an action based on which was pressed
how would I do that?
Here's my (nonworking) attempt:
import discord
from discord import app_commands
from discord.ext import commands
from discord import member
bot = commands.Bot(command_prefix='!')
bot.remove_command('help')
@bot.event()
async def on_ready():
print("Im online.")
await bot.change_presence(activity=discord.Game(name="Use !ban"))
@bot.command()
async def ban(ctx, member: discord.Member, *, reason=None):
member = ctx.message.member
await ctx.member.send(f"Has sido descalificado!")
await member.ban(reason=reason)
await ctx.reply(f'{member} ha sido descalificado!')``` why is this not working
view = disnake.ui.View()
view.add_item(NoButton())
view.add_item(YesButton())
await inter.response.edit_message(f"The color named \"{inter.text_values['name']}\" already exists, but its hex code is {(format(colors[inter.text_values['name']], '#08X')).removeprefix('0X')}.\n Would you like to set the hex code for \"{inter.text_values['name']}\" to \"{inter.text_values['hex']}\"?", view=view)
if view: # This does not work
colors[inter.text_values['name']] = int(inter.text_values['hex'], 16)
json.dump(colors, open('colors.json', 'w'))
await setcolor(self, inter.text_values['name'])
#
class NoButton(disnake.ui.Button):
def __init__(self):
super().__init__(label="No", style=disnake.ButtonStyle.grey)
async def callback(self,inter):
return False
class YesButton(disnake.ui.Button):
def __init__(self):
super().__init__(label="Yes", style=disnake.ButtonStyle.grey)
async def callback(self,inter):
return True
???
the error message tells you exactly what is wrong
you need to specify the bot's intents
bot = commands.Bot(command_prefix='!', intents = (INTENTS GO HERE))
except this isn't disnake
discord.Intents.default()
although it looks like all it does is ban
It’s a temporary bot for a ban royale
so you could probably use discord.Intents.bans()
Ok
oh, you may need discord.Intents.messages() too
So how should it be
intents = (discord.Intents.random(), discord.Intents.random2())
that’s how it should go?
random is not an intent.
its an example
but should it be like that but with valid intents or what?
!intents like this
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
If only...
What is the max amount of questions you can have in a forum?(modal)
test it and find out
import discord
from discord import app_commands
from discord.ext import commands
from discord import member
from discord import Intents
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
bot.remove_command('help')
@bot.event()
async def on_ready():
print("Im online.")
await bot.change_presence(activity=discord.Game(name="Use !ban"))
@bot.command()
async def ban(ctx, member: discord.Member, *, reason=None):
member = ctx.message.member
await ctx.member.send(f"Has sido descalificado!")
await member.ban(reason=reason)
await ctx.reply(f'{member} ha sido descalificado!')```
if i wasnt lazy i would
easier to just ask someone who knows
fair enough lol
i hate discord limits, max amount of questions, max amount of question char length
smh, and its so small for both
help
stop doing that
what
we saw it the first time
ok, sorry
async def on_ready(self):?
I've done all my work in cogs so it's a bit different but that might work
Remove () from @bot.event()
i have py token = 'here_goes_token' bot.run(token)
and you put your token?
yeah
or do you literally have 'here_goes_token'
i've had bots before, they're not working anymore lol
im not that dumb 
okay lol
Paginator Docs?
idk because this is exactly what I get when I use ctrl+c to stop the bot
!d discord.ext.commands.Paginator
class discord.ext.commands.Paginator(prefix='```', suffix='```', max_size=2000, linesep='\n')```
A class that aids in paginating code blocks for Discord messages.
len(x) Returns the total number of characters in the paginator.
?
you're sure it's not working right?
Modals don't have a concept of a "question"
You can fit different components, yes, but there isn't a "question" component
idk what its called
Text fields?
i mean for forums
yeah
yeah i guess text fields
If you consider a text field to be a question, you can have 5 I believe
I'm sorry, I really don't know then
ah okay
i've had bots before and had them running, they're no longer working
they worked before without that intent thing
oh, Robin, maybe you would know...
and when i add it it gives errors that i don't understand
I want to perform an action based on the button that is pressed in this view
Know what?
I'm able to put the action in the callback of the button
but is it possible to just return a boolean based on which button was pressed instead?
like the code I linked, except functional lol
Yes, actually a nice way to do it
https://github.com/Rapptz/discord.py/blob/master/examples/views/confirm.py see here, it's exactly what you want
ah, okay
tyvm, that makes sense
now...
is there a better way to write this?
role = disnake.utils.get(inter.guild.roles, name=option)
if role is not None:
if role.color != colors[option]:
await role.delete()
role = disnake.utils.get(inter.guild.roles, name=option)
if role is None:
role = await inter.guild.create_role(name=option, color=colors[option])
this code works, but seems clunky
I want to either:
> create the role if it doesn't exist
> set it if it does exist and is the right color, or
> delete it and recreate it with the correct color if it does exist but is the wrong color
it would be super clean except role.delete() doesn't set role to None
oh nvm, there's a role.edit() function
You can use utils.get to find a role with multiple attributes, using logical AND
role = discord.utils.get(roles, name="role name", color=...)
How to purge bot messages in chat using channel history?
if role is not None, then just assign that role, it exists and is the right color. else, check if a role with that name exists, but ignore color:
role = discord.utils.get(roles, name=...)
if role is not None, then delete it/edit it with the right color. else, create a new role entirely
He is using disnake*
import discord
from discord import app_commands
from discord.ext import commands
from discord import member
from discord import Intents
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
bot.remove_command('help')
@bot.event
async def on_ready():
print("Im online.")
await bot.change_presence(activity=discord.Game(name="Use !ban"))
@bot.command()
async def ban(ctx, member: discord.Member, *, reason='Descalificado.'):
member = ctx.message.member
await ctx.member.send(f"Has sido descalificado!")
await member.ban(reason=reason)
await ctx.reply(f'{member} ha sido descalificado!')```
i don't get why is this not working
Why did you pasted it 2 times
my bad
Yes, but the concept is what applies
I mean, the error kind of says what's wrong, don't you think?
no, im a noob
Something wrong with token!
Look right at the middle here
No, actually, it's something else entirely
Intents error
how do i fix it
That's right, but I'd like them to reach that conclusion themselves so they learn how to read error messages
It tells you
Also There is a link given there
"Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developres/applications and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead."
english isn't my main language, only think i get from that it's that i need to enable priviledged intents but idk where
The link in the error message is a good starting point
Link is there
@sick birch .
!d discord.TextChannel.purge
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Changed in version 2.0: The `reason` keyword-only parameter was added.
Examples
Deleting bot’s messages...
i feel so dumb
Don't beat yourself up over it, happens to all of us
@lyric apex you should pass a function accepting a single discord.Message parameter into the check kwarg, and its return value determines whether or not the message specified will be deleted (if the return value is truthy, the message is deleted)
IT'S ON!
?
Got it i have to use check functions to detect the message type
not the type
?
well i think i know what you mean, it's just wrong terminology
If I want to delete embed i have detect that
Example from docs
def is_me(m):
return m.author == client.user
deleted = await channel.purge(limit=100, check=is_me)
await channel.send(f'Deleted {len(deleted)} message(s)')
m is a discord.Message object, and the function returns True if the message's author is the bot user
Lemmie Get into docs guessing is a bad idea i think*
no lol i don't need help
He was helping out i think you didn't read the messages!
so it's responding now because i enabled this 3 things which i don't know if i should've turned all of them on
but the !ban @user doesn't work
what
Errors?
im sorry 
no errors, it just doesn't work
member = ctx.message.member isn't required*
Coz you have an argument passed in def already
and Message doesnt have a member attribute
still doesn't work
show code
.
yeah
Make the changes which i said above
show updated code*
this?
He didn't update anything he just turned on intents
it's the same code
then change it because its screaming attribute errors
import discord
from discord import app_commands
from discord.ext import commands
from discord import member
from discord import Intents
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
bot.remove_command('help')
@bot.event
async def on_ready():
print("Im online.")
await bot.change_presence(activity=discord.Game(name="Use !ban"))
@bot.command()
async def ban(ctx, member: discord.Member, *, reason='Descalificado.'):
await member.send(f"Has sido descalificado!")
await member.ban(reason=reason)
await ctx.reply(f'{member} ha sido descalificado!')
token = 'token_goes_here'
bot.run(token)```
updated code
now
No
await ctx.member.send
#instead of it
await member.send
#remove
member = ctx.message.member```
i did
.
Whats now?
thats good but you should change the bots presence in the Bot constructor
and you should add a check so anybody cant use it
Not here in the code*
!d discord.ext.commands.has_permissions
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
i did
this is literally the code
did you restart it?
it's a bot designed so anyone can ban anyone
yea
ah thats kinda funny and strange
No not like that
Anyone can misuse
thats the purpose of his bot
that's the purpose
He enabled all*
enable intents.message_content
ok
But not in code
Doesn't look like it
This is not a Modmail thread.
if he actually said what was wrong it would be nice😔
Danny
it worked
bro there was no errors
feedback lol
Guessing power doesn't work anymore
So is your issue resolved?
and you should use the classmethod of Intents aka all()
since you activated all of them
You don't have to
Instead of default*
yeah but he can lol
A time will come that he will again struggle for it so better than never
They aren't using all the intents, no need to subscribe to unnecessary events.
Especially presences
(:
he activated all intents so you can save a line or 2 ig
¯_(ツ)_/¯
I think next time it's better to help resolve the issue in a practical manner instead of trying to scrape for lines
):
?
It's more than saving lines, more events are physically sent to your bot if you specify all()
i know lmao
Then don't suggest that
dont you think if he is creating a Perfect bot he will need them
Presences? I certainly didn't.
we really dont know what he will do with his bots lmao
This is a pointless discussion
its his bot in the end of the day why would we care
Alr
class AnonymousView(View):
@discord.ui.button(label='Yes', style=discord.ButtonStyle.green, custom_id='yes')
async def yes_callback(self, button, interaction):
self.clear_items()
await interaction.response.edit_message('Confirmed', view = self)
I'm getting an error: AttributeError: 'Button' object has no attribute 'response'
Someone knows why I'm getting this?
how would i get a users discord tag from their id?, for example if i did .find 123 it would print dew#9999 for example
here your button is your interaction and your interaction is your button object so just switch them around
you can just str the member and then just have a member argument
I can't believe it ! thank you !
👍
i mean if i want to do it on anyone tho
so i get this interaction failed but no errors in terminal
well you can do it with a member object and user objects
reaction.emoji =
but it doesn't pass through the statement
i did bot.get_user(my id) and it says None
how can I make slash command autofill strict?
currently I'm using a decorator:
@cog.autocomplete("cog")
async def cog_autocomplete(self, inter, module):
return list(self.bot.cogs)
because the bot can only see users that are in the same guild as the bot
but it allows the user to type items that aren't in the list
yeah im in it
!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.
#help-pretzel any1 ?
what
Do you have intents enabled ?
But should it matter in fetching a member, it should not, i guess ?
hes not fetching a member
hes getting the member from cache
no idea
U need 2.0 not 1.7
i just enabled it and it's not working
Add this to yr requirements.txt instead of discord.py- git+https://github.com/Rapptz/discord.py
I am using pycord btw
Weird then
you need to use the git version for py-cord too, its 1.7.3 on pypi
i enabled these 3 and it stilld oesn't work
Do u have members intent enabled in yr code?
!pip py-cord
No
Do it then
how
I am using
py-cord --pre in requirements
That wrong ?
lemme check
Since it's installing the requirement, i would hope not
intents = discord.Intents.all() in yr bot constructor
bot constructor ??
wtf is that
yeah it should work then
And with what if you don't have all intents enabled, you will get an error
bot = commands.Bot()
i did from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
He has all intents
Doesnt
Hmm u already have it
ok
i dont have the discord.Intents.all() part i only have intents
@sonic flax Can you show your code?
works for me. i just installed pycord using the command you told, and imported Option
On heroku ?
ok it doesnt
not heroku but another host, i used an eval command to install it
but that host has a heroku like environment so yeah
Well, heroku seems to not be able to find it
import discord
import os
import dotenv
import time
import discord.ext
from discord import Intents
from discord.ext import commands
from discord.utils import get
from discord.ext import commands, tasks
from discord.ext.commands import has_permissions, CheckFailure, check
from dotenv import load_dotenv
intents = Intents.default()
intents.members = True
bot = discord.Client()
bot = commands.Bot(command_prefix='.', intents=discord.Intents.all())
load_dotenv()
token = os.getenv("DC_TOKEN")
@bot.event
async def on_ready():
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="test"))
print("bot online")
@bot.command()
@has_permissions(administrator=True)
async def mm(ctx, person1=None, person2=None):
guild = ctx.message.guild
if not person1 or not person2:
await ctx.send('Sorry, but you have to insert a name. Try again, but do it like this: ``.mm <ID #1> <ID #2>``')
else:
if any("mm-4767" in channel.name for channel in ctx.guild.channels):
ctx.send('Thia channel is currently open! Please type ``.close`` to close it.')
else:
channel = await guild.create_text_channel('mm-4767')
channel = discord.utils.get(ctx.guild.channels, name='mm-4767')
channel_id = channel.id
test1 = bot.get_user(person1)
test2 = bot.get_user(person2)
await ctx.send(f'Channel created successfully! <#{channel_id}>')
await channel.send(f"<@{person1}>, <@{person2}>")
await channel.send(f'{test1}, {test2}')
person1 and person2 will be str. either type-hint it to an int or use int(personx) for get_user()
@short silo are you using requirements.txt?
Yeah
Kk
Thanks
What is the method of getting command
get_command(name, /)```
Get a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list of commands.
This could also be used as a way to get aliases.
The name could be fully qualified (e.g. `'foo bar'`) will get the subcommand `bar` of the group command `foo`. If a subcommand is not found then `None` is returned just as usual.
Changed in version 2.0: `name` parameter is now positional-only.
So using that i want to make a help command that works automatically is that worthy?
await send_help(entity=<bot>)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Shows the help command for the specified entity if given. The entity can be a command or a cog.
If no entity is given, then it’ll show help for the entire bot.
If the entity is a string, then it looks up whether it’s a [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog") or a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command").
Note
Due to the way this function works, instead of returning something similar to [`command_not_found()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HelpCommand.command_not_found "discord.ext.commands.HelpCommand.command_not_found") this returns `None` on bad input or no help command.
worthy?
What this does
Sends help
I meant is that good idea or any other method exist
sends a help embed however u defined it
ctx.send_help() will work as if some user used the help command
Context.send_help() is only useful if you are using the commands.HelpCommand system
it will send the default help if you're not and used remove_command.
You can just pass help_command=None into the Bot constructor to just not create one
Like if someone does -help say so it send the say command syntax
Custom help commands in discord.py
To learn more about how to create custom help commands in discord.py by subclassing the help command, please see this tutorial by Stella#2000
@slate swan Do you know how to make these?
the send_command_help override
<t:728223:R>
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
Please don't @ me
I mean, I know how to make that, but how do I make it so it displays the second it started
I don't think Discord supports that
yes
!e py import time print(time.time())
@lyric apex :white_check_mark: Your eval job has completed with return code 0.
1655352290.7440596
Just use this

