#discord-bots

1 messages ยท Page 240 of 1

meager chasm
#

Message content intent is not enabled

#

!intents

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

slate swan
#

can you fix it?

meager chasm
#

Make an instance of discord.Intents and pass it to intents kwarg of your Client

slate swan
#

can you rewrite it?

meager chasm
#

No, you should learn to fix your own code

slate swan
meager chasm
#

We don't help with ChatGPT code here

slate swan
#

i tried to fix it

#

but

#

still not working

meager chasm
#

Good

#

You still haven't enabled message content intent

meager chasm
#

But good progress

#

!d discord.Intents.message_content

unkempt canyonBOT
#

Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:

โ€ข The message was sent by the client

โ€ข The message was sent in direct messages

โ€ข The message mentions the client

This applies to the following events...

meager chasm
#

Set this to True on ur instance

meager chasm
slate swan
meager chasm
#

Read my messages carefully

slate swan
#

oke

#

how just help me decode it

meager chasm
#

Just set intents.message_content to True bruh

slate swan
#

done

meager chasm
#

Now enable it in dev portal

slate swan
#

where

north kiln
#

you don't pass a role id to utils.get

meager chasm
# slate swan where

This is explained in great detail in the tag which you clearly didn't bother reading

slate swan
meager chasm
slate swan
#

how to update

meager chasm
#

Ur on like 1.7.3 you should be on 2.2.3

meager chasm
slate swan
#

bruh

#

even yoou updated it

formal basin
#

How can I make a bot detect a message like any message not a certain word

formal basin
# thin raft Wdym

So for example a person sends a message I want the bot to detect it and delete it

#

Like any message

thin raft
#

Do you know what an event is?

formal basin
thin raft
#

Use the message event and delete the message

formal basin
#

Oh I see

knotty mountain
#

How would I go about finding the latest command usage in a server? For example I want a bot to solve an equation, and after that I want to do /graph, for example, to graph the equation, do I need to store the command myself or is there some discordpy magic I can use

thin raft
#

And then when someone uses the graph command you get the user ID from that dict

smoky sinew
smoky sinew
#
@app_commands.context_menu()
async def graph(interaction: discord.Interaction, message: discord.Message) -> None:
    # do things with message here
knotty mountain
slate swan
#

Why message context Menu huh

smoky sinew
smoky sinew
#

or just parse the data of the equation from the message content

knotty mountain
smoky sinew
#

i only recommend a database because i did something like this before and it's hell ```py
class MyData:
def init(self, a: str, b: int) -> None:
self.a = a
self.b = b

@classmethod
def from_message(cls, message: discord.Message, /) -> MyData:
    return cls(
        a=message.content.split()[0],
        b=message.content.split()[1]
    )
vocal snow
vocal snow
#

what if the message accidently get deleted

#

what u will do then @smoky sinew

smoky sinew
#

then u can't use context menu command on it

vocal snow
#

why not just store the session state in like a dict tho

south burrow
#

Need a help real quick , My bot is online and have no problems but "/" isn't working , IDK WHY , all libraries are updated and Code have no problem

#

Mention me out if anyone can help me

vocal snow
#

how are you syncing the commands?

#

and are the commands defined in cogs or directly via the client.tree.command decorator?

slate swan
#

Naming a bot variable client stonks

north kiln
#

how about naming your bot a

slate swan
#

Don't need a professional to name your variables correctly, e.g.

bot = commands.Bot(...) # Makes sense

