#discord-bots

1 messages · Page 1102 of 1

slate swan
#

crush = @maiden fable

shrewd apex
#

commands.Cog.listner()

slate swan
#

😳

paper sluice
#

Wanna get rejected at runtime?

slate swan
#

||getattr(crush, 'okimiis_love', True)||

#

Thanks

slate swan
maiden fable
#

!ot

unkempt canyonBOT
shrewd apex
slate swan
regal pulsar
#
@commands.Cog.listener()
async def on_guild_join(guild):
    pass
slate swan
regal pulsar
slate swan
regal pulsar
#

oh mb

slate swan
#

@slate swan can i __call__ you?😳

shrewd apex
#

i think u should take some time to cool down 🤣

regal pulsar
slate swan
#

👋

slate swan
shrewd apex
#

ic

velvet compass
#

What is happening

shrewd apex
#

👋

slate swan
#

brad you saw nothing

paper sluice
slate swan
#

😳

velvet compass
slate swan
#

Ok

velvet compass
shrewd apex
#

yes sir

slate swan
#

This channel is ot4 never on topic

shrewd apex
#

pfft

cerulean folio
#

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?

paper sluice
stray adder
#

Help me in this intend always getting stuck here🤯

paper sluice
slate swan
#

what the dog doing🐕

slate swan
slate swan
stray adder
cerulean folio
paper sluice
slate swan
stray adder
#

Someone pls help me brooo

slate swan
#

cogs are just a subclass of a Cog class

flat solstice
#

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?

shrewd apex
#

think of it as an extension of ur bots code like u are plugging in an pendrive in a computer

slate swan
#

so its less of the url, but the json params actually

flat solstice
# shrewd apex it's not dynamic

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?

stiff fern
#
        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) == '![Yes](https://cdn.discordapp.com/emojis/986643084718796810.webp?size=128 "Yes")':
            print('Approved ')
            suggestion_embed.set_footer(text='Status: Accepted\n')
        elif reaction and str(reaction.emoji) == '![No](https://cdn.discordapp.com/emojis/986643106835353691.webp?size=128 "No")':
            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

shrewd apex
#

guild Id -> member id -> roles -> [roles]

cerulean folio
#

is await channel.send('Welcome {0.mention}.'.format(member)) the equivalent of await channel.send('Welcome {member.mention}.' ?

slate swan
shrewd apex
slate swan
#

!f-strings

#

1 min

shrewd apex
#

iirc it's prolly due to some injection problems

slate swan
flat solstice
karmic marsh
#

hey, how can I get the response out of a modal that I send?

slate swan
#

callback

#

!d discord.ui.Modal ( checking docs)

karmic marsh
#
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)
shrewd apex
slate swan
#

How to find out the number of bots on the server (discord.py)

paper sluice
shrewd apex
#

ic

slate swan
unkempt canyonBOT
#

property bot```
Equivalent to [`User.bot`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.bot "discord.User.bot")
slate swan
# karmic marsh hey, how can I get the response out of a modal that I send?

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)
karmic marsh
#

so do I have to define the modal as a class to be able to do this?

karmic marsh
paper sluice
slate swan
#

ah disnake. its eaisier

cunning iris
#

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 ?

slate swan
karmic marsh
#

ah, perfect

paper sluice
karmic marsh
#

use inter.text_values to get responses
how would I do this for two text_inputs?

sick birch
karmic marsh
#

nvm

cunning iris
#

nah, have them launch an app, that they could interact with through the bot, not launch one

shrewd apex
#

that defeats the purpose of game on discord bot tho

flat solstice
slate swan
#

not quite how discord api works

shrewd apex
#

i was just telling u thats ids are static send an req link one sends a req and returns a form of response

sick birch
#

Simple multiplayer games like tic tac toe you can do with buttons, but it's hard to make more complex games on discord

shrewd apex
#

to get stuff done u have to use other fields like headers data files payload requests have a lot of fields

sick birch
#

Considering discord is a social media platform rather than a gaming platform

cunning iris
paper sluice
#

I keep forgetting that discord was originally made for gamers to chat xd

sick birch
cunning iris
#

nevermind then, thanks still

shrewd apex
#

ur bot just redirects or send the website link actual stuff is still on the website

karmic marsh
karmic marsh
#

that sounds like a problem unless I did something wrong

slate swan
shrewd apex
karmic marsh
shrewd apex
#

yeah dpy 2.0 some interaction methods don't work without subclassing

cunning iris
shrewd apex
slate swan
shrewd apex
slate swan
#

maybe, cause this works for slots

flat solstice
cunning iris
shrewd apex
#

yeah that can be done

sick birch
shrewd apex
#

it's easy

sick birch
#

If that user voluntarily sends some files over discord, then yes you can do things with that

shrewd apex
#

suppose they send file as attachment

#

u can just post a request to the attachment link and fetch it

sick birch
#

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

flat solstice
shrewd apex
#

even if it were possible i wouldn't want to authorise a third party bot to

cunning iris
sick birch
#

Then you can do that using message.attachments

shrewd apex
#

add a button callback

karmic marsh
#

I'm assigning roles from a list and allowing users to create their own roles

#

through a button click

flat solstice
sick birch
#

Which is?

flat solstice
#

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

shrewd apex
#

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

flat solstice
#

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

slate swan
#

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?

flat solstice
slate swan
#

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

slate swan
#

And what should be done?

#

Remove discord.

flat solstice
#

yep

shrewd apex
slate swan
#

ok

#

And so everywhere?

#

depends....

shrewd apex
#

yeah everywhere

#

and self first then guild

slate swan
#

😔

shrewd apex
#

i didn't read the whole thing gives me adhd without `

karmic marsh
#

this ^ lol

shrewd apex
#

it shouldn't be required in this case tho

slate swan
#

hm, are decorators in red colour or yellow colour in the discord formatting?

karmic marsh
#

alright... this one is probably quite easy, I just don't know what I'm doing

slate swan
#

oh ok... thanks

karmic marsh
#

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?

slate swan
#

Thanks

slate swan
#

it has nothing to do with your backend

karmic marsh
#

no I think it's a skill issue lol

slate swan
#

restart the client

karmic marsh
#

reading docs now

slate swan
karmic marsh
#

yeah I'm pretty sure I did something wrong lol

slate swan
#

I'm dumb but not a whole lot

karmic marsh
#

nah, I was doing it wrong

#

wasn't responding to the interaction right

slate swan
#

well, no comments

cerulean folio
#

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

fluid ferry
#

looks good to me

cerulean folio
#

aw ! cool !

fluid ferry
#

I wouldn't do it differend

slate swan
#

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?

dense swallow
#

can someone give me an example of button pagination

dense swallow
#

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

slate swan
#

There are a lot of sites that can cover you up

dense swallow
#

i did a simple google search and third party libs were brought up like discord-components

slate swan
slate swan
slate swan
#

Is this fixable ?

#

no

#

just make api calls later on

#

maybe 10 seconds would be fine

cerulean folio
#

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

cerulean folio
#

ooooooh thank youuu !

vale wing
#

Button gets important 😳

cerulean folio
#
|-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'

vale wing
slate swan
vale sierra
#

did somebody has the link to send code ?

vale wing
#

But I think 5 is enough

slate swan
#

Ok thanks

vale wing
#

I even contacted discord support that time

slate swan
vale wing
#

Depends on the file the bot is being ran from

slate swan
vale wing
#

Still depends

slate swan
#

depends on what?

vale wing
#

Entrypoint script

slate swan
#

wut

vale wing
#

Idk I call it that

slate swan
#

🗿

vale wing
#

Basically the script you run

#

But not necessarily

#

The folder the file is in is considered project root and the imports can be done only from its insides

slate swan
#

what

vale sierra
slate swan
#

Dear. please tell me how to add custom emoji to the server. there is an emoji picture in the folder

quaint epoch
#

could you THEORETICALLY, create a bot client, where you log in with bot credentials?

vale sierra
quaint epoch
slate swan
slate swan
unkempt canyonBOT
#

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.
slate swan
vale sierra
vale wing
#

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
quaint epoch
slate swan
vale sierra
quaint epoch
slate swan
unkempt canyonBOT
#

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.
quaint epoch
vale sierra
quaint epoch
#

nope

slate swan
slate swan
vale wing
#

Unless you use relative imports it is always like that

slate swan
vale wing
#

If the main.py is outside of some_folder yes

#

If it is inside, no

slate swan
#

that is so.

stiff fern
#