client = commands.Bot(...) # Doesn't make sense
past prism
#
script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:3
+ & "c:/Users/jashv/OneDrive/Desktop/Discord Bot/.venv/Scripts/python.e ...
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (c:/Users/jashv/...ipts/python.exe:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException```
#

I am getting this error when i run the file. idk why

#

please help

slate swan
#
    parent_id = category.id if category else None
                ^^^^^^^^^^^
AttributeError: 'int' object has no attribute 'id'
#
channel = await interaction.guild.create_text_channel(name=f"coins-request{interaction.user.id}", category=1107249039377977404 , topic=f"Hello")

#

You cannot get the id attribute of an integer

#

channel is an integer, and potentially already your category ID

#

category = interaction.guild.get_channel(1107249039377977404)

#

?

#

hey i want to set image from my computer's temp folder

embed.set_image(url=f"./temp/qr{userid}.png")

This is not working

#

I dont have any url

#

how to set image

slate swan
#

Does anyone know how to add buttons to messages using discord.py

slate swan
#

hey my command doesnt work for 19 digits discord id user

@commands.command(name='balance' , aliases=['bal'] , help="Check your balance")
async def balance(ctx , user: discord.Member = None):
    if not user:
        user = ctx.author
    else:
        user = user
#

help

#

it work for people with 17 or 18 digit id

#

doesnt work for 19

#

got it

#

its due to animated avatar

slate swan
buoyant plover
#

does anyone know how i can get the content of a message by message id?

slate swan
#

if user avatar is animated then make png

slate swan
slate swan
#

I'm just saying that doing else: user = user

#

Changes nothing

slate swan
slate swan
#

what does user.avatar gives

#

Check the docs shrug

#

!d discord.Member.avatar

unkempt canyonBOT
#

property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
buoyant plover
#

channel = bot.get_channel(110479386170597966) message = await channel.fetch_message(110704355759056569) await channel.send(message)

this returns:
<Message id=110704557598056569 channel=<TextChannel id=11047938615977966 name='key-list' position=6 nsfw=False news=False category_id=110479337219623063> type=<MessageType.default: 0> author=<Member id=78692517431826432 name='malehs bot' discriminator='2109' bot=True nick=None guild=<Guild id=11047206720815104 name='fuck the world' shard_id=0 chunked=False member_count=5>> flags=<MessageFlags value=0>>

but i want it to return the content of the message

slate swan
#

!d discord.Message.content

unkempt canyonBOT
buoyant plover
#

how do i implement that into my code?

slate swan
#

You have got Message

#

So you need to do .content on it

lean harbor
#

How would you change the colour of that side thing?

slate swan
#

!d discord.Embed.colour

unkempt canyonBOT
#

The colour code of the embed. Aliased to color as well. This can be set during initialisation.

lean harbor
#

thanks

lean harbor
slate swan
#

You can pass color kwarg

#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if itโ€™s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
lean harbor
#

aight thanks

north kiln
#

why are there colour and color

slate swan
#

Bri ish pepl

lean harbor
#

is way better

#

EMBED = Embed(title='`[ - Rules - ]`', description=item_info.get(rules)) whys there a unsolved reference to rules

naive briar
#

What

lean harbor
slate swan
#

Show the error

lean harbor
#

i fixed it thanks

lean harbor
# slate swan Show the error
async def announce(ctx, *, message = None):
    if message == None:
        return
    else:
        EMBED = Embed(title='`[ - Rules - ]`', description=item_info.get('rules'))
        await ctx.send(EMBED)
#

This code isn't working when i type !announce

#

wait is it because EMBED doesn't = EMBED

slate swan
#

embed=EMBED

slate swan
lean harbor
#

@bot.command()
async def announce(ctx, *, message = None):
    if message == None:
        return
    else:
        EMBED = Embed(title='`[ - Rules - ]`', description=item_info.get('rules'))
        await ctx.send(Embed=EMBED)
#

bot doesn't do anything when i do !announce

north kiln
#

message is None

south burrow
lean harbor
north kiln
#

you returned the function and else block is not run

north kiln
south burrow
#

`@bot.slash_command(description="Sends Reports")
async def report(ctx, username):

for k in range(5):
    p = Process(target=profile_attack_process, args=(username, [],))
    p.start()
    print_status(str(k + 1) + ". Transaction Opened!")

color = discord.Color.blue()
bot_embed = discord.Embed(title=f'{username}',color=color)
bot_embed.add_field(name="โšก Started sending reports to...",value=f'```@{username}```' )    
    
await ctx.respond(embeds=[bot_embed])`
north kiln
#

no

south burrow
#

then

lean harbor
#

still doesn't work

south burrow
#

idk much about dc bots, i need help

lean harbor
#

this is so annoying.

north kiln
#

this describes a way to sync in setup_hook

#

although it would be better to sync manually

lean harbor
north kiln
#

show your code again

lean harbor
# north kiln show your code again
async def announce(ctx, *, message = None):
    if message == None:
        return
    else:
        EMBED = Embed(title='`[ - Rules - ]`', description=item_info.get('rules'))
        await ctx.send(Embed=EMBED)
north kiln
#
async def announce(ctx, *, message = None):
    if message == None:
        return

^^^

#

why do you even need the message param

slate swan
#

!d discord.ext.commands.Context.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.

For interaction based contexts this does one of the following...
north kiln
#

the else block will not be executed at all with just !announce

lean harbor
slate swan
#

Why do you even need message if you don't use it

lean harbor
#

thats the rules

slate swan
#

But you use item_info varriabls

south burrow
#

bruhhh library is up-to-date

slate swan
#

What do you get when you print in console this discord.__version__

south burrow
slate swan
#

If you are sure it's up to date

#

Then go report it at their support server

lean harbor
buoyant plover
wide sandal
#

it's just .content, you can't call a str object (.content())

jovial patrol
#

is there any bot that can auto remove a role after it was assigned in a specific time delay?

#

like a discord bot

#

nothing youd have to program

white citrus
#

Why is he playing 2 time audio_search_a

                await inter.response.defer(ephemeral=True)
                vc = await inter.user.voice.channel.connect()
                await inter.guild.change_voice_state(channel=inter.user.voice.channel, self_deaf=True)
                check_mark_png = File("pictures\\check_mark_maja.png", filename="check_mark_maja.png")
                re_connected.set_thumbnail(url="attachment://check_mark_maja.png")
                await inter.edit_original_message(embed=re_connected, file=check_mark_png)
                audio_source_a = nextcord.FFmpegPCMAudio("audios\\maja_hello.mp3")
                vc.play(audio_source_a)
                while vc.is_playing():
                    await asyncio.sleep(5)
                
                audio_source_b = nextcord.FFmpegPCMAudio("audios\\maja_soundboard_info.mp3")
                vc.play(audio_source_b)```
round blade
white citrus
round blade
#
engine = pyttsx3.init()

@bot.command()
async def join(ctx):
    if not ctx.author.voice:
        await ctx.send("You are not connected to a voice channel.")
        return
    channel = ctx.author.voice.channel
    voice_client = await channel.connect()
    text = "Starting code Alpha"
    text2 = "What would you like me to do?"
    engine.save_to_file(text, 'text1.mp3')
    engine.save_to_file(text2, 'text2.mp3')
    engine.runAndWait()
    audio_source = discord.FFmpegPCMAudio('text1.mp3')
    voice_client.play(audio_source)
    while voice_client.is_playing():
        await time.sleep(1)

    audio_source = discord.FFmpegPCMAudio('text2.mp3')
    voice_client.play(audio_source)
    while voice_client.is_playing():
        await time.sleep(1)
    await voice_client.disconnect()
white citrus
#

Nope sry

round blade
#

oke

tidal tiger
white citrus
tidal tiger
white citrus
#

Reload?

tidal tiger
#

yep i did

slate swan
white citrus
tidal tiger
#

I've done that a few times.

white citrus
tidal tiger
white citrus
#

Output = What is spent

tidal tiger
#

it wont let me send the img.

white citrus
#

Copy and Paste it

tidal tiger
#

welp

#

you saw my name lol

vocal snow
unkempt canyonBOT
#
Install packages with `python -m pip`

When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.

Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.

Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.

tidal tiger
vocal snow
vocal snow
#

hover over it

#

are you sure it isn't just telling you that the variable is not accessed?

tidal tiger
vocal snow
#

ok, and when you run your script with the python command does it give you an importerror

tidal tiger
#

no module named 'discord'

vocal snow
#

you ran this with the python command or with the IDE run button

vocal snow
#

I explicitly said run it with the python command

#

your environment is misconfigured, the interpreter used by the IDE is different from the one attached to pip

proven birch
#

how to make some python code look in the python format on discord

#

i forgot how to do it

unkempt canyonBOT
#
Formatting code on discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

tidal tiger
vocal snow
#

python filename.py

#

or py file.py

tidal tiger
#

it said nothing.

vocal snow
#

so your script ran

#

without errors

tidal tiger
#

why does it thingy underlined/

tidal tiger
#

Ah.

vocal snow
#

you can run pip -V and see which python it's tied to

round blade
#

why ffmpeg not working???

vocal snow
#

how can we possibly know that

#

without any other information

round blade
vocal snow
#

did you install it and add it to PATH?

tidal tiger
vocal snow
#

or are you passing the executable lcoation?

vocal snow
tidal tiger
#

a..

vocal snow
#

and your client.run call is indented inside the on_ready event so it'll never run

round blade
vocal snow
round blade
vocal snow
#

not the python library

#

did you install ffmpeg itself

round blade
tidal tiger
#

now it just does this

#

lol

tidal tiger
#

mhm.

plucky sun
#

@vocal snowwhat code in def on_ready for slash commands ?

vocal snow
#

what

#

are you asking how to sync the slash commands

plucky sun
#

yes

vocal snow
#

use setup_hook instead of on_ready and use bot.tree.sync

plucky sun
#

send a code

vocal snow
#

bot.tree.sync

#

await bot.tree.sync()

plucky sun
#

thank you

white citrus
slate swan
#

Unknown interaction

#

You're trying to respond to something non existent

real badger
#

how do I use discord.Member.activities and send the activity that the user is doing

slate swan
#

You get a member object

#

You get its activities attribute

#

You iterate over it

#

You send them

real badger
#

i know that

#
@tree.command(name = "track", description = "?")
async def self(interaction: discord.Interaction, user: discord.Member = None):
    if user == None:
        user == interaction.user
    await interaction.response.send_message(f"Your activity is {user.activities}!")

This doesn't work, just sends ()
and when I dont specify a user it doesnt work

slate swan
#

Then you know everything to do it

white citrus
#

Why is he playing 2 time audio_search_a

                await inter.response.defer(ephemeral=True)
                vc = await inter.user.voice.channel.connect()
                await inter.guild.change_voice_state(channel=inter.user.voice.channel, self_deaf=True)
                check_mark_png = File("pictures\\check_mark_maja.png", filename="check_mark_maja.png")
                re_connected.set_thumbnail(url="attachment://check_mark_maja.png")
                await inter.edit_original_message(embed=re_connected, file=check_mark_png)
                audio_source_a = nextcord.FFmpegPCMAudio("audios\\maja_hello.mp3")
                vc.play(audio_source_a)
                while vc.is_playing():
                    await asyncio.sleep(5)
                
                audio_source_b = nextcord.FFmpegPCMAudio("audios\\maja_soundboard_info.mp3")
                vc.play(audio_source_b)```
deft quartz
#

I have a nextcord view where i create 4 button objects in, the button is a separate class not a decorator. How do i stop the view that created the button object from inside of the button class

real badger
#

can someone answer my question

deft quartz
real badger
deft quartz
#

do you have the intents enabled

real badger
#

yes

#

intents=discord.Intents.all() this is in my code

#

so yeah all the intents

deft quartz
#

Did you try to enable the presence intent in the discord developer portal

real badger
#

where

deft quartz
#

idk the rules about links here just google "discord developer portal"

#

should be the first link

real badger
#

yeah but like where in the website

#

where do I inable the presence intent

deft quartz
#

go into the applications tab. select your bot, in the bot tab

#

Privileged Gateway Intents

real badger
#

yeah thats on

#

brooo

south burrow
#

WHY MY BOT isnt syncing
`*@bot.tree.commands(name="Sends Reports")
async def report(interaction: discord.Interaction, username):

for k in range(5):
    p = Process(target=profile_attack_process, args=(username, [],))
    p.start()
    print_status(str(k + 1) + ". Transaction Opened!")

color = discord.Color.blue()
bot_embed = discord.Embed(title=f'{username}',color=color)
bot_embed.add_field(name="โšก Started sending reports to...",value=f'```@{username}```' )    
    
await interaction.response.send_message(embeds=[bot_embed], ephemeral=True)*`
#

@bot.event async def on_ready(): print(f"We have logged in as {bot.user} and are serving at {len(bot.guilds)} Guilds!") try: synced = await bot.tree.sync() print(f"Synced {len(synced)} command(s)") except Exception as e: print(e)

slate swan
#
        try:
            await interaction.user.send(embed=qr_code_embed(interaction.user.id , amount , channel_id) , file=discord.File(f"temp/qr{interaction.user.id}.png"))
        except:
            await interaction.response.send_message("Please enable your DMs to get the QR Code", ephemeral=True)
            await channel.delete()
            return

discord.errors.InteractionResponded: This interaction has already been responded to before

naive briar
#

How straight forward

shrewd fjord
#

application.commands scope needs to be enabled

mossy palm
#

dumb question to ask but since i havent made a discord bot in a while and i heard discord.py is discontinued, what package is good to make a discord bot?

unkempt canyonBOT
native rose
#

How can I talk

#

Iโ€™m new and I need to talk

#

Help please

south burrow
celest panther
#

hey guys, I have a discord bot that I am attempting to get to run with a python script to do an automessage, which I'd put on a schedule, wondered if I could get assistance with that

i have the script, and the bot in the discord, just trying to put the pieces together at this point

celest panther
#

im at a bit of a loss when it comes to actually getting it to run

smoky sinew
#

so?

#

can you share the code at least

celest panther
#

sure

smoky sinew
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

celest panther
sick birch
celest panther
#

then not posted if there was a previous one still there, or less than three messages since the last one

the bat I'm running to run that is giving an error (after i put in the bot token and website link) of "no module named config"

sick birch
#

Sorry? Not sure I'm understanding

smoky sinew
celest panther
#

yes

#

assuming the config was something else, but if i comment it out it won't run

past prism
#
from discord.ext import commands
from discord_slash import SlashCommand

intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents)
slash = SlashCommand(bot, sync_commands=True)

@bot.event
async def on_ready():
    print("Successfully logged in as {0.user}".format(bot))

@slash.slash(name="ping", description="Gives you bot's current ping latency.")
async def ping(ctx):
    await ctx.send(f"Bot's Current Ping is **{round(bot.latency * 1000)}ms**")

bot.run("bot_token")```
#

this is my code, it keeps giving me this error:

  File "c:\Users\jashv\OneDrive\Desktop\Discord Bot\main.py", line 3, in <module>
    from discord_slash import SlashCommand
ModuleNotFoundError: No module named 'discord_slash'```
#

how to fix?

cloud dawn
#

Don't use it.

past prism
#

what?

cloud dawn
#

The Discord library already has build in slash commands this is an old library.

hushed galleon
past prism
#

now it's showing me this error

  File "c:\Users\jashv\OneDrive\Desktop\Discord Bot\main.py", line 12, in <module>    
    bot.tree.command(name="ping", description="Gives you bot's current ping latency.")
    ^^^^^^^^
AttributeError: 'Client' object has no attribute 'tree'```
#

i updated the code to

import discord
from discord.ext import commands
from discord import app_commands

intents = discord.Intents.all()
bot = discord.Client(command_prefix="!", intents=intents)

@bot.event
async def on_ready():
    print("Successfully logged in as {0.user}".format(bot))

bot.tree.command(name="ping", description="Gives you bot's current ping latency.")
async def ping(interaction: discord.Interaction):
    await interaction.response.send_message(f"Bot's Current Ping is **{round(bot.latency * 1000)}ms**")

bot.run("token_of_bot")```
#

why it's showing that? what is the fix?

cloud dawn
#

You need to use a bot instead of a client. You can use a Client but I'd only suggest it if you want a more advanced bot.

past prism
#

hm

#

you mean here bot = discord.Client(command_prefix="!", intents=intents)?

cloud dawn
#

Just change discord.Client to commands.Bot

past prism
#

oaky

grim inlet
#

I was tryna send a discord embed with an added image, but it's just blank.

#

Of course, no errors.

cloud dawn
#

Could you show what you are doing?

past prism
#

i can't use slash command because it's not showing up

cloud dawn
past prism
cloud dawn
#

!d discord.app_commands.CommandTree.sync

unkempt canyonBOT
#

await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Syncs the application commands to Discord.

This also runs the translator to get the translated strings necessary for feeding back into Discord.

This must be called for the application commands to show up.
cloud dawn
#

I'd pass a guild where you are developing then it's instant if you leave it empty it takes up to an hour to sync.

grim inlet
# cloud dawn Could you show what you are doing?
@commands.command()
async def rare(self, ctx, *, query: str) -> None:
    """
    Send an image test.
    """
    await ctx.send(embed=discord.Embed().set_image(url="https://rare-gallery.com/thumbs/669363-George-Washington-quote.jpg"))
cloud dawn
past prism
#

... ?

cloud dawn
cloud dawn
#

!d discord.ext.commands.Bot.setup_hook

unkempt canyonBOT
#

await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

A coroutine to be called to setup the bot, by default this is blank.

To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.

This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login "discord.ext.commands.Bot.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.

Warning

Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_for "discord.ext.commands.Bot.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_until_ready "discord.ext.commands.Bot.wait_until_ready")...
grim inlet
cloud dawn
past prism
#

so I have to write:

@bot.event
async def login():
  await await setup_hook()
cloud dawn
cloud dawn
past prism
cloud dawn
#

Did it finish?

past prism
#

nope

cloud dawn
#

What/ how are you running the code?

past prism
#

wait... it's showing some error

#
Traceback (most recent call last):
  File "C:\Users\jashv\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "c:\Users\jashv\OneDrive\Desktop\Discord Bot\main.py", line 40, in hello
    await interaction.response.send_message(f'Hi, {interaction.user.mention}')
  File "C:\Users\jashv\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 778, in send_message     
    await adapter.create_interaction_response(
  File "C:\Users\jashv\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 221, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In name: Username cannot contain "discord"

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\jashv\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\jashv\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 867, in _invoke_with_namespace       
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\jashv\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 860, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'hello' raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body    
In name: Username cannot contain "discord"```
cloud dawn
#

I've never seen this before

#

Try someone else

#

Was the user called "discord"?

thin raft
#

Btw you can't change names that contain Discord

cloud dawn
#
@client.tree.command()
async def hello(interaction: discord.Interaction):
    """Says hello!"""
    await interaction.response.send_message(f'Hi, {interaction.user.mention}')
cloud dawn
thin raft
#

Ask Discord

past prism
thin raft
#

Yep that's ir

past prism
#

should i change it?

cloud dawn
#

Well that's odd they should prevent you from doing that in the Discord portal then not just throw an error.

thin raft
#

If you want it to work then yes

past prism
#

okay

thin raft
#

Or at least for me

cloud dawn
#

How did he invoke the command then? hmmm

past prism
#

hmmm

slate swan
#

Could someone help i have my code like this

class Main(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix='$',intents=discord.Intents.all())
    
    async def blacklist(self,ctx):
        await ctx.send('HI')```
#

and when trying to run the command it wont work

#

and it says the command does not exist

flint dome
#

this a cog?

#

@slate swan

slate swan
#

no

#

I saw it on here

flint dome
#
@client.command(name = "commandName", aliases=["aliase"])
async def commandName(ctx):
    await ctx.send("template command")
slate swan
#

I know that

#

Nvm its fine

flint dome
slate swan
#

Not a cog just in a class

#
class MyClient(discord.Client):
    async def setup_hook(self):
        print('This is asynchronous!')

client = MyClient()
client.run(TOKEN)```
#

something like that in there example

flint dome
#

aah

#

by chance do you know how to make the client case insensitive

slate swan
#

you mean like if message.content

flint dome
#

no so if i do ping and Ping it still runs the cog

slate swan
#

oh

#

never used cogs so

flint dome
#

rip me

slate swan
#

LOL

flint dome
#

i just learned that it was a thing and cant find a working version

slate swan
#

LOL

flint dome
#

im slow the function is case_insensitive i read it as case_sensitive and set it to false so it never did anything

slate swan
#

๐Ÿ’€

smoky sinew
slate swan
#

Oh

#

And what is that

smoky sinew
#

the command decorator?

#

how does your bot know to register a command

slate swan
#

Oh

shrewd fjord
unkempt canyonBOT
#

@discord.ext.commands.command(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or if called with [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group"), [`Group`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group").

By default the `help` attribute is received automatically from the docstring of the function and is cleaned up with the use of `inspect.cleandoc`. If the docstring is `bytes`, then it is decoded into [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") using utf-8 encoding.

All checks added using the [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
shrewd fjord
#

This deco he is talking about

slate swan
#

I need hep

#

help*

#

can anyone assist ,e

#

me

#

why is this not working ???

#

my python version is 3.11

#

@orchid falcon

#

@full lily

#

@vivid mango

vocal snow
#

No one here gets paid to help. Everyone has a life. Learn to be patient

vocal snow
unkempt canyonBOT
#
Install packages with `python -m pip`

When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.

Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.

Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.

vocal snow
#

On windows the python command is py

#

Unless you install from MS Store

#

This is very basic knowledge that you should have before starting a discord bot... Are you new to python?

#

I would really recommend you learn it first

#

You won't be able to make a discord bot otherwise, they are quite complex

#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

vocal snow
#

You can find some good courses and books to learn from here for free

north kiln
#

I have a command that registers 2 scores and I try to set boundaries of the scores to be 0-30 using discord.app_commands.Range but the command is still executed (RangeError should be raised from what I read in the docs) when the user inputs a number not in that range (like 100)

async def register_match(self, ctx: commands.Context, winner1: discord.Member, winner2: discord.Member, loser1: discord.Member, loser2: discord.Member, winner_score: Range[int, 0, 30], loser_score: Range[int, 0, 30]) -> None:
#

idk if I did anything wrong when defining the command

tired kernel
#

@commands.Cog.listener()
async def on_automod_action(self, action):
Reason = action.content
user = action.user_id
print(f"the reporter is {user}")
print(f"content: {Reason}")
print("test")
with open("Warns.json") as w:
Warndata = json.load(w)
if str(user) in Warndata:
Warndata[str(user)].append(Reason)
else:
Warndata[str(user)] = [Reason]
with open("Warns.json", "w") as w:
json.dump(Warndata, w)

south burrow
#

can someone review my code and tell the error

vale wing
north kiln
#

it was a hybrid command

vale wing
#

In app commands it is

async def cmd(self, interaction: discord.Interaction):
    await interaction.response.send_message(...)```
vale wing
vale wing
north kiln
#

I said the command is still executed when input score is like 100

vale wing
#

!d discord.app_commands.Range

#

Oh wait frick it's hybrid command

#

I keep forgetting these even exist

south burrow
vale wing
#

!d discord.ext.commands.Range

unkempt canyonBOT
#

class discord.ext.commands.Range```
A special converter that can be applied to a parameter to require a numeric or string type to fit within the range provided.

During type checking time this is equivalent to [`typing.Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated "(in Python v3.11)") so type checkers understand the intent of the code.

Some example ranges...
north kiln
#

I have tried both and it didn't show up

vale wing
#

@north kiln k do you have error handlers?

north kiln
#

but it does warn me when I am not inputting integers

vale wing
#

๐Ÿง๐Ÿง๐Ÿง

north kiln
south burrow
vale wing
north kiln
#

so half of the check works but other half does not

vale wing
#

Are you using commands.Range or app_commands.Range?

north kiln
#

I have tried both

south burrow
vale wing
north kiln
#

oh damn

#

I forgot to sync then

vale wing
#

Switch to disnake and never think about sync again

south burrow
#

@vale wing

vale wing
#

Errors?

south burrow
vale wing
#

I need complete traceback

south burrow
#

I'll send u the file

slate swan
#

Starting the bot at the top is not a too smart idea

slate swan
#

You start your bot at line 24 and create commands etc. below it, not such a good idea

north kiln
#

I still don't know the good practices when configuring a bot

buoyant quartz
#

my bot is verified with the proper intents enabled and verified yet i still get this.

livid hinge
#

what's the simplest way to have a button at the bottom of a text message

#

on a message command if that's the right term to use

#

wonder if this would work for the message

async def send_message(self, ctx: Context) -> disnake.Message:
        f = io.StringIO("Some text to download")
        return await ctx.channel.send(
            content="some content",
            file=disnake.File(
                fp=f,
                filename="message_log.txt"
            )
        )```
#

i guess that would just have the attachment directly not a button

vale wing
#

I don't quite understand how buttons and files are related in your problem

#

If you mean you want buttons to be below attachments that's not possible to customise

vale wing
north kiln
#

is the only way to do that by setting up a listener

vale wing
north kiln
#

yes

#

I want to bot to do something once all 4 ppl have reacted with a reaction

vale wing
#

That's simple wait_for

r, u = await bot.wait_for("reaction_add", check=lambda r, u: u.id == ctx.author.id and r.message.id == message.id and r.emoji == "๐Ÿ…ฑ๏ธ")```
#

Iirc that's how it's done

north kiln
#

something I don't understand here is wait_for should return the reaction and users once the check is met

#

but I want sth like a condition to run more code

#

kinda lost here

vale wing
#

The condition comes after the wait_for or if it was timed out

north kiln
#

r, u are both not conditions tho?

#

check does the checking

vale wing
#

r is reaction, u is user

north kiln
#

so I run my wanted code in check that's weird

vale wing
#

You can check the reaction emoji afterwards

#

For example alter the check condition to allow several emojis and then check using simple if what emoji was selected

north kiln
#

the thing is I am passing other users than the author in my command so I thought the way is to use reaction.users() but it is async and cannot be used in the check function

naive briar
#

!d discord.Client.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.11)"). 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.11)") 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.11)") 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**...
north kiln
#

now I think

#

wait_for is like finding a event where some event requirements are met
but what I want is to run some more code when some event requirements are met (eg. all the users I mentioned have reacted with ๐Ÿ…ฑ๏ธ on the message sent by the bot after command is executed)

naive briar
#

What

north kiln
#

as if I put some code after wait_for, it could run even when the condition is not met

#

so like:

reaction, user = await self.bot.wait_for('reaction_add', timeout=60.0, check=check)
await ctx.send('hiiiii')
#

will the bot send hiii only after wait_for returns

naive briar
#

Yes? Why don't you just test it

north kiln
#

I have tried but didn't get my expected result

#

maybe I did something wrong somewhere else

naive briar
#

What's the actual code then

north kiln
#

sorry but I am gonna take a break for myself first

north kiln
vale wing
#
required_users = {u.id for u in your_users_list}
r, _ = await bot.wait_for(..., check=lambda r, u: r.message.id == message.id and {user.id async for user in reaction.users} == required_users)

The code will only proceed after all the required users have reacted

#

!d discord.Reaction.users

unkempt canyonBOT
#

async for ... in users(*, limit=None, after=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") representing the users that have reacted to the message.

The `after` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

Changed in version 2.0: `limit` and `after` parameters are now keyword-only.

Examples

Usage...
vale wing
#

Frick asynchronous iterator

north kiln
#

reaction.users gives an async generator

#

๐Ÿ™‚

#

I am stuck here basically

vale wing
#

Not sure if comprehension works with async expressions but try

#

Eh wait

#

I will resolve this now

#

!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.11)"). 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.11)") 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.11)") 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**...
vale wing
#

Why check can't be coro brainmon

#

Maybe this is xy problem

vale wing
dapper citrus
#

hi when i create a bot will i have "active developer" badge?

vale wing
dapper citrus
#

cool, can i create one?

vale wing
#

Sure why not

#

If you only need the badge there are plenty of tutorials on yt, it doesn't require professional help from here

dapper citrus
#

oh ill see an youtube tutorial

#

uh it is not necessary ill study first

#

AH There r so much disctraction to my study

north kiln
# vale wing Uh tell me what exactly you are trying to do

Someone executes a command, passes 4 other discord member (might not include the author), the bot sends a message in response to the command, and wait until the 4 members passed have reacted that message with a reaction given by the bot let's say incident_actioned then the bot gives another response

#

Idk if I could replace the reaction part with like the 4 members all clicking a button or sth but the bot needs to wait until all of them responded

slate swan
vocal snow
#

you're passing the token to os.getenv

#

and reset your token

vale wing
#

If you want to wait in actual command code until all reactions are completed you can do this (pseudocode)

async def command(...):
    future = asyncio.get_event_loop().create_future()
    reactions[message.id] = [1, future]
    await future
    # next code

async def listener(reaction, user):
    data = reactions[reaction.message.id]
    data[0] += 1
    if data[0] >= 4:
        data[1].set_result(True)

It's pseudocode and you need to add a few checks but this is the principle

deft quartz
#

is there a way to call a command from a different cog on let's say a button callback in a different cog

thin raft
white citrus
#

How can i translate embeds with my bot

north kiln
#

My listener will share variable with my command?

naive briar
#

That's just how python works

north kiln
#

Or I have to store every execution detail in a database then query the database everytime

naive briar
#

!e

def func():
    a = 0
    def inner_func():
        print(a)

    inner_func()

func()
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

0
north kiln
#

But I don't define the listener in my command function or do I

naive briar
#

What does that supposed to mean

north kiln
#

The listener is not inside that function

#

It is in the cog

naive briar
#

Show the code

#

I don't understand one bit

north kiln
#

I am on my phone now

obsidian fable
#
Traceback (most recent call last):
  File "C:\Users\lona\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\files\meow-py\recode.py", line 35, in load
    await bot.load_extension(f"cogs.{cog}")
  File "C:\Users\lona\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension
    await self._load_from_module_spec(spec, name)
  File "C:\Users\lona\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 952, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.hello' raised an error: TypeError: object NoneType can't be used in 'await' expression```


what's the issue? This is my cogs load command
```py
@bot.tree.command(name="load", description="Loads a cog file")
async def load(interaction: Interaction, cog: str):
    await interaction.response.defer()
    try:
        await bot.load_extension(f"cogs.{cog}")
        print(f"Loaded '{cog}.py'")
        await interaction.followup.send(f"Loaded `{cog}`", ephemeral=False)
    except commands.ExtensionNotFound:
        print(f"Extension '{cog}.py' not found")
        await interaction.followup.send(f"Extension `{cog}.py` not found.", ephemeral=True)
hushed galleon
#

it means your extension file is the issue, not the command

#

but usually there's more to that error message, i think you've only copied the bottom half of it

obsidian fable
# hushed galleon it means your extension file is the issue, not the command

this is my hello.py file

import discord

from discord import app_commands
from discord import ui
from discord.ext import commands
from discord.interactions import Interaction

class hello(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @app_commands.command()
    async def my_command(self, interaction: Interaction):
        await interaction.response.send_message("Hello")

def setup(bot):
    bot.add_cog(hello(bot))```
obsidian fable
# hushed galleon but usually there's more to that error message, i think you've only copied the b...
  File "C:\Users\lona\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\files\meow-py\recode.py", line 35, in load
    await bot.load_extension(f"cogs.{cog}")
  File "C:\Users\lona\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension
    await self._load_from_module_spec(spec, name)
  File "C:\Users\lona\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 952, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.hello' raised an error: TypeError: object NoneType can't be used in 'await' expression

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\lona\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\lona\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 867, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\lona\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 860, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'load' raised an exception: ExtensionFailed: Extension 'cogs.hello' raised an error: TypeError: object NoneType can't be used in 'await' expression``` here you go
vocal snow
#

async def

obsidian fable
#

I am sorry I am new to these

#

or its the class

hushed galleon
obsidian fable
#
import discord

from discord import app_commands
from discord import ui
from discord.ext import commands
from discord.interactions import Interaction

class HelloCog(commands.Cog):
    async def __init__(self, bot):
        self.bot = bot

    @app_commands.command()
    async def hello(self, interaction: Interaction):
        await interaction.response.send_message("Hello")

def setup(bot):
    bot.add_cog(HelloCog(bot))```

this is my current cog file code, its still throwing errors
surreal valve
#

what is a cog

hushed galleon
obsidian fable
#
async def setup(bot):
    bot.add_cog(HelloCog(bot))```
#

like this?

naive briar
#

add_cog is a coroutine

#

So, await it

hushed galleon
obsidian fable
#

is it possible to sync commands in a cogs file aswell? using await bot.tree.sync()

hushed galleon
hushed galleon
north kiln
# north kiln But I don't define the listener in my command function or do I

I will try to explain what I want to do with a minimal example

@commands.hybrid_command()
async def register_match(self, ctx: commands.Context, user1: discord.Member, user2: discord.Member, user3: discord.Member, user4: discord.Member):
    await ctx.send(f'Hi {user1.mention} {user2.mention} {user3.mention} {user4.mention}, please react with โœ… to confirm your registration'
    #wait until all 4 of them reacted โœ…
    #run code to insert data into database

but when I define a listener in the same cog, like

@commands.Cog.listener('on_reaction_add'):
async def check_if_all_reacted(reaction: discord.Reaction, user: discord.Member):
    pass

it shouldn't have access to user1 to user4 right? So I couldn't check if user1 to 4 has reacted to that message, maybe I could store every execution detail in a database then try to query the database with reaction.message.id to fetch info but I don't want to do that

obsidian fable
hushed galleon
#

definitely dont do that

naive briar
hushed galleon
north kiln
#

I can't use wait_for as I couldn't get the users reacted in the check function

#

reaction.users returns an async generator

naive briar
#

You can do something like storing who reacted

north kiln
#

yes but that means I have to use a database probably

#

and interact with it

obsidian fable
naive briar
#

Like

reacted_members = []

def check(reaction, member):
    reacted_members.append(member)
    return member in reacted_members
naive briar
naive briar
north kiln
#

the condition I need is when all 4 members reacted tho

naive briar
#

Then check it

north kiln
#

so I should be checking the len or sth

naive briar
#

Like

reacted_members = []

def check(reaction, member):
    reacted_members.append(member)
    return all(member in reacted_members for member in (member_1, member_2, member_3, ...))
#

There are many things you can do depending on what you want

north kiln
#

I am just kinda frustrated that I couldn't use the reaction.users as a shortcut and has to do some weird workaround around check not being a coroutine

naive briar
#

You don't need it anyway

thin raft
naive briar
#

Since you can just store them yourself

thin raft
#

Wait nvm

naive briar
thin raft
#

I thought you were doing something else

obsidian fable
hushed galleon
#

why would you? you're already assigning the bot instance to self.bot

#

would you prefer giving it a different name

obsidian fable
cloud dawn
hushed galleon
north kiln
#

how would I do that

obsidian fable
reef gazelle
#

Need to rewrite my shit was treating cogs like extensions when i realised i can just solely use extensions ๐Ÿ’€

hushed galleon
#

the cogs need to be loaded before you call sync()

obsidian fable
#

wait, what's extensions?

reef gazelle
#

separating a command into its own file

#

Cogs can contain multiple commands

hushed galleon
#

extensions is what provides Bot.load_extension() and the setup() function, cogs are the commands.Cog class definitions

#

they're almost always combined together which gets people pretty confused about the difference

reef gazelle
#

I just want 1 command in the file that iโ€™m working on at the moment

obsidian fable
#

I feel like I should be using extensions instead, how can I do that?

hushed galleon
#

you already are

obsidian fable
#

but isnt this just normal cogs?

reef gazelle
#

you just donโ€™t use the cog class

obsidian fable
#

i see

reef gazelle
#

and use add command instead of add cog

#

in the setup function

obsidian fable
#

should I be using @app_commands.command() if I am using Interaction?

reef gazelle
#

yeah

obsidian fable
#

but that doesnt sync so I am not sure

reef gazelle
#

Are you syncโ€™ing them globally or locally.. globally can take some time

#

local youโ€™ll need to specify the guild to sync them to

obsidian fable
#

I am using synced = await bot.tree.sync()

#

so I think thats global

#

and I am not sure how to specify guilds

reef gazelle
#

iโ€™m on mobile 1 sec

obsidian fable
#

take your time dw

reef gazelle
#

Mainly this bit

I use a setup_hook cause your not meant to call some things in on_ready

#

Should load extensions and sync the commands in here

obsidian fable
# reef gazelle

thank you, does that mean I don't need to sync the commands in async def setup but the main.py file?

cloud dawn
reef gazelle
north kiln
reef gazelle
#

so have like setup_hook = YourSetupFunction

SetupFunction:
load_extensions()
sync_slash()

#

Then obv need to make the load and sync functions somewhere in main also

cloud dawn
reef gazelle
obsidian fable
cloud dawn
# north kiln I will try to explain what I want to do with a minimal example ```py @commands.h...

I'd do it like this```py
self.memb = ["dunno", "some", "members", "etc"]

@commands.Cog.listener("on_raw_reaction_add")
async def check_if_all_reacted(self, payload: discord.RawReactionActionEvent) -> None:
emoji_name = "idk some emoji"
if payload.emoji != emoji_name:
return

message = await payload.member(payload.message_id)
reaction = discord.utils.find(lambda e: e.name == emoji_name, message.reactions)

if reaction.count >= 4:
    users = [user async for user in reaction.users() if user in self.memb]
    if len(users) == 4:
        print("Yeey they all reacted")
north kiln
#

umm

#

what will happen if I executes the command multiple times

#

the 4 members are different everytime I call the command

cloud dawn
#

I mean you could just save it

#

The command would use self with a dict to keep track.

obsidian fable
cloud dawn
#

I'd build it so that it looks at the message id's as well. If message id not in dict then don't execute it.

#

And then you could also delete the record and remove reactions. Fancy :3

reef gazelle
cloud dawn
#

What even is build_tree

obsidian fable
reef gazelle
#

lemme look

cloud dawn
#

Some are a bit dated but it's an example.

reef gazelle
#

^

obsidian fable
#

thank you

north kiln
#

so I guess this works for me

confirmation_msg = await ctx.send(f'Hi {user1.mention} {user2.mention} {user3.mention} {user4.mention}, please react with โœ… to confirm your registration'

pending_members = set((user1, user2, user3, user4))
reacted_members = set()        

def check(reaction: discord.Reaction, user: discord.Member):
    if reaction.message != confirmation_msg: #ignore reactions on messages other than the one bot has sent
        return False
    reacted_members.add(user)
    return pending_members.issubset(reacted_members) and str(reaction.emoji) == ':white_check_mark:'
   
try:                        
    reaction, user = await self.bot.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
    await ctx.send('The command has timed out.')  
    return 

await ctx.send('All 4 members have reacted!')
minor lodge
#

what did I do wrong

#

pls help:(

north kiln
#

you leaked your token

#

that's what you did wrong

minor lodge
#

doesnt matter

north kiln
#

how

minor lodge
#

help pls:(

north kiln
#

well it is

@client.command
async def gamble():
minor lodge
#

thx

north kiln
#

also reset your token

minor lodge
#

yup

#

What did I do wrong this time

#

@north kiln

north kiln
#

do you even know basic python syntax

minor lodge
#

nah

north kiln
minor lodge
#

XD

north kiln
#

then perhaps you should learn it

minor lodge
#

pls bro

cloud dawn
#

Looks good to me

reef gazelle
#

missing a few new lines

#

like you typed it into notepad with word wrap on

minor lodge
#

like this? @reef gazelle @north kiln

cold sonnet
#

hell

reef gazelle
#

You need to indent 19

#

and the rest

cold sonnet
#

still hell

reef gazelle
#

๐Ÿ˜‚

cold sonnet
#

but it would work

#

no

#

it wouldn't

reef gazelle
#

everything is outside gamble rn

minor lodge
#

I'm confused

cold sonnet
#

duh

minor lodge
#

what do i need to do

#

i got it

#

i think

slate swan
minor lodge
#

nah bro idk

south burrow
lean harbor
#

How would you make a database and then make commands which can change the value of a specific variable in the database?

#

Or is there any way to link Google excel to the value of a variable?

formal basin
#
Traceback (most recent call last):
  File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 842, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 56, in clear
    await interaction.response.send_message(f"deleted {amount} messages")
  File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/interactions.py", line 778, in send_message
    await adapter.create_interaction_response(
  File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/webhook/async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 860, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'clear' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
#
@commands.has_permissions(manage_messages=True)
async def clear(interaction: discord.Interaction, amount: int):
     await interaction.channel.purge(limit=amount)
     await interaction.response.send_message(f"deleted {amount} messages")```
#

idk how to fix this

minor lodge
#

unidentified names

turbid condor
#

Just put " " around each roles

turbid condor
#

Instead use random.randomchoice(Roles)

turbid condor
#
Roles = ["Role 1","Role 2"
roles= random.randomchoice(Roles)
turbid condor
formal basin
#

what is it then?

turbid condor
#

It's just that bot fails to respond in the time it is required to

formal basin
#

so how do i fix it?

formal basin
turbid condor
#

Idk XD

#

Even I'm suffering from same thing

formal basin
turbid condor
#

Yeah my commands were working fine till earlier today

#

But when i uploaded the new cog it just kept giving me the error

#

Tho sometimes the commands work

#

But mostly they don't work

formal basin
#

oh

minor lodge
#

@turbid condor

reef gazelle
#

Just random.randomchoice(Roles)

minor lodge
#

k

reef gazelle
#

not roles[]

turbid condor
#

Yeah remove the brackets

#

And that Roles too that's outside

minor lodge
turbid condor
#

Remove the Roles before random too

turbid condor
#

Sorry it's random.choice not random.randomchoice

reef gazelle
#

import random ?

turbid condor
#

U have imported random??

#

Cuz now this shouldn't give any errors

sullen trout
#

can someone help me?

turbid condor
#

It's random.choice not randomchoice

#

And check if u have imported random

reef gazelle
#

definitely hasnโ€™t

formal basin
#

yeah prob havent

#

do import random

turbid condor
vocal snow
minor lodge
turbid condor
#

Send the whole code

vocal snow
sullen trout
#

i've just copied a yt tutorial xD

formal basin
vocal snow
#

the full traceback, code, etc

turbid condor
#

And if any error u getting when running the file

vocal snow
#

reset your token

#

do you have import random?

formal basin
#

that isnt your imports

#

the top of your code

reef gazelle
#

@hollow osprey

#

Delete this poor guys message exposing his own token

vocal snow
#

and that command code will not be reachable if it's under client.run

#

it will execute after the bot logs out

reef gazelle
#

ty

turbid condor
#

But still random shouldn't be be an error

#

If he had it imported

reef gazelle
#

Client.run should be at the end

formal basin
#

show your imports aswell\

turbid condor
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

reef gazelle
#

Can you send a full screenshot from line 1 to where gamble is or paste it in that^

turbid condor
#

Paste the code in above link

#

And share the the link after saving the file

minor lodge
sullen trout
reef gazelle
#

Youโ€™re not importing random

turbid condor
#

There goes the fish

formal basin
reef gazelle
#

add a line at the top and import random

turbid condor
#

In line 3 put import random

vocal snow
minor lodge
reef gazelle
#

Move client.run to the last line also

sullen trout
turbid condor
#

And copy the client.run to the end of your code

reef gazelle
#

should rename client to bot also imo but u know

#

tomato tomato

vocal snow
turbid condor
formal basin
turbid condor
#

Let him do what he's comfortable with

reef gazelle
#

yeh itโ€™s personal pref

vocal snow
#

especially when someone else is reading the code

turbid condor
#

When we know what the variable is is there still a need to change it?

vocal snow
#

yes

turbid condor
#

Am dead

reef gazelle
#

if weโ€™re being picky iโ€™d change role to selected_role for readability ahaha

#

cause got Roles then role

minor lodge
turbid condor
#

Move it to the last

vocal snow
reef gazelle
#

Place it on the last line at the end of the code

#

client.run :

turbid condor
#

Btw can u give me the pistol u holding??

reef gazelle
#

You reckon u can handle it ?

#

Almost sent hasbulla to the shadow realm with the kickback

turbid condor
#

Welp I'll probably fine just need to be careful not getting my finger prints on it

#

That's a desert eagle I'd say it has good recoil but nothing too much if u can handle g3

reef gazelle
#

if you can write python you can handle the deagle

#

transferable skill

turbid condor
minor lodge
#

did I do something wrong ?

formal basin
turbid condor
#

The same 404?

naive briar
formal basin
turbid condor
naive briar
formal basin
turbid condor
#

I heard something like defer it

naive briar
#

I mean exactly what I said

turbid condor
#

What does that mean?

turbid condor
minor lodge
naive briar
unkempt canyonBOT
#

await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

This is only supported with the following interaction types...
turbid condor
turbid condor
naive briar
#

Yes, you'd get some extra time to respond to the interaction

#

Without using it, you need to respond within 3 seconds

turbid condor
#

Hmm

#

So the defer is same in hybrid command?

naive briar
#

!d discord.ext.commands.Context.defer

unkempt canyonBOT
#

await defer(*, ephemeral=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Defers the interaction based contexts.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

If this isnโ€™t an interaction based context then it does nothing.
naive briar
#

Probably

turbid condor
#

Ok thx

minor lodge
naive briar
#

Isn't that obvious

minor lodge
minor lodge
naive briar
#

The error already did, the user argument is missing

turbid condor
#

U not tagging a member when using command

minor lodge
#

bc i don't want to tag myself

turbid condor
#

U have to tag the person on which u want to run the command

vocal snow
#

oh wait

turbid condor
#

That's for use in embed or message

#

He can fix it by changing the if statement

minor lodge
#

Can I make a button to press instead of a command in discord?

turbid condor
#

!discord.ui.buttons

vocal snow
minor lodge
turbid condor
#

U should first learn how to fix the error in your command

vocal snow
#

ok, and do you know how to use classes?

turbid condor
#

Then move to the buttons

minor lodge
vocal snow
#

you'll need to know those to use rich ui components like buttons

vocal snow
minor lodge
#

k

vocal snow
plucky sun
#

@vocal snow how to make select menus ?

dense coral
dense coral
minor lodge
#

need a little bit of help again

#

damn

#

pls

thin raft
minor lodge
#

a noob

thin raft
#

It is recommended you learn python first before hopping to discordpy

minor lodge
#

ik

#

but I don't really have time rn

#

pls help

thin raft
#

there's everything wrong in that code man

#

try learning python first

minor lodge
north kiln
#

Is this from chatgpt

minor lodge
slate swan
slate swan
#

How to fix this?

#

can someone help?

#
@bot.command()
@commands.has_permissions(ban_Members=True)
async def unban(ctx, user_id: int, *, reason=None):
    try:
        user = await bot.fetch_user(user_id)
        await ctx.guild.unban(user, reason=reason)
        embed = discord.Embed(title="Unban", description=f"{user.name} ({user.id}) has been unbanned.", color=0x00ff00)
        await ctx.send(embed=embed)
    except discord.NotFound:
        embed = discord.Embed(title="Error", description=f"User with ID {user_id} not found.", color=0xff0000)
        await ctx.send(embed=embed)
    except discord.Forbidden:
        embed = discord.Embed(title="Error", description="I do not have permission to unban users.", color=0xff0000)
        await ctx.send(embed=embed)
    except Exception as e:
        embed = discord.Embed(title="Error", description=str(e), color=0xff0000)
        await ctx.send(embed=embed)
shrewd apex
#

have u redefined commands somewhere

#

!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").
vale wing
# slate swan

Ctrl + click the commands and see where it leads you. If that's your own code, rename it to something else, because you redefined what you were not supposed to

reef gazelle
#

How come error isnt being handled in the extension here?

#

Do I need to do it in on_command_error ?

#

Changed it to an error on its own but the error is still printed to console

#

I tried returning the error but still prints

reef gazelle
#

Fixed

#

Was handling this globally

#

async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
raise error

Meant to be return

twilit grotto
#

are you using slashcommands by chance or no

#

then just configure what channel it can be ran in from the integrations tab in server settings

reef gazelle
#

Not getting any embed if its a different response any ideas?

twilit grotto
reef gazelle
#
from datetime import datetime
import discord
from discord.ext import commands
import requests


@commands.command(aliases=["isitdown"])
async def check(ctx, website):
    response = requests.get(f"https://{website}", timeout=5)
    code = response.status_code

    print(code)

    try:
        if code == 200:
            embed = discord.Embed(title="โœ… Success 200", description=f"{website} appears to be up.", color=0x11d61e)
            embed.set_footer(text=f"{datetime.utcnow().strftime('%d-%m-%Y at %H:%M')}")
            await ctx.send(embed=embed)
    except Exception as e:
        embed = discord.Embed(title="๐Ÿ’€ Down", description=f"{website} appears to be down. Code: {code}", color=0xde1032)
        embed.set_footer(text=f"{datetime.utcnow().strftime('%d-%m-%Y at %H:%M')}")
        await ctx.send(embed=embed)


@check.error
async def check_error(ctx, error):
    if isinstance(error, commands.BadArgument):
        embed = discord.Embed(title="โš ๏ธ Whoops..", description=f"Enter a valid URL!", color=0xe0cf48)
        embed.set_footer(text=f"{datetime.utcnow().strftime('%d-%m-%Y at %H:%M')}")
        await ctx.send(embed=embed, delete_after=5)
        await ctx.message.delete(delay=5)
    elif isinstance(error, commands.MissingRequiredArgument):
        embed = discord.Embed(title="โš ๏ธ Whoops..", description=f"Enter a URL!", color=0xe0cf48)
        embed.set_footer(text=f"{datetime.utcnow().strftime('%d-%m-%Y at %H:%M')}")
        await ctx.send(embed=embed, delete_after=5)
        await ctx.message.delete(delay=5)


async def setup(bot):
    bot.add_command(check)
#

If I put like a random address in get nothing presuming cause it doesnt send a response at all

twilit grotto
#
@commands.command(aliases=["isitdown"])
async def check(ctx, website):
    response = requests.get(f"https://{website}", timeout=5)
    code = response.status_code

    print(code)

    if code == 200:
        embed = discord.Embed(title="โœ… Success 200", description=f"{website} appears to be up.", color=0x11d61e)
    else:
        embed = discord.Embed(title="๐Ÿ’€ Down", description=f"{website} appears to be down. Code: {code}", color=0xde1032)
    embed.set_footer(text=f"{datetime.utcnow().strftime('%d-%m-%Y at %H:%M')}")
    await ctx.send(embed=embed)
```try something like this, you were sending the appears to be down embed on Exception which wouldn't be hit because it wouldn't be raising an exception
reef gazelle
#

Working for 404

twilit grotto
#

should work in general :)

reef gazelle
#

Will try it on a random URL that wont exist

#

If you put a random URL nothing happens but dont think thats really worth handling

twilit grotto
#

yeah tbh lmao

reef gazelle
#

Thank you ๐Ÿ™‚

twilit grotto
#

np man

twilit grotto
reef gazelle
#

Thanks just seen I like that didn't know could be done that way will change my other embeds ๐Ÿ˜„

#

niceee

twilit grotto
#

np

twilit grotto
# minor lodge

why are you splitting the user to receive the username? calling user.name returns just the name ๐Ÿ’€

slate swan
#

how to make "!test" it will send an embed??????

smoky sinew
slate swan
#

how

turbid condor
slate swan
turbid condor
#

Then u will need check at the very least on how to get started

#
  1. Before even attempting to create a discord bot, please learn python (?tag lp)
  2. To install discord.py, please run python3 -m pip install discord.py (linux), or py -3 - m pip install discord.py (windows)
    ... a. If you wish to use voice functionality, please use discord.py[voice] instead of discord.py
  3. Take a look at https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py Mess around.
  4. When you start making your bot, use the commands ext: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html
  5. The library documentation is available at https://discordpy.readthedocs.org/en/latest/

If you are migrating from the old version of this library (0.16.XX; async) to version 1.XX.XX please follow the migrating guide http://discordpy.readthedocs.io/en/latest/migrating.html

turbid condor
timber spire
#
from discord.ext import commands, tasks

spam_id = os.environ['spam_id']
user_token = os.environ['user_token']


intervals = [2, 3.2]


@tasks.loop(seconds=random.choice(intervals))

async def spam():
    #for i in intervals:
    # if i < 1.9:
    #  print("โ†’ You can't put less than 1.9s! Your interval was changed temporally to 2s.")
    # intervals = [5]
    channel = client.get_channel(int(spam_id))
    await channel.send(''.join(
        random.sample(['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'], 7) *
        5))


@spam.before_loop
async def before_spam():
    await client.wait_until_ready()


spam.start()


@client.event
async def on_ready():
    print(f'Logged into account: {client.user.name}')

keep_alive.keep_alive()
client.run(f"{user_token}")```
smoky sinew
timber spire
#

inside async?

twilit grotto
#

run the task in on_ready

timber spire
#

how?

twilit grotto
#
import re, os, asyncio, random, string, keep_alive
from discord.ext import commands, tasks

spam_id = os.environ['spam_id']
user_token = os.environ['user_token']


intervals = [2, 3.2]


@tasks.loop(seconds=random.choice(intervals))
async def spam():
    #for i in intervals:
    # if i < 1.9:
    #  print("โ†’ You can't put less than 1.9s! Your interval was changed temporally to 2s.")
    # intervals = [5]
    channel = client.get_channel(int(spam_id))
    await channel.send(''.join(
        random.sample(['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'], 7) *
        5))


@spam.before_loop
async def before_spam():
    await client.wait_until_ready()

@client.event
async def on_ready():
    print(f'Logged into account: {client.user.name}')
    await spam.start()

keep_alive.keep_alive()
client.run(f"{user_token}")