(<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

slate swan
slate swan
cerulean folio
#

OMG

vale wing
cerulean folio
#

I DID IT !!! Thank you guys !!!!

#

I LOVE YOU ALL SO MUCH !!! THANK YOUUUU ♥️ ♥️ ♥️ ♥️

stiff fern
#

print(reaction)

slate swan
stiff fern
vale wing
#

!d discord.on_reaction_add

unkempt canyonBOT
#

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.
slate swan
stiff fern
slate swan
slate swan
vale wing
stiff fern
#

o

slate swan
vale wing
#

Return is supposed to be bool

stiff fern
#

I was checking it here

 if reaction and str(reaction.emoji) == '![Yes](https://cdn.discordapp.com/emojis/986643084718796810.webp?size=128 "Yes")':
            print('Approved ')
            suggestion_embed.set_footer(text='Status: Accepted\n')
        elif reaction and str(reaction.emoji) == '![No](https://cdn.discordapp.com/emojis/986643106835353691.webp?size=128 "No")':
            print('Rejected')
            suggestion_embed.set_footer(text='Status: Rejected\n')
slate swan
stiff fern
#

reaction.emoji is suppose to be the emoji id

slate swan
#

since its not an empty string but thats not really your point

stiff fern
#

reaction was suppose to be the bool

#

Idk I guess its all a mess now lol

slate swan
vale wing
stiff fern
# vale wing You need to unpack the result ```py reaction, user = await bot.wait_for(...)```
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) == '![Yes](https://cdn.discordapp.com/emojis/986643084718796810.webp?size=128 "Yes")':
            print('Approved ')
            suggestion_embed.set_footer(text='Status: Accepted\n')
        elif reaction and str(reaction.emoji) == '![No](https://cdn.discordapp.com/emojis/986643106835353691.webp?size=128 "No")':
            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
slate swan
#

since its a method of the Guild class as show in the documentation

stiff fern
slate swan
#

Context has a guild property if thats what youre looking for

vale wing
#

str(reaction.emoji) will basically always be true as okimii said

slate swan
#

!d discord.ext.commands.Context.guild

unkempt canyonBOT
stiff fern
#

o

stiff fern
# vale wing Yeah

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

slim spoke
#

hey, is there a way to get the guild name right from the start when someone adds my bot?

slate swan
unkempt canyonBOT
slim spoke
#

found this website but I don't understand how to use it'

slate swan
#

the documentation?

slim spoke
#

yes

#

it gives the command itself but then what

slate swan
#

well its a reference for all the stuff in the library dpy

slate swan
cerulean folio
vale wing
slate swan
#

😭

vale wing
#

😳

slate swan
#

🙄

#

im bad at explaining

slim spoke
# slate swan pardon?

something like this but it's not quite right

async def on_guild_join()
    server = guild.name
vale wing
#

I am studying pedagogy so don't judge yourself

slate swan
haughty nova
#
end = datetime.datetime.utcnow() + datetime.timedelta(seconds = mins*60)```
where I live is the time UTC + 2 hours, how should I fix that?
slate swan
slim spoke
vale wing
haughty nova
#

but when i write the commands it says that the giveaway stops in 2 hours back

vale wing
#

Then try using now()

stiff fern
#

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

slate swan
unkempt canyonBOT
#

remove_footer()```
Clears embed’s footer information.

This function returns the class instance to allow for fluent-style chaining.

New in version 2.0.
stiff fern
#

ah

slim spoke
#

@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'
slate swan
#

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

stiff fern
#

I tried to but it didnt work

slate swan
#
  @commands.command(aliases = "123")

you need put the string in a list @slate swan

slim spoke
dense swallow
wicked atlas
slate swan
stiff fern
#

sure gimme a sec

dense swallow
#

k

dense swallow
haughty nova
#
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?
stiff fern
# dense swallow can u show me how u tried
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('![Yes](https://cdn.discordapp.com/emojis/986643084718796810.webp?size=128 "Yes")')
        await suggestion_msg.add_reaction('![No](https://cdn.discordapp.com/emojis/986643106835353691.webp?size=128 "No")')

        def check(reaction, user):
            if str(reaction.emoji) == '![Yes](https://cdn.discordapp.com/emojis/986643084718796810.webp?size=128 "Yes")':
                suggestion_embed.remove_footer()
                suggestion_embed.set_footer(text='Status: Accepted\n')
                return True

            elif str(reaction.emoji) == '![No](https://cdn.discordapp.com/emojis/986643106835353691.webp?size=128 "No")':
                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

slate swan
slate swan
wicked atlas
slim spoke
slate swan
#
    @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

slate swan
haughty nova
slate swan
sick birch
slate swan
wicked atlas
#

!strings

unkempt canyonBOT
#

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.

haughty nova
#
await ctx.send(f"Tillykke! {winner.mention} du vant {prize}!")```
ah so like this?
dense swallow
# stiff fern ```py suggestion_embed.set_footer(text='Status: Pending\n') suggestion_e...

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
slate swan
haughty nova
#

yes

#

i just forgot tho put it inside the message i sent

slate swan
#

well thats how you make a string an f string

haughty nova
#

thank you

slate swan
#

ah ok

cerulean folio
#

nevermind i fixed it sorry

stiff fern
dense swallow
stiff fern
#

oh im stupid

#

lol

dense swallow
#

lol

slate swan
#

🥺

    @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)
potent spear
stiff fern
potent spear
haughty nova
haughty nova
slate swan
#

and the argument use for class instances is named self not sefl

#

so theirs a typo

lost lichen
#

if i have a slash command in a cog do i still need to use the self arg? disnake

slate swan
#

yes so its in the cog

lost lichen
slate swan
slate swan
stiff fern
# potent spear `return str(reaction.emoji) == "Yes"`
        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

slate swan
#

as shown in your parameters

potent spear
stiff fern
#

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 "Yes" and "Yes" but I guess I have to use the id

scarlet aurora
#

how can I make an argument to suit a string like "like this"

wicked atlas
scarlet aurora
#

a string consisting of spaces

wicked atlas
#
async def my_command(ctx, arg1, arg2, *, rest_of_input):
#

Or, you can use "" around the arguments

slate swan
slate swan
slate swan
#

😅

#

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

cerulean folio
#

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

slate swan
#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

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**...
slate swan
#

you can use this and wait for a message

cerulean folio
#

Mmmh... what about buttons?

slate swan
#

you can use buttons yes

cerulean folio
#

Okie I'll see what I can do

slate swan
#

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!

jaunty sparrow
#

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 swan
#

@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

jaunty sparrow
#

discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook

slate swan
#

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

jaunty sparrow
#

From the traceback it was definitely that method. Interactions are just webhooks under the hood so it does make sense

slate swan
#

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

unkempt canyonBOT
#

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.
slate swan
#

/ and * Why are they?...

slate swan
stiff fern
#

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

slate swan
#

@jaunty sparrow a good solution is to pass Context to the view class

jaunty sparrow
unkempt canyonBOT
#

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.
jaunty sparrow
#

You don't pick the user, it'll send it where the original message is

slate swan
#

and then just using Context.Message to get an instance of a Message object and then using Message.edit

stiff fern
jaunty sparrow
slate swan
stiff fern
#

I was going to do that but .send didn't autocomplete which is usually a sign it wont work 😅

stiff fern
#

Thats what I needed :D

jaunty sparrow
cerulean folio
#
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?

slate swan
#

await delete_emoji(emoji, /, *, reason=None)
emoji then how to write? ID: 123: 986743768231321621

slate swan
#

What is it like?😳

slate swan
# jaunty sparrow yep, like I mentioned editing normally and deferring the response does work, but...

@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

unkempt canyonBOT
#

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)```
jaunty sparrow
slate swan
jaunty sparrow
#

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

slate swan
#

and if you dont defer the response the issue is the 404?

jaunty sparrow
#

If I don't defer the interaction just fails

#

The 404 is when I try to use interaction.edit_original_message

slate swan
#

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

jaunty sparrow
#

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
stiff fern
#
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

jaunty sparrow
scarlet aurora
#
    @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?
jaunty sparrow
# unkempt canyon

@stiff fernLook back to this signature. It takes one positional argument which is the content, the rest is by keywords

slate swan
#
        await ctx.guild.delete_emoji(discord.Emoji(), /, *, reason=None)
#

what to write there?

stiff fern
slate swan
#

tell me pleace

jaunty sparrow
stiff fern
#

o

jaunty sparrow
stiff fern
#

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:)

scarlet aurora
#

but the designated time is a variable

#

set by the user who uses the command

jaunty sparrow
#

Hmm you could call loop() within the command and supply it the function that sends the message

slate swan
jaunty sparrow
slate swan
#
e = ctx.emoji.id("123")

Dear, how to find out emoji id?

jaunty sparrow
#

Thanks again

slate swan
# jaunty sparrow I see. Thanks for the help!

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😔

jaunty sparrow
#

Yeah I asked on the dpy server as well and people weren't sure there either

indigo pilot
#

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

slate swan
livid hinge
#

looks different.. there didn't used to be color at least

slate swan
cerulean folio
#
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?

sick birch
#

Your button callback as way too many arguments

slate swan
sick birch
#

Assuming this is a regular button callback from discord.py

cerulean folio
#

Yeah I'll delete some :o

slate swan
sick birch
#

Button callbacks take self, the view, button, the actual discord.ui.Button instance, and interaction, a discord.Interaction instance

sick birch
#

Also what fork is this? Not familiar with it

cerulean folio
unkempt canyonBOT
#

Hey @slate swan!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

sick birch
#

can you print the full exception by doing raise e?

slate swan
#

?

sick birch
#

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)

slate swan
#

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 ;/

sick birch
#

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()
slate swan
#

wait

slate swan
#

remember raise is like the return keyword it ends execution

sick birch
#

Yes, but it gets the job done

#

We get the actual traceback which is important in this case

slate swan
#

@sick birch yes?

sick birch
#

Using traceback library and setting up properly error handling can come later

sick birch
slate swan
#

run linux?

slate swan
sick birch
#

Yes

sick birch
slate swan
stiff fern
#

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

sick birch
sick birch
slate swan
slate swan
sick birch
#

Doesn't look like it unless your SSHing from command prompt

slate swan
stiff fern
# sick birch That would happen if you add the reaction *after* your wait_for

Well I have it = to it no?

def check(reaction, user):
            if str(reaction.emoji) == "![Yes](https://cdn.discordapp.com/emojis/986643084718796810.webp?size=128 "Yes")":
                return 'True'

            elif str(reaction.emoji) == "![No](https://cdn.discordapp.com/emojis/986643106835353691.webp?size=128 "No")":
                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)
slate swan
#

Why all time i have this problem?

sick birch
slate swan
#

me too

sick birch
slate swan
#

there is nothing on the internet either....

sick birch
stiff fern
#

o

sick birch
#

You're getting ratelimited/blocked from discord

slate swan
#

@sick birch maybe we can find a fix

sick birch
sick birch
#

This is why you usually dockerize your applications so you don't run into issues like these

slate swan
#

and u know Alternative?

#

i tried on another linux and it has the same problem....

sick birch
#

Editors/IDEs are infinetely better than any online code platform as you're still gonna have the same issues

slate swan
#

ah okay man

#

Thank you

stiff fern
sick birch
#

Return a boolean from check, not a Literal['True', 'False'], and don't call the check directly

stiff fern
#

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

granite moat
#

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.

slate swan
slate swan
#

👍

granite moat
stiff fern
#
        def check(reaction, user):
            if str(reaction.emoji) == "![Yes](https://cdn.discordapp.com/emojis/986643084718796810.webp?size=128 "Yes")":
                return True

            elif str(reaction.emoji) == "![No](https://cdn.discordapp.com/emojis/986643106835353691.webp?size=128 "No")":
                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 😬

granite moat
#

Oof it's awfully quiet there lol

slate swan
#

remember Bot.wait_for returns objects of the given event

stiff fern
#

So how would I get the result of check if not referencing it directly

slate swan
#

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

stiff fern
#

so I have to use some format kwarg thing

slate swan
#

@sick birch mmmm

#

maybe threading error

potent spear
slate swan
stiff fern
#

thats how im thinking about it

slate swan
#

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

stiff fern
slate swan
#

And When i creating bot with visual studio code. then i cant hosting?

sick birch
stiff fern
#

push files

#

i use vscode and can host (not from vscode)

sick birch
slate swan
#

free?

stiff fern
#

yes

slate swan
sick birch
#

Some have free tiers, yes

slate swan
sick birch
cerulean folio
#
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 :(

slate swan
#

@sick birch free hosting?

sick birch
#

Reputable cloud service providers have free tiers, yes, e.g oracle, aws, etc

stiff fern
#

Or else why return it ?

slate swan
slate swan
sick birch
wicked atlas
sick birch
#

discord won't let me paste the actual emoji but you get the point

sick birch
stiff fern
#

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

sick birch
#

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

stiff fern
#

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

sick birch
#

you don't even need the if statement, the check function can be done in one line

#

return str(reaction.emoji) == "your emoji here"

stiff fern
#

That goes in the check

sick birch
#

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

stiff fern
#

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

sick birch
#

the wait_for only returns if the check passes

potent spear
sick birch
#

so you can assume if you've gotten past the wait_for the emoji was the one you expected

stiff fern
#

That's what I was confused about, I was thinking it would just continue past it or something

sick birch
stiff fern
#

👍

#
        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('![UpVote](https://cdn.discordapp.com/emojis/986643126796042320.webp?size=128 "UpVote")')
            await suggestion_message.add_reaction('![DownVote](https://cdn.discordapp.com/emojis/986643070864994416.webp?size=128 "DownVote")')
        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

unkempt canyonBOT
#

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.

stiff fern
#
try:
  reaction, user = await interaction.client.wait_for('reaction_add', check=lambda reaction, user: user == interaction.user and reaction.emoji in ['![Yes](https://cdn.discordapp.com/emojis/986643084718796810.webp?size=128 "Yes")', '![No](https://cdn.discordapp.com/emojis/986643106835353691.webp?size=128 "No")'], timeout=None)
except asyncio.TimeoutError: 
  print('Timed out request for suggestion modal.')
else:
   if reaction.emoji == '![Yes](https://cdn.discordapp.com/emojis/986643084718796810.webp?size=128 "Yes")':
     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('![UpVote](https://cdn.discordapp.com/emojis/986643126796042320.webp?size=128 "UpVote")')
      await suggestion_message.add_reaction('![DownVote](https://cdn.discordapp.com/emojis/986643070864994416.webp?size=128 "DownVote")')
                
       elif reaction.emoji == '![No](https://cdn.discordapp.com/emojis/986643106835353691.webp?size=128 "No")':
         suggestion_embed.set_footer(text='Status: Rejected')
         await suggestion_message.edit(embed=suggestion_embed)

Well I tried doing this but it also doesnt work

cerulean folio
#

can someone help me with my very very last struggle in #🤡help-banana pleaaase? pleadingmelt

karmic marsh
#

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:

azure nebula
#
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
karmic marsh
#
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
karmic marsh
#

you need to specify the bot's intents

#
bot = commands.Bot(command_prefix='!', intents = (INTENTS GO HERE))
dusky pine
#

intents=disnake.Intents.default()

#

🙂

karmic marsh
#

except this isn't disnake

#

discord.Intents.default()

#

although it looks like all it does is ban

azure nebula
#

It’s a temporary bot for a ban royale

karmic marsh
#

so you could probably use discord.Intents.bans()

azure nebula
#

Ok

karmic marsh
#

oh, you may need discord.Intents.messages() too

azure nebula
#

So how should it be

#

intents = (discord.Intents.random(), discord.Intents.random2())

#

that’s how it should go?

slate swan
#

random is not an intent.

azure nebula
#

but should it be like that but with valid intents or what?

slate swan
#

!intents like this

unkempt canyonBOT
#

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.

azure nebula
#

ok

sick birch
indigo pilot
#

What is the max amount of questions you can have in a forum?(modal)

karmic marsh
#

test it and find out

azure nebula
#
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!')```
indigo pilot
#

easier to just ask someone who knows

karmic marsh
#

fair enough lol

indigo pilot
#

i hate discord limits, max amount of questions, max amount of question char length

#

smh, and its so small for both

karmic marsh
azure nebula
#

what

karmic marsh
#

we saw it the first time

azure nebula
#

ok, sorry

karmic marsh
#

bot.event needs a required argument

#

try throwing self after on_ready(

azure nebula
#

async def on_ready(self):?

karmic marsh
#

I've done all my work in cogs so it's a bit different but that might work

azure nebula
karmic marsh
#

no, okay

#

maybe someone else knows better than I

torn sail
azure nebula
karmic marsh
#

are you actually running the bot?

#

bot.run(TOKEN)

#

at the end

azure nebula
#

i have py token = 'here_goes_token' bot.run(token)

karmic marsh
#

and you put your token?

azure nebula
#

yeah

karmic marsh
#

or do you literally have 'here_goes_token'

azure nebula
#

i've had bots before, they're not working anymore lol

azure nebula
karmic marsh
#

okay lol

lyric apex
#

Paginator Docs?

karmic marsh
# azure nebula

idk because this is exactly what I get when I use ctrl+c to stop the bot

lyric apex
#

!d discord.ext.commands.Paginator

unkempt canyonBOT
#

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.
azure nebula
#

?

karmic marsh
#

you're sure it's not working right?

sick birch
#

You can fit different components, yes, but there isn't a "question" component

indigo pilot
#

idk what its called

sick birch
#

Text fields?

indigo pilot
#

i mean for forums

azure nebula
indigo pilot
#

yeah i guess text fields

sick birch
#

If you consider a text field to be a question, you can have 5 I believe

karmic marsh
azure nebula
#

i've had bots before and had them running, they're no longer working

#

they worked before without that intent thing

karmic marsh
#

oh, Robin, maybe you would know...

azure nebula
karmic marsh
sick birch
karmic marsh
#

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

sick birch
#

Yes, actually a nice way to do it

karmic marsh
#

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

sick birch
#
role = discord.utils.get(roles, name="role name", color=...)
lyric apex
#

How to purge bot messages in chat using channel history?

sick birch
lyric apex
#

He is using disnake*

azure nebula
#
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!')```
azure nebula
lyric apex
azure nebula
#

my bad

sick birch
sick birch
# azure nebula

I mean, the error kind of says what's wrong, don't you think?

azure nebula
lyric apex
sick birch
sick birch
lyric apex
#

Intents error

azure nebula
#

how do i fix it

sick birch
#

That's right, but I'd like them to reach that conclusion themselves so they learn how to read error messages

sick birch
lyric apex
#

Also There is a link given there

sick birch
#

"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."

azure nebula
# sick birch It tells you

english isn't my main language, only think i get from that it's that i need to enable priviledged intents but idk where

sick birch
lyric apex
slate swan
#

!d discord.TextChannel.purge

unkempt canyonBOT
#

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...
sick birch
#

You'd be interested in the check

azure nebula
#

i feel so dumb

sick birch
#

Don't beat yourself up over it, happens to all of us

azure nebula
#

imma google how to enable that skull

#

OH I GOT IT

slate swan
#

@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)

azure nebula
#

IT'S ON!

lyric apex
lyric apex
slate swan
#

not the type

lyric apex
#

?

slate swan
#

well i think i know what you mean, it's just wrong terminology

lyric apex
#

If I want to delete embed i have detect that

slate swan
#

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)')
slate swan
lyric apex
#

Lemmie Get into docs guessing is a bad idea i think*

slate swan
#

no lol i don't need help

lyric apex
#

He was helping out i think you didn't read the messages!

azure nebula
#

but the !ban @user doesn't work

rich otter
#

what

lyric apex
azure nebula
azure nebula
lyric apex
#

Coz you have an argument passed in def already

slate swan
#

and Message doesnt have a member attribute

azure nebula
#

still doesn't work

lyric apex
#

await member.send

#

not ctx

slate swan
azure nebula
#

yeah

lyric apex
slate swan
#

show updated code*

azure nebula
lyric apex
#

He didn't update anything he just turned on intents

azure nebula
slate swan
#

then change it because its screaming attribute errors

azure nebula
#
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)```
slate swan
#

now

lyric apex
# azure nebula this?

No

await ctx.member.send
#instead of it 
await member.send
#remove
member = ctx.message.member```
lyric apex
#

Whats now?

slate swan
#

thats good but you should change the bots presence in the Bot constructor

#

and you should add a check so anybody cant use it

lyric apex
slate swan
#

!d discord.ext.commands.has_permissions

unkempt canyonBOT
#

@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").
azure nebula
lyric apex
azure nebula
azure nebula
slate swan
lyric apex
#

Anyone can misuse

azure nebula
#

??

#

ik anyone can ban any user

slate swan
azure nebula
#

that's the purpose

slate swan
#

@azure nebula did you enable message content intents in your code?

#

kinda funny lol

slate swan
#

enable intents.message_content

azure nebula
#

ok

lyric apex
#

But not in code

lyric apex
#

?tag intents=intents

novel apexBOT
#

This is not a Modmail thread.

slate swan
#

if he actually said what was wrong it would be nice😔

lyric apex
#

zzTh_QtCat Danny

azure nebula
azure nebula
slate swan
#

feedback lol

lyric apex
slate swan
#

and you should use the classmethod of Intents aka all()

#

since you activated all of them

#

You don't have to

lyric apex
#

Instead of default*

slate swan
lyric apex
slate swan
#

They aren't using all the intents, no need to subscribe to unnecessary events.

#

Especially presences

lyric apex
#

(:

slate swan
#

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

lyric apex
#

):

slate swan
#

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

lyric apex
#

dont you think if he is creating a Perfect bot he will need them

slate swan
#

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

lyric apex
#

Alr

cerulean folio
#
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?

sonic flax
#

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

slate swan
slate swan
cerulean folio
slate swan
#

👍

sonic flax
spring flax
#

so i get this interaction failed but no errors in terminal

slate swan
stiff fern
#

reaction.emoji = Yes but it doesn't pass through the statement

sonic flax
karmic marsh
#

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)
slate swan
karmic marsh
#

but it allows the user to type items that aren't in the list

slate swan
unkempt canyonBOT
#

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.

short silo
sonic flax
short silo
short silo
slate swan
#

hes getting the member from cache

sonic flax
short silo
maiden fable
#

U need 2.0 not 1.7

sonic flax
maiden fable
#

Add this to yr requirements.txt instead of discord.py- git+https://github.com/Rapptz/discord.py

maiden fable
#

Weird then

sonic flax
#

bot.get_user(id) displays None

slate swan
#

you need to use the git version for py-cord too, its 1.7.3 on pypi

sonic flax
#

i enabled these 3 and it stilld oesn't work

maiden fable
slate swan
#

!pip py-cord

unkempt canyonBOT
maiden fable
#

Do it then

sonic flax
#

how

short silo
#

That wrong ?

slate swan
#

lemme check

short silo
#

Since it's installing the requirement, i would hope not

maiden fable
sonic flax
#

wtf is that

slate swan
short silo
maiden fable
sonic flax
#

i did from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.members = True

bot = commands.Bot(command_prefix="!", intents=intents)

short silo
sonic flax
#

ok

sonic flax
slate swan
#

@sonic flax Can you show your code?

slate swan
# short silo Doesnt

works for me. i just installed pycord using the command you told, and imported Option

sonic flax
#

wait

#

im testing it to see if it worked

sonic flax
#

ok it doesnt

slate swan
#

not heroku but another host, i used an eval command to install it

#

but that host has a heroku like environment so yeah

short silo
#

Well, heroku seems to not be able to find it

sonic flax
# slate swan <@710532756181876787> Can you show your code?
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}')
slate swan
#

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?

slate swan
#

change py-cord --pre to py-cord==2.0.0rc1

#

Flags don't work in requirements.txt

short silo
lyric apex
#

What is the method of getting command

slate swan
#

Bot.get_command ez

#

!d discord.ext.commands.Bot.get_command

unkempt canyonBOT
#

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.
lyric apex
#

So using that i want to make a help command that works automatically is that worthy?

slate swan
#

Hi

#

!d discord.ext.commands.Context.send_help this exists btw

unkempt canyonBOT
#

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.
shrewd apex
#

worthy?pithink

lyric apex
slate swan
#

Sends help

lyric apex
shrewd apex
#

sends a help embed however u defined it

slate swan
shrewd apex
#

if u subclass helpcommand

#

otherwise it will send default help

slate swan
#

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.

lyric apex
#

I want it for commands in the bot not the help page

slate swan
#

You can just pass help_command=None into the Bot constructor to just not create one

lyric apex
# slate swan ?

Like if someone does -help say so it send the say command syntax

slate swan
#

oooooof

#

why don't you subclass help command

#

!custom-help

unkempt canyonBOT
#

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

sonic flax
#

@slate swan Do you know how to make these?

slate swan
#

the send_command_help override

lyric apex
#

<t:728223:R>

slate swan
unkempt canyonBOT
#

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...
slate swan
sonic flax
slate swan
#

I don't think Discord supports that

lyric apex
#

time.time()

#

? He wants the current time

sonic flax
lyric apex
#

!e py import time print(time.time())

unkempt canyonBOT
#

@lyric apex :white_check_mark: Your eval job has completed with return code 0.

1655352290.7440596
lyric apex
#

Just use this