#discord-bots

1 messages · Page 298 of 1

final iron
#

What's the use-case for this?

#

I don't really understand how it could be useful tbh

#

Why would you want the bot token then?

quick brook
#

??????

final iron
#

what

#

So you want to send the message from the bot account that the token is associated with?

quick brook
#

sounds like commands to me

whole ocean
#

i don’t think so, i think he just made a typo lol

quick brook
#

like for example, ?help

#

then what do you want?

#

so basically on_message and just check for hello

turbid condor
#

Then what would a command do?

final iron
#

Then you wouldn't need the bot token, or guild ID

whole ocean
#

he just wants to bot to print it out in the channel when he runs the script

#

i understand it’s not practical either but he’s just learning ofc

final iron
whole ocean
#

you need a bot token for discord

final iron
#

Yes, but you don't need to include it as an arg

turbid condor
whole ocean
#

yep

#

didn’t see that

turbid condor
#

It's only needed in run()

whole ocean
#

don’t forget your .env

slate swan
#

is anyone making discord bots now? 💀

turbid condor
slate swan
turbid condor
#

welp music

slate swan
#

aah right

#

but making bots isn't against tos

#

before there were like 10 people active in this channel

turbid condor
#

a music bot is against yt tos

#

spotify

#

and discord too

slate swan
#

wth

#

discord too

turbid condor
#

yeah

slate swan
#

ig there are all kinds of bots now

#

and everything is just ai now so

turbid condor
#

welp there are loopholes

slate swan
#

ig it wasn't defined

harsh orbit
#

nope

vale wing
#

And promotional campaign

#

I accidentally broke voting rewards and they didn't work for a week so I had to make apology video

glad cradle
#

🥶

topaz steppe
#

how I can change bot name & photo nfrom the project?

rugged shadow
mighty pilot
buoyant quail
#

There are moderation tools by discord, but people still make moderation bots

#

So just always :p

mighty pilot
#

Yea ik, discords mod tools still don't cover as much as some bots

naive briar
#

Like?

turbid condor
hallow kernel
turbid condor
#

Uhh....

#

Cuz they not as popular discord bots?

brazen raft
#

Because this isn't Telegram

#

And that too probably

buoyant quail
#

#whatsapp-bots

#

lol

nova vessel
#

Having issues with my bot not sending a DM and setting the user's nickname, any help would be appreciated, if you need further information, please let me know.

https://pastebin.com/zU3XKUXd

turbid condor
#

Can u tell us the error you are getting

nova vessel
#

I am thinking it something to do with how I am defining the user but I am not to sure.

mighty pilot
# naive briar Like?

well i was going to say invite links but i guess you can do that with keyword matching and regex

naive briar
turbid condor
#

And that's one hella code

#

Oh and one more thing use an async lib for db

#

As a synchronous lib can cause blocking

mighty pilot
#

is it sending the one at the beginning before sending the embed

nova vessel
nova vessel
#

I should've really put in try statements and implemented better error handling, would've made it alot easier but this is more of a side project and just for a bit a fun

slate swan
#

#makeerrorhandlinganorm

nova vessel
mighty pilot
#

can you discord.utils.get a list of roles?

nova vessel
#

I am still learning Python so almost everything I do, I am way out of my depth but I feel it's a lot more fun

nova vessel
turbid condor
nova vessel
mighty pilot
# nova vessel I think so?

i dont think it takes a list object, thats probably why its not assigning any roles, your get is returning None

turbid condor
#

No without try except

nova vessel
turbid condor
#

We are just checking to see till where your code is executed

nova vessel
#

Is there a quick way to do that?

unkempt canyonBOT
#

discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find).

When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.

To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.

If nothing is found that matches the attributes passed, then `None` is returned.

Changed in version 2.0: The `iterable` parameter is now positional-only.

Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable)s...
slate swan
naive briar
#

It takes any iterable, so it can take list objects

slate swan
#

in its most basic form

mighty pilot
#

hmmm ok

nova vessel
naive briar
#

Instead of what?

nova vessel
turbid condor
nova vessel
turbid condor
#

But both are doing samething

naive briar
#

What's the problem with the discord.utils.get? Because I see none

slate swan
nova vessel
turbid condor
mighty pilot
naive briar
naive briar
mighty pilot
#

staff_role = discord.utils.get(user.roles, id=staff_role_id) his staff_role_id is a list

nova vessel
mighty pilot
#

that was my only question about it, i didnt know it took a list

naive briar
#

It can take anything

mighty pilot
#

throw some print() statements around your code and see where it stops

nova vessel
#

Apparently there isn't any exeptions, it ran all of the code.

naive briar
nova vessel
#
async def handle_accept_application(message, user):
    # Check if the user who added the reaction is a staff member
    staff_role_id = [1147834535728402523, 1147834296778887221, 1147834091455139870, 1147991729790779556, 1147991646714208286, 1147990426603749442]  # Replace with the staff role ID
    staff_role = discord.utils.get(user.roles, id=staff_role_id)
    
    if staff_role is None:
        return  # Only staff members can accept applications

    # Get the information from the message's embed
    try:
        embed = message.embeds[0]
        applicant_mention = embed.description.split("\n")[0].split(":")[1].strip()
        division = embed.description.split("\n")[3].split(":")[1].strip()
        applicant_id_match = re.search(r'\d+', applicant_mention)
    except Exception as e:
        print(f"Error: {e}")
    
    # Extract the user ID from the mention
    try:
        if applicant_id_match:
            applicant_id = int(applicant_id_match.group())
        else:
            await user.send("Invalid mention format in the application.")
            return
    except Exception as e:
        print(f"Error: {e}")

    # Update the rank to "Accepted" in the database
    try:
        cursor.execute('''
            UPDATE enlistments
            SET rank = ?
            WHERE user_id = ?
        ''', ("Private", applicant_id))

        conn.commit()
    except Exception as e:
        print(f"Error: {e}")

    # Fetch the applicant's user object
    try:
        applicant = await bot.fetch_user(applicant_id)
    except Exception as e:
        print(f"Error: {e}")
    
    # Get the server (guild) and member objects
    try:
        server_id = 1147831792712306749  # Replace with your server ID
        server = bot.get_guild(server_id)
        member = server.get_member(applicant_id)
    except Exception as e:
        print(f"Error: {e}")

    try:
        if member is not None:
            # Assign roles based on division
            Infantry = discord.utils.get(server.roles, name="Army")
            MilitaryPolice = discord.utils.get(server.roles, name="Military Police")
            Logistics = discord.utils.get(server.roles, name="Logistics")
            V1 = discord.utils.get(server.roles, name="V1 Authorisation")
            if division == str(Infantry):
                await member.add_roles(Infantry)
                await member.add_roles(V1)
            elif division == str(MilitaryPolice):
                await member.add_roles(MilitaryPolice)
                await member.add_roles(V1)
            elif division == str(Logistics):
                await member.add_roles(Logistics)
                await member.add_roles(V1)
    except Exception as e:
        print(f"Error: {e}")

        try:
            if division == "Infantry":
                x = "ARMY"
            elif division == "Military Police":
                x = "MP"
            elif division == "Logistics":
                x = "LOG"
            
            r = "PVT"

            new_nickname = f"{r} | {applicant.name} | {x}"  # Customize the new nickname format
            await member.edit(nick=new_nickname)
        except Exception as e:
            print(f"Error: {e}")

            try:
                await applicant.send("Congratulations! Your application has been accepted. You are now a member of the division.")
            except Exception as e:
                print(f"Error: {e}")
        else:
            try:
                await user.send("Failed to find the applicant in the server. Make sure they are still a member of the server.")
            except Exception as e:
                print(f"Error: {e}")
nova vessel
naive briar
#

Don't you want the role?

#

Because you're not getting one from that

nova vessel
#

Ah

topaz steppe
nova vessel
#

Damn I am struggling

#
    staff_role_id = [1147834535728402523, 1147834296778887221, 1147834091455139870, 1147991729790779556, 1147991646714208286, 1147990426603749442]
    has_staff_role = any(role.id in staff_role_id for role in user.roles)
    
    if has_staff_role is True:
        staff_role_id = discord.utils.get(user.roles, id=staff_role_id)
    elif has_staff_role:
        return

@naive briar This look right?

hallow kernel
topaz steppe
#

.....

hallow kernel
naive briar
topaz steppe
#

bruh

nova vessel
# topaz steppe how I can change bot name & photo nfrom the project?
import discord
from discord.ext import commands

# Initialize the bot
intents = discord.Intents.default()
intents.typing = False
intents.presences = False

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

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')

@bot.command()
async def change_name(ctx, new_name):
    if ctx.author.guild_permissions.manage_guild:  # Check if the user has 'Manage Server' permission
        await bot.user.edit(username=new_name)
        await ctx.send(f'Bot name changed to {new_name}')
    else:
        await ctx.send('You do not have permission to change the bot name.')

bot.run('YOUR_BOT_TOKEN')
``` From ChatGPT4 to change bot name. 

```py
import discord
from discord.ext import commands

# Initialize the bot
intents = discord.Intents.default()
intents.typing = False
intents.presences = False

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

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')

@bot.command()
async def change_avatar(ctx, avatar_url):
    if ctx.author.guild_permissions.manage_guild:  # Check if the user has 'Manage Server' permission
        async with aiohttp.ClientSession() as session:
            async with session.get(avatar_url) as response:
                if response.status == 200:
                    data = await response.read()
                    await bot.user.edit(avatar=data)
                    await ctx.send('Bot avatar changed successfully.')
                else:
                    await ctx.send('Failed to fetch the image. Make sure the URL is valid.')
    else:
        await ctx.send('You do not have permission to change the bot avatar.')

bot.run('YOUR_BOT_TOKEN')
``` From ChatGPT4 on how to change avatar.
unkempt canyonBOT
#

10. Do not copy and paste answers from ChatGPT or similar AI tools.

nova vessel
hallow kernel
#

bot.user.edit whats wrong

mighty pilot
unkempt canyonBOT
#

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

Edits the current profile of the client.

Note

To upload an avatar, a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) must be passed in that represents the image being uploaded. If this is done through a file then the file must be opened via `open('some_filename', 'rb')` and the [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) is given through the use of `fp.read()`.

The only image formats supported for uploading is JPEG and PNG.

Changed in version 2.0: The edit is no longer in-place, instead the newly edited client user is returned...
hallow kernel
#

!d any

unkempt canyonBOT
#
any

any(iterable)```
Return `True` if any element of the *iterable* is true. If the iterable is empty, return `False`. Equivalent to:

```py
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
hallow kernel
#

Chain them with or then

naive briar
#

I don't understand that message one bit

nova vessel
#

Nor do I

#

I am just beginning with Python in the grand scheme of things so this is getting confusing

#

But I am wanting and willing to learn

hallow kernel
#

Why is not it

def any(iterable):
    for element in iterable:
        if element:
            break
    return element
#

Either last or first Boolean True

#

Anywayy

#

Im not helping

nova vessel
#

Right, it seems to have fixed the issue and now for the most part works however, I am getting the error below and for some reason, it keeps saying {x} is undefined when editing the nickname.

2023-09-05 13:24:24 ERROR discord.client Ignoring exception in on_reaction_add
Traceback (most recent call last):
File "C:\Users\kiera\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "c:\Users\kiera\Desktop\CDC Discord Bot\main.py", line 217, in on_reaction_add
await handle_accept_application(reaction.message, user)
File "c:\Users\kiera\Desktop\CDC Discord Bot\main.py", line 332, in handle_accept_application
await message.add_reaction("✅") # Accept
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\kiera\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\message.py", line 1116, in add_reaction
await self._state.http.add_reaction(self.channel.id, self.id, emoji)
File "C:\Users\kiera\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 741, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message

buoyant quail
#
        await message.delete() # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
 
        # Add reaction options for staff to accept or deny the application
        await message.add_reaction("✅")  # Accept
        await message.add_reaction("❌")  # Deny
#

how do you want to add a reaction to deleted message

turbid condor
#

magic?

hallow kernel
turbid condor
#

they are just trying to add reaction to something that doesn't exist

hallow kernel
turbid condor
#

always hated the pointers

hallow kernel
#

Imagine those reaction appear in log of deleted messages?

buoyant quail
#

In the accounts with self bots that save deleted messages

hallow kernel
turbid condor
#

Welp i still hate pointers

#

sometimes u need to * with them sometime not like wth

slate swan
#

i need a very smart and fast individual to help me with finishing a very beneficial discord bot for a big project im working on for a server. i currently have a friend that is very experienced with coding and we have got a good amount of the coding done but i would like to get someone else that can help speed up the process. the bot is meant to track messages and VC hours and convert them into points then have leaderboard ranking system. seperate channels with automatic refreshing embed leaderboards of the top 10 people in the server with the highest points for alltime, monthly, weekly & daily. what has been done so far is the .stats command which is meant to provide basic information on an individuals stats in the server, but we have not been able to fully finish this to begin on the leaderboard coding. i need someone that can help with tracking VC hours (time spent in any voice call) and display that time on the stats command and convert it into points (1 second = 1 point by default, if the user is boosting it is 2x points per second) 1 message in chat = 1 point. (double for boosting) below is a screenshot of the current embed displayed when the command is used. please hit me up if you can work with me, i am willing to provide a big reward on your end considering this will help my new server a lot. i can make huge active servers

#

i also have created all of the embeds that i want to use, including the ones for the leaderboards. just need someone to help with the coding of stuff. if you are able to continue from the current code we have now that would be great

turbid condor
naive briar
#

What?

turbid condor
#

like if bot is checking every second who is active in vc wouldn't that cause ratelimit issues

#

considering it is also counting message sent count and other stuff

naive briar
#

Just don't? You can just use the on voice update events and keep track with a dict or something

turbid condor
#

that it keeps track of total seconds spent in the vc and when user leaves the vc it then allocates the point or allocates em at a fix time like after every hour or day

restive dagger
#

Do non slash commands still work?

#

using discord.ext

slate swan
#

yes

restive dagger
#

ah k

#

but can anyone help me with slash commands in discord.py i dont understand how they work

slate swan
#

examples ^

restive dagger
#

ah k

mighty pilot
supple pagoda
#

vs the other python libraries?

slate swan
mighty pilot
sick birch
mighty pilot
#

Looks like all the examples I learned from lol

sick birch
#

I think it's simply the oldest one with the most people using it

mighty pilot
#

AFAIK they all accomplish the same, just personal preference

slate swan
#

the only reason discord.py is seen as "main" library for discord bots is cause other popular libs are forks of it

unkempt canyonBOT
#

nextcord/__init__.py lines 7 to 8

:copyright: (c) 2015-2021 Rapptz
:copyright: (c) 2021-present Nextcord Developers```
`disnake/__init__.py` line 8
```py
:copyright: (c) 2015-2021 Rapptz, 2021-present Disnake Development```
`discord/__init__.py` line 7
```py
:copyright: (c) 2015-2021 Rapptz & (c) 2021-present Pycord Development```
mighty pilot
velvet compass
#

There isn’t a single programmer alive at this point who isn’t using an ultra-wide monitor. To accommodate these extremely wide monitors, all lines must now be at least 120 characters long, and no longer than 240 characters.

slate swan
#

im also fan of unimport keyword

mighty pilot
#

Running my stuff in a vm so I had that terminal running alongside vscode and retyped it

nova vessel
slate swan
#

Can someone share a simple code for discord bot using cogs in it

buoyant quail
slate swan
buoyant quail
hushed galleon
#

well, they explain cogs and extensions separately which makes it a bit confusing on how they're combined in conventional code

hushed galleon
#

almost bare minimum of cogs+extensions: ```py

cogs/my_cog.py

class MyCog(commands.Cog):
def init(self, bot):
self.bot = bot

async def setup(bot):
await bot.add_cog(MyCog(bot)) py

main.py

bot = commands.Bot(...)

@bot.event
async def setup_hook():
await bot.load_extension("cogs.my_cog")

bot.run(...)```

slate swan
#

in simple terms Cog is a class that is a subclass of commands.Cog class while extension is a file that contains setup function in it

#

I just needed help on how to load up the cogs and stuff some codes doesn't even use the asyncio functionality so it was a bit confusing.

slate swan
#

Extension 'cogs.greetings' raised an error: TypeError: object NoneType can't be used in 'await' expression

#

I'm getting this error now when loading up the bot

buoyant quail
#

You did ```py
await None

somewhere it seems

show code
hushed galleon
#

usually means you forgot to add async in front of def setup():

slate swan
slate swan
buoyant quail
#

it's not here

slate swan
#

it's in the link

buoyant quail
#

The error is inside the cogs.greetings

slate swan
#

i created a folder cogs

buoyant quail
#

what's in that file

slate swan
#

I'll share it wait

#

here

slate swan
#

oh inside the cogs file

#

oh ok thanks

buoyant quail
#

and add_cog should be awaited

slate swan
#

ok brother tysm

tall temple
#

command's not working :/

mighty pilot
#

Did you interaction.response

tall temple
sick birch
buoyant quail
#

Slash commands always should be responded in some way. You didn't respond anything

mighty pilot
#

If you don't respond to an interaction it'll fail. Or you can defer the interaction

buoyant quail
#

Ye, all interactions, not just commands

tall temple
#

like that ? 😅

buoyant quail
#

Maybe
What library is that

tall temple
#

pycord

mighty pilot
#

I'm not familiar with that one

tall temple
#

but as i know it doesn't require any response ://

mighty pilot
#

Interactions require responses

buoyant quail
#

Any interaction reqiures response
Command, button, user command, anything

tall temple
#

ok but how in that case ??

buoyant quail
tall temple
mighty pilot
#

It looks like you're never actually sending the enable/disable for the user to click

buoyant quail
#

Or you send disable and there you don't have some response

tall temple
#

nah i selected enable :/

mighty pilot
#

Oh

tall temple
mighty pilot
#

Oh I see

#

Does it print your dict?

tall temple
mighty pilot
#

Then it's failing somewhere before your print

buoyant quail
#

Check what's inside choice

#
print(type(choice), choice)
tall temple
#

okay okay

#

it doesn't print anything

nova vessel
#

Everything else is fixed however, when it comes to handle_accept_application, the bot doesn't add roles or change their nickname correctly.

https://pastebin.com/3ixbgJyL

buoyant quail
tall temple
buoyant quail
#

Do you have error handlers?
Things like raidmode.error, cog_command_error, on_application_command_error

tall temple
#

nah dude

#

nothing occurs 💀

buoyant quail
#

idk then
pycord dark magic

mighty pilot
#

Take out the "enable/disable" in your discord.Option and go straight to choices

final iron
#

pycords slash command implementation makes me want to burn my computer

mighty pilot
#

It also shows this instead of just ctx
ctx: discord.ApplicationContext

tall temple
#

bruh wtf i removed the choices to make the user able to type but it still require to select a choice

#

i restarted discord but the problem still the same 💀

mighty pilot
#
bot.slash_command(name="animal")
async def animal_command(
  ctx: discord.ApplicationContext,
  animal_type: discord.Option(str, choices=['Marine', 'Land']),
  animal: discord.Option(str, autocomplete=discord.utils.basic_autocomplete(get_animal_types))
):
  await ctx.respond(f'You picked an animal type of `{animal_type}` that led you to pick `{animal}`!')```
#

This is the example from the documents. It should looks similar

buoyant quail
mighty pilot
#

Ah

#

Pycord looks frustrating to me lol

tall temple
#

but i think there is a certain problem because the script is different to what the bot executes idk

mighty pilot
#

Bot only does what you tell it to

tall temple
#

i removed the choices but the bot still give choices

tall temple
#

i'm confused rn

mighty pilot
#

So you changed it to choice : str

tall temple
mighty pilot
#

It's giving you options because options are still there lol if you want to type, make it choice : str

#

Instead of discord.Option(xxxx)

tall temple
#

huh dude i always use this syntax for choices or not and it's working

mighty pilot
#

Or maybe discord.Option(str)? Idk pycord is beyond me. I'm just trying to absorb info from the docs rn

upbeat mason
#
@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name} with the ID of {bot.user.id}')

    presence_list = ["1", "2", "3"]

    async def change_presence():
        while True:
            presence = random.choice(presence_list)
            await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=presence))
            await asyncio.sleep(10)

    bot.loop.create_task(change_presence())
    await bot.change_presence(status=discord.Status.idle)

bot isn't going on idle, any ideas?

buoyant quail
buoyant quail
mighty pilot
#

Idkchu pycord voodoo. I gotta head out anyways

upbeat mason
#

i mean i know its probably cause of the loop but where else can i place it

#

aren't going to make a command for it lol

buoyant quail
#

pass status in the change_presence inside the loop

upbeat mason
#

i just did

#

still doesnt

buoyant quail
#

In one change

#

In first you set status to idle

#

and in second you set it back to online

#

because it's the default one

upbeat mason
#

so i should set it after?

buoyant quail
#

together

#

in one function call

upbeat mason
#

yeah i just did that i gotta wait for bot to update

#

await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=presence), status=discord.Status.idle)

#

still not changing i think

#

nope

buoyant quail
#

should work
did you keep some other change_presence?

upbeat mason
#
@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name} with the ID of {bot.user.id}')

    presence_list = ["ds", "d", "s"]

    async def change_presence():
        while True:
            presence = random.choice(presence_list)
            await bot.change_presence(status=discord.Status.idle)
            await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=presence), status=discord.Status.idle)
            await asyncio.sleep(10)

    bot.loop.create_task(change_presence())
#

thats all i have to do with change presence but i'll check

#

yeah it is

#

oh crap it just changed

#

i guess the one function call did work, just had to wait for it to update

#

only issue is now, if i ever want to change the status in some command for whatever reason i wont really be able to but thanks

mighty pilot
#

You can, just put that code into a command and take some input on what to change it to

upbeat mason
#

true

slate swan
upbeat mason
#

i have

#

bot.loop.create_task(change_presence())

normal harbor
#

ModuleNotFoundError: No module named 'discord'

final iron
#

Are you using a venv?

normal harbor
#

I don't know

final iron
#

Did you create one?

slate swan
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, name=None)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop).
upbeat mason
#

oh alr

clear lark
#

Using discord.py is it possible to have embeds with integrated buttons? Using a server invite as an example, but I'm not trying to mimic its design to be clear, I just want the embed to have the button in the box with it rather than below

clear lark
#

Damn thats unfortunate, thanks for the response heart_02

wicked atlas
#

I can totally imagine the new scams that would pop up if that was possible

final iron
#

fr

#

Does anyone have any examples on how to create dropdown menus?

#

Also, this might be a longshot but does dpy have a converter to convert a countries name to it's flag?

sick birch
#

that is completely out of scope

final iron
#

meh

#

worth a shot

#

would've saved me some work

sick birch
#

true enough

pallid meadow
#

One sec

final iron
#

Will emojis work in embed titles?

pallid meadow
pallid meadow
sick birch
pallid meadow
#

lol nice

final iron
#

now I gotta paginate this embed

mighty pilot
#

Covered modals pretty well imo

#

And yes you can most definitely have emoji in embed titles. Footers don't allow anything fun though

hushed galleon
mighty pilot
final iron
#

How are you going to create a giveaway bot without a database?

mighty pilot
#

Already done

final iron
#

How are you storing the data

hushed galleon
#

i did a similar thing with your guide too when i was writing my quiz system, except i used the message content to present a single question and then gave either a select menu or a modal with a single input to receive the answer

mighty pilot
#

The one I currently have made is just a reaction count, but the updated version will use buttons and store the users in the embed

#

Probably have a dict or something idk. I'll figure it out

final iron
mighty pilot
# final iron What if the code restarts?

Shouldn't randomly restart, but that's why I currently have it set to look at reactions after a timer. And I made a reroll command that will check the message as well

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied timeout to @upbeat mason until <t:1693956098:f> (10 minutes) (reason: newlines spam - sent 101 newlines).

The <@&831776746206265384> have been alerted for review.

upbeat mason
#

trash bot

sick birch
final iron
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

karmic shore
#

Guys on the Internet it tells me I can get a Reaction emoji with reaction.emoji but It keeps saying "tuple has no attribute emoji"

#

On a reacted message

#
reaction, user = await bot.wait_for("reaction_add", check=check)
await ctx.send(reaction)
if str(reaction.emoji) == "➕":
#

Thats when it Just stops and gives me this error

#

(<Reaction emoji='heavy_plus_sign' me=True count=2>, <Member id=1017915595083231283 name='heromaex' global_name='heromaex' bot=False nick=None guild=<Guild id=1148733192510128188 name="heromaex's server" shard_id=0 chunked=True member_count=3>>) Is what it gives me

#

Ok wow now that I have it in plain sight it makes sense

#

Thanks haha, solved it

final iron
#

How do I disable a dropdown menu after a certain amount of time?

#

Or, would it be better just to sleep the command, then remove it entirely

hushed galleon
#

is it based on the view timeout or just an arbitrary time?

#

if its the former, you can store your message/interaction in the view and edit it during on_timeout()

final iron
#

I don't want the resource use I guess

#

How long is the timeout?

hushed galleon
#

its however long you want it to be

final iron
#

Also, how would I update the embed when the user selects an option in the dropdown?

#

discord.InteractionResponse.edit_message?

hushed galleon
#

yup

final iron
#

Alright

#

In the callback, how do I see which option was pressed?

hushed galleon
#

the Select.values attribute will give you a list of the option values chosen

final iron
#

I see that

#

Also, one of the options should edit the embed back to it's original state, how would I get the original message?

#

Should I take it as a value in the __init__, and pass it when I initialize the class in the command

#

Or is there a method/attr that returns the original message

hushed galleon
#

passing the embed at the start sounds reasonable

shrewd apex
#

u can get the interaction response but if it has been edited it wont give the original

final iron
#

Yeah I'll just pass it then

shrewd apex
#

u can store the original message as an attribute

hushed galleon
#

^ though dpy doesnt really document which message objects are cached (which will change with edit events)

zinc mist
#

@hushed galleon have a favor to ask real quick if you wanna check your dm

hushed galleon
#

err id rather just answer questions here

zinc mist
#

yea i get that, i honestly just dont know wtf im doing and theres passwords and information stuff in my code and im pingponging between the code and chatgpt to try to fix it, im just trying to figure out why its not posting to discord

#

i can tell you rate limits, webhooks, and proxies are fine. and any ai is like no youre good should be posting

final iron
# hushed galleon passing the embed at the start sounds reasonable

This seem reasonable enough?

class ShippingLineDropdown(discord.ui.Select):
    def __init__(self, sorted_lines: dict[str, list[float, float]], original_embed: discord.Embed) -> None:
        self.original_embed = original_embed
        options = [discord.SelectOption(label="All Lines")]
        for value in sorted_lines.keys():
            options.append(discord.SelectOption(label=value))
        super().__init__(placeholder="Select a shipping line for more information", options=options)

    async def callback(self, interaction: discord.Interaction) -> None:
        if self.values[0] == "All Lines":
            await interaction.response.edit_message(embed=self.original_embed)
        else:
            await interaction.response.send_message(f"Placeholder")
#

dis be pissing me off fr

#

My whole code is kinda cursed

#

Before I release for beta testing I'm going to move everything into cogs and utils files

#

Everything is in 1 file rn

hushed galleon
gray junco
#

How do i do options on slash command discordpy? Can someone show me an example

quick brook
wispy pasture
unkempt canyonBOT
#
Not in my house!

No documentation found for the requested symbol.

shrewd apex
#

!pypi reactionmenu

unkempt canyonBOT
#

A library to create a discord.py 2.0+ paginator. Supports pagination with buttons, reactions, and category selection using selects.

wispy pasture
#

😮

shrewd apex
#

@wispy pasture ^^

wispy pasture
#

thanks

wispy pasture
quick brook
#

yep

shrewd apex
#

discord-ext-menus u can use it

quick brook
shrewd apex
#

i just make my own

quick brook
#

works with buttons as well. although you just have to create a paginator view

wispy pasture
shrewd apex
#

i have my view subclassed

quick brook
shrewd apex
#

for a bunch of custom utilities

quick brook
#

i've been meaning to track down the owner of the pypi package (i did) and don't know much info about him

#

danny probably knows more

shrewd apex
#

oof i am really hungry 10 more mins for class to get over 😔

quick brook
#

anyways you'll have to install from git

wispy pasture
#

oh alright

#

thanks for the help

quick brook
#

np

quick brook
#

Danny's account should be Rapptz

#

Rexum leads to an old friend of Danny

shrewd apex
#

ok yeah

quartz viper
#

Hi, for a few days now I've been getting this error even though I haven't changed my code. Do you know why?

discord.app_commands.errors.CommandInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
buoyant quail
#

For example if you are trying to respond to interaction when it's already expired

async def foo(interaction):
    await asyncio.sleep(5)
    await interaction.response.send_message('123')

would give this error

#

show code

wispy pasture
#

when the button works is getting this normal?

turbid condor
#

try defering it

quartz viper
#
@app_commands.command(name="minecraft",description="Choose a minecraft server to manage") 
    async def minecraftserver(self, interaction : discord.Integration):
    [code but no discord interaction]
    await interaction.response.send_message(embed=embed, view=view) #crash here
    ...
turbid condor
buoyant quail
mighty pilot
buoyant quail
#

: discord.Integration ducky_sus
it's Interaction btw

quartz viper
mighty pilot
#

Because that's not an interaction response

#

That's sending a seperate message into the same channel as interaction

turbid condor
#

as cereal said

#

thats the case

mighty pilot
#

You could either move the response earlier or defer it and send it later, it'll just say the bot is thinking for a second before sending the response

#

!d discord.InteractionResponse.defer

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
#

after this you will need to use followup to send the embed

quartz viper
#

Okay, so I use defer and followup instead and it works but I don't understand why it stopped working when it used to work so well.

buoyant quail
#

You have some code that works different time depending on situation
For example sending requests

quartz viper
#

yes, ty

wispy pasture
cyan jolt
#

How do i make a working slash command in discord.py? i found online on "Stack Overflow" a way but it didnt work, can someone help?

plucky sun
#

My bot command doesn't want to work, this is what comes out:

discord.ext.commands.errors.CommandNotFound: command "generate_licanse" is not found```

And I'm typing the command correctly.
#

My code is:

    characters = string.ascii_letters + string.digits
    key = ''.join(random.choice(characters) for _ in range(32))
    return key

# Функция за запазване на ключа в базата данни
def save_license_key(key):
    conn = sqlite3.connect(db_file)
    cursor = conn.cursor()
    cursor.execute("INSERT INTO licenses (key) VALUES (?)", (key,))
    conn.commit()
    conn.close()

# Команда за бота
@bot.command()
async def generate_license(ctx, number: int, role: discord.Role):
    if number <= 0:
        await ctx.send("Моля, въведете валиден брой ключове (положително число).")
        return

    for _ in range(number):
        key = generate_license_key()
        save_license_key(key)
        await ctx.send(f"Създаден лицензен ключ: `{key}` за роля {role.mention}.")```
buoyant quail
#

You have generate_license but you are trying to call generate_licanse

#

And I'm typing the command correctly.
no?

turbid condor
#

Here u go this contains almost all info u need regarding app_commands(slash commands)

cyan jolt
#

i did it, i am the best developer in the world

gray junco
#

Can someone send me a example of using autocomplete in discordpy please i didnt learn nothing from the doc

buoyant quail
#

interaction.message exists only if interaction was got from message, for example dropdown or button.
so in slash command it is None

buoyant quail
#

!d discord.app_commands.autocomplete

unkempt canyonBOT
#

@discord.app_commands.autocomplete(**parameters)```
Associates the given parameters with the given autocomplete callback.

Autocomplete is only supported on types that have [`str`](https://docs.python.org/3/library/stdtypes.html#str), [`int`](https://docs.python.org/3/library/functions.html#int), or [`float`](https://docs.python.org/3/library/functions.html#float) values.

[`Checks`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check) are supported, however they must be attached to the autocomplete callback in order to work. Checks attached to the command are ignored when invoking the autocomplete callback.

For more information, see the [`Command.autocomplete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command.autocomplete) documentation.

Warning

The choices returned from this coroutine are suggestions. The user may ignore them and input their own value...
gray junco
#

Oh ok but i dont understand that explanation

buoyant quail
#

?

turbid condor
#

I find use Enums easier

buoyant quail
#

i don't see something about them in dpy docs

#

how are they used?

#

i guess you are talking about choices

#

because it'd be strange to do something dynamic with enums

turbid condor
#

Aren't they pretty similar to auto complete

buoyant quail
#

autocomplete can change to anything while you are typing the value

#

and choices are always the same

turbid condor
#

Hmm i see

#

I thought they had same functionality

#

I might need to experiment with them later to get a better understanding

final iron
#

current is the current string the user typed in

#

The function then loops over fruits, and if current is in fruit it returns a value

wispy pasture
#

so this is my code:
https://srcb.in/XrYfydEjM4

and i need to either differ the interaction response or just respond to it... but for some reason i cant figure out how

naive briar
#

You don't know how to respond to an interaction?

final iron
#

What was wrong with the answer you were given

wispy pasture
buoyant quail
#

also why are you getting member by string instead of just getting the member?
if you typehint it as Member library will do the work for you

naive briar
#

About what?

#

!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.
buoyant quail
#
member: discord.Member

and you will get a Member object or NotFound error

final iron
buoyant quail
#
  • in slash command you will get a list of members to select or something like that
wispy pasture
#

ie.... okay yeah thats a approach...

gray junco
#

Does someone know how to do this

buoyant quail
#

defer the interaction with thinking=True

#

!d discord.InteractionResponse.defer

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...
buoyant quail
#

!d discord.Interaction.edit_original_response

unkempt canyonBOT
#

await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the original interaction response message.

This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit) in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.
final iron
#

It’s been like that for a while

final iron
buoyant quail
#

For editing response - sure

final iron
#

Cool, that solves my problem then

slate swan
#

python

mighty pilot
#

Lots of questions about deferring today

sullen plaza
#

Is their any way to upload file to discord bot model?

next heath
#

Hi Can somone help me whit gettign server

@client.command()
@commands.has_any_role("Manager", "Admin som fan", "Mod som tusan")
async def ban(ctx, member : discord.Member, *, reason=None):
    if member is None:
        return await ctx.send("The provided member could not be found or you forgot to provide one.")
        
    if reason is None:
        return await ctx.send("Please provide a reason to ban this user.")

    else:
        server = client.get_guild(id=1148073800374693908)
        
        channel = server.get_channel(id=1149013490523189359)
        
        await ctx.message.delete()
        await member.send(f"{member.mention} You got a Band for **{reason}**. by {ctx.author} in **Rash**")

        embed=discord.Embed(title="Ban", description="Member Banned", color=0xff0000)
        embed.set_thumbnail(url=member.avatar_url)
        embed.add_field(name="User", value=f"{member.mention}", inline=False)
        embed.add_field(name="User id", value=f"{member.id}", inline=False)
        embed.add_field(name="Reason", value=f"{reason}", inline=False)
        embed.add_field(name="Author", Value=f"{ctx.author.mention}")
        await channel.send(embed=embed)
        await member.ban(reason=reason)
shrewd fjord
slate swan
#

!d discord.ext.commands.has_any_role

unkempt canyonBOT
#

@discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return `True`.

Similar to [`has_role()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_role), the names or IDs passed in must be exact.

This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole) if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage) if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).

Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole) or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage) instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure)
restive dagger
#

my discord bot gives error at : in this line invalid syntax
if i add @client.event,
everything looks properly indented

if __name__ == "__main__":

quick brook
#

What you haven't completed the if statement

#

Also

restive dagger
#

It is

quick brook
#

!paste

restive dagger
#

Completed

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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

quick brook
restive dagger
slate swan
#

indentation doesnt look proper

restive dagger
#

k

slate swan
#

most time you use 4 spaces

#

but on the last line you use 1?

restive dagger
#

ah k in my editor is hard to see unless pasted

slate swan
#

what editor is that then

quick brook
#

Idk what editor it is bc it should have been throwing warnings about it

buoyant quail
#

The problem is not indentation though

slate swan
#

and not gonna lie looks like you are missing few intermediate topics like OOP and decorators

buoyant quail
#

Line 38 unclosed

#

And @client.commands wrong decorator. It's not even decorator

quick brook
#

@commands.commands

slate swan
#

cause you have random lines like py member = discord.Member or ```py
@client.commands

#

so i suggest looking up Python OOP learning it then coming back to this project

#

also prolly worth changing text editor too

glad cradle
slate swan
buoyant quail
#

Feature request:
Make any code work as programmer wants to

restive dagger
buoyant quail
restive dagger
buoyant quail
#

What's the new error
It would fix at least the syntaxerror

restive dagger
#

no wait i tested it wrong line 38 was the problem

nova vessel
#

Getting this error: 'NoneType' object has no attribute 'id'

It is orginating in the bot command: manage inside of the transfer option.

https://pastebin.com/5ykS7Fvk

unkempt canyonBOT
#

@slate swan :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     None.id
004 | AttributeError: 'NoneType' object has no attribute 'id'
slate swan
#

you didnt provide full traceback so i cant tell you on what line it happens but somewhere in your code you are trying to access id on None

quick brook
#

Just use asqlite or aiosqlite

nova vessel
#

No idea how to use them, what is the difference.

slate swan
unkempt canyonBOT
#
NEGATORY.

No documentation found for the requested symbol.

slate swan
#

!pypi aiosqlite

unkempt canyonBOT
nova vessel
nova vessel
slate swan
nova vessel
#

Okay, I will get that for you

#
Traceback (most recent call last):
  File "C:\Users\kiera\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "c:\Users\kiera\Desktop\CDC Discord Bot\CDC-Discord-Bot\main.py", line 505, in manage
    await userMsg.remove_roles(currentDivision)
  File "C:\Users\kiera\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\member.py", line 1096, in remove_roles
    await req(guild_id, user_id, role.id, reason=reason)
                                 ^^^^^^^
AttributeError: 'NoneType' object has no attribute 'id'

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

Traceback (most recent call last):
  File "C:\Users\kiera\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\kiera\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\kiera\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'

It wil be somewhere around those lines as I removed the try statement.

slate swan
#

yeah so

#

this line currentDivision = discord.utils.get(server.roles, name=currentDivisionProcess) returned None (didnt find the role)

#

and then else you passed it to .remove_roles() method

#

it tried accessing .id attribute and failed cause its None

nova vessel
#

Ah, okay

#

I’m not sure why that is

slate swan
#

also i see you are repeating code a bit here

nova vessel
slate swan
#

lines 481 - 492

nova vessel
#

Just getting the hang of everything still

#

What’s the best way to implement error handling and logging?

slate swan
#

just to give you example how to shorten code ```py
if rAB == "Private":
rAB = "PVT"
elif rAB == "Private First Class":
rAB = "PFC"
elif rAB == "Lance Corporal":
rAB = "LCPL"
elif rAB == "Corporal":
rAB = "CPL"
elif rAB == "Sergeant":
rAB = "SGT"
elif rAB == "Company Sergeant Major":
rAB = "CSGT"
else:
await ctx.author.send("Rank cannot be defined.")
rAB = "OPEN"



can be shorten to this ```py
mapping = {"Private": "PVT", "Private First Class": "PFC", ...}

rAB = mapping.get(rAB)

if not rAB:
    await ctx.author.send("Rank cannot be defined.")
    rAB = "OPEN"
#

i guess its easier to expand it further on 👍

nova vessel
smoky patrol
#

someone in here knows much stuff about discord.py and discord rate limits for fetching users

#

Im fetching every user id excluded its a dm autopinger

smoky patrol
#

A dm autopinger if a keyword is found

quick brook
#

You should not make fetch user requests, but instead use the cache

quick brook
smoky patrol
#

But only to dm the users that have the keyword set I don’t know how to explain

quick brook
#

Just why

smoky patrol
#

It’s a project

#

No scam btw haha

quick brook
#

Tbh that type of stuff is extremely annoying. All bots that just dm and auto ping with no actual purpose are just annoying

quick brook
smoky patrol
#

No

quick brook
#

And it sounds like a scam

smoky patrol
#

The user can set there own keywords

#

You don’t understand it I think

quick brook
#

Anyways just use the get_user coros. They always look up the cache, which prevents rate limiting

smoky patrol
#

I get no response if I’m using that

#

I already tried

slate swan
quick brook
#

Then probably methods

quick brook
smoky patrol
#

💀

#

WTF

#

Why is it sus

mighty pilot
#

Sus because you're getting rate limited fetching users

smoky patrol
#

Yeah I’m fetching 20 users

#

Cause 20 users have the keyword set

mighty pilot
#

I assume you have their ID stored why not just ping them in a channel

#

<@USERID>

smoky patrol
#

That would be too easy

#

Want it to be special

#

But discord is trolling

slate swan
#

It does the exact same thing though

#

If you are only needing to ping them and you have the user ID, no need to get/fetch the user object

mighty pilot
#

If someone uses @ everyone but don't have permissions to ping everyone, would a bot detect it as a ping for moderation purposes?

hushed galleon
mighty pilot
#

Interesting

#

Just saw a raid attempt that wasn't stopped because either their bot didn't detect it or they just don't have anything set up

mighty pilot
#

Can I disable a button based on a custom ID or something?

#

Trying to set up tic tac toe in discord buttons. Opponent is a minimax, maximin, or random AI algorithm. I can return which space it's selecting but I want to be able to disable that button

slate swan
#

then just filter to ur liking

mighty pilot
#

Right now it's set such that I click button 1, sends that position to the ai, ai selects button 5, returns the number 5, and I'd like to disable button 5 before updating the view

sick birch
mighty pilot
#

Am I just going to have to do if x == 5: self.btn5.disabled = True or is there an easier way

#

Unless I can call a button from a coro?

#

I guess it doesn't matter I'd still have to check what number it selects wutpika5

#

Can't just insert the number into self.btnX.disabled

final iron
#

How should I go about disabling a select menu after a certain amount of time?

main holly
#

wait how do i make the / commands sync again

quick brook
#

arg?

#

Here is a short example of how to use discord.py's slash commands as well as general information on them:

https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f

This currently covers free commands and groups at the Bot level, as well as within Cog classes.
It also includes information and gotchas relating to syncing and whatnot.

NOTE: This will be migrating to https://about.abstractumbra.dev/ as soon as I can be bothered to finish it.

quick brook
#

np

#

you can only respond to an interaction once

#

via await interaction.edit_original_response()

#

you effectively have it twice in your code

mighty pilot
#

Disregard, view children is the answer to all my problems.

vale wing
buoyant quail
#

or ```py
getattr(self, f"btn{X}")

mighty pilot
sharp whale
#

how do we send a local image as a embed thumbnail? in discord.py*

sharp whale
#

I tried this:

embed = discord.Embed(title="Item Info",
                              description=f"Query: {item_name}",
                              color=discord.Color.green())
        
        embed.add_field(name="Name", value=Item_Name)
        embed.add_field(name="Display_Name", value=display_name)
        embed.add_field(name="StackSize", value=stackSize)
        file = discord.File(f"data/item/{Item_Name}.png")
        embed.set_thumbnail(url=f"attachment:data/item/{Item_Name}.png")```
buoyant quail
#

attachment://
you are missing //

#
  • don't forget to send the file
sharp whale
#

:o

sharp whale
buoyant quail
#

because how will discord know what is that attachment if it doesn't exist in discord

sharp whale
#
embed = discord.Embed(title="Item Info",
                              description=f"Query: {item_name}",
                              color=discord.Color.green())
        
        embed.add_field(name="Name", value=Item_Name, inline=False)
        embed.add_field(name="Display_Name", value=display_name, inline=False)
        embed.add_field(name="StackSize", value=stackSize, inline=False)
        file = discord.File(f"data/item/{Item_Name}.png")
        embed.set_thumbnail(url=f"attachment://data/item/{Item_Name}.png")
        
        
        await interaction.response.send_message(file=file, embed=embed)``` its not giving any errors but it doesn't show up on the thumbnail
sharp whale
#

it just sends the image there

buoyant quail
#

Set the filename as the docs says
I am not sure if it gives the same name as filename

#
    Item_Name = "background"
    embed = discord.Embed(title="Item Info", color=discord.Color.green())
    embed.add_field(name="Name", value=Item_Name, inline=False)
    file = discord.File(f"{Item_Name}.jpg", filename="image.jpg")
    embed.set_thumbnail(url=f"attachment://image.jpg")
    await interaction.response.send_message(file=file, embed=embed)
tepid dagger
#

do slash commands have a default help command like command prefix

sharp whale
buoyant quail
sharp whale
#

as it already shows every commands in the command list

buoyant quail
sharp whale
tepid dagger
sharp whale
#

because my image is very small

buoyant quail
naive briar
#

There's no limit as far as I'm concerned

tepid dagger
sharp whale
tepid dagger
#

how

turbid condor
sharp whale
naive briar
#

!d discord.app_commands.CommandTree.walk_commands

unkempt canyonBOT
turbid condor
#

As far as i know when we upload an image it gets compressed(unless we do open in browser) so i think that might apply to thumbnail too

sharp whale
#

it sends it as a file attachment and not in thumbnail

tepid dagger
#

are you sending it as a thumbnail?

sharp whale
#

yes

tepid dagger
#

did you try set_image

sharp whale
#

no

#

i don't want to set it to image

naive briar
sharp whale
# naive briar Show your code
embed = discord.Embed(title="Item Info",
                                    description=f"Query: {item_name}",
                                    color=discord.Color.green())

            embed.add_field(name="Name", value=Item_Name, inline=False)
            embed.add_field(name="Display Name", value=display_name, inline=False)
            embed.add_field(name="Stack Size", value=stackSize, inline=False)
            file = discord.File(f"data/item/{Item_Name}.png", filename="image.png")
            embed.set_thumbnail(url=f"attachment://data/item/{Item_Name}.png")
            await interaction.response.send_message(file=file, embed=embed)```
turbid condor
tepid dagger
#

don't send file idk im guessing

#

just the embed

naive briar
#

Keep just the image's name and extension

sharp whale
#
embed.set_thumbnail(url=f"attachment://image.png")```
like this?
turbid condor
#

Yeah try this

naive briar
#

Yes

sharp whale
#

works 👍

#

can we resize

turbid condor
#

Nope

sharp whale
#

the attachment

#

oka

tepid dagger
#

but that's a lot of work]

turbid condor
#

It might be possible in future updates

naive briar
#

Why would it be

tepid dagger
turbid condor
#

Tho u can resize the image using other lib like Pillow and then send it but that might cause a bit of a delay

tepid dagger
#

its faster to just save it and crop it urself i think

turbid condor
#

But I'm talking if u want to retain the original file

buoyant quail
tepid dagger
#

for commands in walk_commands():
NameError: name 'walk_commands' is not defined

naive briar
#

It's a method

tepid dagger
#

client.walk_commands?

#

command_tree.walk_commands

naive briar
tepid dagger
#

ok

buoyant quail
#

||he will try to use it on just class now||

tepid dagger
#

so like

and then tree.walk_commands
naive briar
#

If you define a new command tree that has no commands attached to it, no

tepid dagger
#

thats how i defined my tree

buoyant quail
#

then yes

tepid dagger
#

so the tree has all the commands

#

so it'll just loop through them

sharp whale
#

bot.tree.walk_commands

sharp whale
buoyant quail
#

he is using just client

sharp whale
#

oh

buoyant quail
#

you can still get them from sync, but it's harder to save them

tepid dagger
buoyant quail
#

why not to just get the commands when you need instead of making a global variable with them

tepid dagger
#

does the just mean anything

wispy pasture
#

this is my code:

pinned_messages = {}

@bot.event
async def on_message(message):
    if message.pinned:
        pinned_messages[message.channel.id] = message

@bot.event
async def on_message_delete(message):
    if message.id in pinned_messages:
        log_channel = bot.get_channel(COMMAND_LOG_CHANNEL_ID)
        if log_channel:
            current_date = datetime.datetime.now().strftime("%A, %B %d, %Y")
            embed = discord.Embed(
                title="Message Unpinned",
                description=f"A pinned message in {message.channel.mention} was deleted by {message.author.mention}.",
                color=discord.Color.red()
            )
            embed.set_footer(text=current_date)
            await log_channel.send(embed=embed)

@bot.event
async def on_guild_channel_pins_update(channel, last_pin):
    if last_pin:
        if channel.id in pinned_messages and pinned_messages[channel.id].id != last_pin.id:
            log_channel = bot.get_channel(COMMAND_LOG_CHANNEL_ID)
            if log_channel:
                current_date = datetime.datetime.now().strftime("%A, %B %d, %Y")
                embed = discord.Embed(
                    title="Message Unpinned",
                    description=f"A pinned message in {channel.mention} was manually unpinned by {last_pin.author.mention}.",
                    color=discord.Color.red()
                )
                embed.set_footer(text=current_date)
                await log_channel.send(embed=embed)

            pinned_messages[channel.id] = last_pin

but when i pin or unpin a message it is not logging anything....

buoyant quail
#

Bot is subclass of client and has some added functionality like pre made slash commands tree and prefix commands

sharp whale
#

vitness, is that a husky in your pfp

tepid dagger
#

is one better than the other

naive briar
#

!d discord.on_guild_channel_pins_update

unkempt canyonBOT
#

discord.on_guild_channel_pins_update(channel, last_pin)```
Called whenever a message is pinned or unpinned from a guild channel.

This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds) to be enabled.
buoyant quail
naive briar
sharp whale
wispy pasture
buoyant quail
#

I believe your pinned_messages is always empty (because when message is sent it is not pinned)

#

Also it's weird that your keys in pinned_messages are channel ids and then you are checking if message id is inside there

tepid dagger
# naive briar

how do you get the name of the command

    await interaction.followup.send(command.name)
```i did this but it didn't work, because of

**unknown webhook **
what's that mean
#

and how do i fix it

wispy pasture
tepid dagger
#

should i not use followup

buoyant quail
tepid dagger
#

oh

#

so interaction.response

#

then interaction.followup

buoyant quail
#

ye

#

actually most libraries implement methods that send response if it was not sent and otherwise send followup.. but it seems discord.py doesn't have such as always

tepid dagger
#

so you have to create a separate case for followup messages and the response

#

?

buoyant quail
#

yes
or you can make your own send that will check and choose the needed one

#

!d discord.InteractionResponse.is_done

like

async def my_send(interaction):
    if interaction.response.is_done():
        interaction.followup.send
    else:
        interaction.response.send_message
unkempt canyonBOT
#

is_done()```
[`bool`](https://docs.python.org/3/library/functions.html#bool): Indicates whether an interaction response has been done before.

An interaction can only be responded to once.
tepid dagger
#

is it because if you run a /command it'll give the response in the same "message" instead of like !command where it'll send the response as a separate message

buoyant quail
#

ye

#

that's how discord made that

final iron
tepid dagger
#

true

next heath
#

Hi can some one help me to make this unban command but its uset in a diffrent server

@client.command()
async def unban(ctx, Userid:discord.User, *, reason=None):
    await ctx.message.delete()
    server = client.get_guild(1148073800374693908)
    await server.guild.unban(Userid, reason=reason)
    
    await Userid.send(f"Memmber got Unbanned **User**: {Userid.mention} **UserId**: {Userid} **Reason**: {reason} unbanned by: {ctx.author.mention}")
    await Userid.send("You got unband on Rash Join her -------------------")
slate swan
#

Does anyone know any free websites where I can host my discord bot?

jolly swallow
#

Hello, I was updating a open-sourced discord bot, It asked me to code the intents but as soon I coded the intents, this error is what I got after debugging. Thank you in advance.

unkempt canyonBOT
#
Discord Bot Hosting

Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.

See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.

You may also use #965291480992321536 to discuss different discord bot hosting options.

jolly swallow
turbid condor
#

welp the error says it all

#

read last line of error

jolly swallow
turbid condor
#

the first error says there is no loop that is currently running

#

and second says that the loop should be awaited

slate swan
naive briar
#

If you're not using discord.py or other (if any) forks that have asynchronous extension and cog loading, you'd want to start the tasks in on_ready or similar events

glad cradle
#

the on_ready event could get called multiple times during the Bot life cycle so it would be better to start tasks in the setup_hook or in other functions where you're sure that gets called only once

jolly swallow
naive briar
#

I don't know much, but I don't think must forks have setup_hook

#

You can just check if the on_ready has been called once anyway

glad cradle
#

calling your custom function in the start function and then doing await super().start()

naive briar
#

If not, just use the on_ready ducky_drawing

meager rock
#

it's a cog so using cog_load to start the task and cog_unload to stop it is also an option

naive briar
#

Forgot those exist ducky_sus

quick brook
#

This is why you shouldn't be using the forks to begin with

#

Dpy already implements all of the latest features, and in pycord's case, you will have to rewrite your bot anyways, so why not migrate it back to dpy v2

crude sparrow
#

When I run the mute command, the bot is supposed to give the user the role that is saved on the db but when I run the code, everything looks like being good but no roles are given to the user

#
    await ctx.bot.rest.add_role_to_member(user=ctx.author, guild=ctx.guild_id, role=mute_role_id)
    await ctx.respond(f"Muted {ctx.options.user.mention}.", flags=hikari.MessageFlag.EPHEMERAL)
    await ctx.bot.rest.create_message(log_channel_id, embed=mute_embed)
buoyant quail
#

hikari pixels_snek_2

quick brook
#

hikari's design decisions are quite questionable

meager rock
meager rock
meager rock
#

also guild user and role (in order) are not kwargs, so there's no need to provide them like that

#
ctx.bot.rest.add_role_to_member(ctx.guild_id, ctx.author.id, mute_role_id) ``` is enough for the callable
hasty coral
#

Making a command that sends information about a specified crypto currency.
The code was working fine until my editor crashed and now i keep getting the same response.

Code

@bot.tree.command(name='crypto', description='Crypto Currency Information')
@app_commands.describe(coin = 'coin')
async def crypto(ctx:discord.Interaction, coin: str):
    # Define the CoinPaprika API URL
    url = f'https://api.coinpaprika.com/v1/tickers/{coin.lower()}'
    
    try:
        # Fetch data from the CoinPaprika API
        response = requests.get(url)
        data = response.json()

        # Check if the response contains data for the specified cryptocurrency
        if 'error' not in data:
            coin_name = data['name']
            coin_symbol = data['symbol']
            price_usd = data['quotes']['USD']['price']
            market_cap = data['quotes']['USD']['market_cap']
            volume_24h = data['quotes']['USD']['volume_24h']
            change_24h = data['quotes']['USD']['percent_change_24h']

            # Create an embed to format and display the data
            embed = discord.Embed(title=f"{coin_name} ({coin_symbol.upper()})", description=f"Price p\Unit: ${price_usd:.2f}\nMarket Cap: ${market_cap:,.0f}\n24h Volume: ${volume_24h:,.0f}\nP/L (Last 24h): {change_24h:.2f}%", color=discord.Color.brand_red())
            embed.set_thumbnail(url=f'https://static.coinpaprika.com/coin/{coin.lower()}/logo.png')
            embed.set_footer(text=f'Requested ~ {formatted_datetime}')

            # Send the embed as a message
            await ctx.response.send_message(embed=embed)
        else:
            await ctx.response.send_message(f"No data found for {coin.upper()}. Make sure your format is correct and that the coin exists.\nExample: `btc-bitcoin`")
    except Exception as e:
        await ctx.response.send_message(f"An error occurred: {str(e)}")

Error response

Traceback (most recent call last):
  File "C:\Users\jackf\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 197, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Users\jackf\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "c:\Users\jackf\.vscode\extensions\ms-python.python-2023.14.0\pythonFiles\lib\python\debugpy\__main__.py", line 39, in <module>
    cli.main()
  File "c:\Users\jackf\.vscode\extensions\ms-python.python-2023.14.0\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 430, in main
    run()
  File "c:\Users\jackf\.vscode\extensions\ms-python.python-2023.14.0\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 284, in run_file
    runpy.run_path(target, run_name="__main__")
  File "c:\Users\jackf\.vscode\extensions\ms-python.python-2023.14.0\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_runpy.py", line 320, in run_path
    code, fname = _get_code_from_file(run_name, path_name)
  File "c:\Users\jackf\.vscode\extensions\ms-python.python-2023.14.0\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_runpy.py", line 294, in _get_code_from_file
    code = compile(f.read(), fname, 'exec')
  File "C:\Users\jackf\Documents\Crypto Bot\main.py", line 49
    embed = discord.Embed(title=f"{coin_name} ({coin_symbol.upper()})", description=f"Price p\Unit: ${price_usd:.2f}\nMarket Cap: ${market_cap:,.0f}\n24h Volume: ${volume_24h:,.0f}\nP/L (Last 24h): {change_24h:.2f}%", color=discord.Color.brand_red())
                                                                                                                                                                                                                
        ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 7-8: truncated \UXXXXXXXX escape
#

(The arrow '^' is meant to be pointing at the comma before color)

glad cradle
#

if you put it like that, forks have many things that d.py doesn't have

#

just because "i don't feel like the library should implement this"

buoyant quail
unkempt canyonBOT
#

@buoyant quail :x: Your 3.11 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     "\U"
003 |         ^
004 | SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \UXXXXXXXX escape
buoyant quail
#

You meant \n there maybe

humble lily
#

Any solution?

buoyant quail
#

What library is that?

#

If it's pycord, then you probably broken you installation. Uninstall all other libraries you have and install it again
If not, then there actually is no such attribute in all other forks as i remember

slate swan
humble lily
#

@buoyant quail @slate swan

slate swan
buoyant quail
# humble lily How do I solve it

If it's pycord - install it again. If not, Bot is located in discord.ext.commands and not in just discord. Use the correct one

slate swan
buoyant quail
#

You did it somehow already

#

pip install -U py-cord

#

maybe you would need to pip uninstall discord.py or anything else you have that uses name discord

slate swan
#

run this script

#

then run this commands

#
pip uninstall discord.py
pip install -U py-cord```
slate swan
humble lily
#

Ig

slate swan
humble lily
slate swan
humble lily
#

How do I solve that

buoyant quail
humble lily
#

I am new to this, sorry

slate swan
#

discord bot is not a good project to learn python it requires many intermediate topics like OOP, decorators and async/await syntax knowledge so i advice you to learn basics before coming back to it

humble lily
#

I kind of know about the stuff

#

How to code the bot

#

Just getting stuck on this shit

slate swan
#

so you know such topics but you dont know how to install packages?

humble lily
#

Correct..

slate swan
#

nor you know how to change discord.Bot to discord.ext.commands.Bot?

buoyant quail
#

lol

humble lily
#

nor?

slate swan
# humble lily nor?

used before the second or further of two or more alternatives (the first being introduced by a negative such as ‘neither’ or ‘not’) to indicate that they are each untrue or each do not happen.
"they were neither cheap nor convenient"
2.
used to introduce a further negative statement.
"‘I don't see how.’ ‘Nor do I.’"

humble lily
#

discord mods

humble lily
humble lily
buoyant quail
#

that's all that you needed to change

slate swan
buoyant quail
#

to fix the first error

#

you will get intents error then

#

or maybe something else before it

humble lily
slate swan
#

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

humble lily
fast robin
#

i need help

#

My name is Benjamin

#

:v, i speak spanish

slate swan
fast robin
#

i need help

slate swan
fast robin
#

I want to send a file through the discord API using the requests module
files = {'file': ('data.txt', <_io.BufferedReader name='\files\1140884481671188581\data.txt'>)}
requests.post(url, headers=headers, json=data, files=files)
print(files)
print(response.json())

But when I make the http request I get this
{'message': 'The request body contains invalid JSON.', 'code': 50109}

buoyant quail
#
  1. What's inside data variable
  2. Why files has a file object representation in it? That line will give just syntax error
#

!e

files = {'file': ('data.txt', <_io.BufferedReader name='\files\1140884481671188581\data.txt'>)}
fast robin
#

The problem is not with the json, the json is valid and if I don't send the file there is no problem

unkempt canyonBOT
#

@buoyant quail :x: Your 3.11 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     files = {'file': ('data.txt', <_io.BufferedReader name='\files\1140884481671188581\data.txt'>)}
003 |                                   ^
004 | SyntaxError: invalid syntax
fast robin
slate swan
fast robin
#

def send_private_message(user_id, message='', embeds=[], files=[]):
url = f"https://discord.com/api/v9/users/@me/channels"
data = {
"recipient_id": user_id
}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
channel_id = response.json().get("id")
url = f"https://discord.com/api/v9/channels/{channel_id}/messages"
data = {
"content":message,
"embeds": embeds,
}
response = requests.post(url, headers=headers, json=data, files=files)
print(files)
print(response.json())

with open(base_path + "data.txt", 'rb') as file:
files = {'file': ('data.txt', file)}
send_private_message(user_id=user_id, files=files)

slate swan
#

!e ```py
import io

io.BytesIO()
print(io.BytesIO())

unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.

<_io.BytesIO object at 0x7fd04f6b4c70>
slate swan
#

or maybe no

fast robin
#

That's the code

buoyant quail
slate swan
buoyant quail
#

It's giving me a different error hmm

{'message': 'Invalid Form Body', 'code': 50035, 'errors': {'channel_id': {'_errors': [{'code': 'NUMBER_TYPE_COERCE', 'message': 'Value "{channel_id}" is not snowflake.'}]}}}
#

i see, because it was replaced with %7B

#

works fine by me

fast robin
#

what

buoyant quail
#

bot sent me the file

fast robin
#

mmm

buoyant quail
#
import requests

headers = {
    "Authorization": "Bot ..."
}

def send_private_message(user_id, message='', embeds=[], files=[]):
    url = f"https://discord.com/api/v9/users/@me/channels"
    data = {
        "recipient_id": user_id
    }
    response = requests.post(url, headers=headers, json=data)
    if response.status_code == 200:
        channel_id = response.json().get("id")
        url = f"https://discord.com/api/v9/channels/{channel_id}/messages"
        data = {
            "content": message,
            "embeds": embeds,
        }
        response = requests.post(url, headers=headers, json=data, files=files)
        print(files)
        print(response.json())

user_id = 656919778572632094
with open("in.txt", 'rb') as file:
    files = {'file': ('in.txt', file)}
    send_private_message(user_id=user_id, files=files)

fast robin
#

What could be the problem?

buoyant quail
#

I don't really know
I don't use raw requests for discord api and i am not getting an error here

fast robin
#

okok

buoyant quail
#

Are you running just that code or you have something more? Maybe something else is breaking it, try just that part

mighty pilot
#

Had something weird going on earlier. Was messing with some test code on my lunch break and it kept labeling my buttons as a view object, I threw in a print statement and it fixed it. Pop1munch

desert kiln
#

I need a list of all discord.Embed colors

#

I don't know what the valid colours are, I just need a green, or light green

thin raft
desert kiln
thin raft
#

im not a hex master

#

youd need to search what is the hex value for it

desert kiln
#

color=discord.Color()

thin raft
#

color = 0x00FF00

desert kiln
#

can I use that for embed colors?

thin raft
#

yeah

#

!d discord.Colour

unkempt canyonBOT
#

class discord.Colour(value)```
Represents a Discord role colour. This class is similar to a (red, green, blue) [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple).

There is an alias for this called Color...
desert kiln
#

I've been using the color names 💀

#

not hex value

thin raft
#

the method returns the hex value

undone aurora
#

import discord

intents = discord.Intents.default()
intents.typing = True
intents.presences = True

intents.members = True

client = discord.Client(intents=intents)

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

@client.event
async def on_message(message):
if message.author == client.user:
return

if message.content.startswith('hi '):
    await message.channel.send('Hello!')

client.run('token')

my friend made this code, but its not working and im not sure why its not working either
its supposed to respond with Hello! when you say hi

unkempt canyonBOT
#
Did you mean ...

» message-content-intent
» mcintent
» message_content
» message_content_intent

thin raft
#

!mcintent

unkempt canyonBOT
#
Discord Message Content Intent

The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."

The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.

Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:

intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents

bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor

For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.

undone aurora
desert kiln
#

Try This @undone aurora

import discord
from discord.ext import commands 
import asyncio
from discord import Activity, ActivityType
from datetime import datetime
from discord import ActionRow, Button, ButtonStyle
import random


intents = discord.Intents.all()

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


# ========== On Ready / Status ==========

@bot.event
async def on_ready():
        print(f'[+] Logged Into {bot.user}')
        await update_status()
async def update_status():
    while not bot.is_closed():
        server_count = len(bot.guilds)
        await bot.change_presence(activity=discord.Streaming(name="Under Maintainance", url='https://twitch.tv/Vaypt_rz'))
        await asyncio.sleep(1)
  
    print(f'[+] Logged Into {bot.user.name}')
bot.start_time = datetime.now()

bot.run('TOKEN HERE')```
#

this is the code for running a bot, with no commands

desert kiln
#

@merry cliff why skull?

undone aurora
thin raft
merry cliff
#

isnt there an unspoken rule not to do API stuff in on_ready?

thin raft
#

not an unspoken rule

desert kiln
thin raft
#

you do not do api stuff there, use setup_hook

undone aurora
merry cliff
#

yeah that

thin raft
#

!d discord.on_ready

unkempt canyonBOT
#

discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.guilds) and co. are filled up.

Warning

This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
desert kiln
#

I don't get what I did wrong in my code

merry cliff
#

basically on_ready might be rapidly called in quick succession so there is a chance for the bot to be rate limited from API spam

#

it is recommended to instead use setup_hook

desert kiln
#

Idk how to use that 💀

#

and that explains why I get API limited as soon as my bot is ran

merry cliff
#

while not bot.is_closed(): might be the reason

thin raft
#

use tasks

merry cliff
#

instead of having it in on_ready that looks like something a task loop would do

desert kiln
#

that's effort

#

plus I ran it again and it didn't rate limit

merry cliff
#

💀

desert kiln
#

buttt, I do need help with bot = autoShardedBot

final iron
desert kiln
#

im gonna be making my bot public for larger server count

#

and I figured it out

final iron
#

It's really not important until you're in like 150+ servers

desert kiln
#

I know

#

I'm just pre making the code now, so I don't have to make it later

final iron
#

The documentation is pretty straight forward

desert kiln
#

let me do what I want jeez

final iron
#

?

#

You're asking for help

desert kiln
#

in fine now

final iron
#

Alr, so you understand how to use AutoShardedBot

#

Cool

desert kiln
#

yes

#

👍🏻

final iron
#

It's just a subclass of Bot

#

Not sure how you didn't understand before lmao

merry cliff
#

isn't it literally the same usage as Bot

final iron
#

!d discord.ext.commands.AutoShardedBot

unkempt canyonBOT
#

class discord.ext.commands.AutoShardedBot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
This is similar to [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot) except that it is inherited from [`discord.AutoShardedClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AutoShardedClient) instead.

async with x Asynchronously initialises the bot and automatically cleans.

New in version 2.0.
desert kiln
#
bot = commands.AutoShardedBot(command_prefix='!', intents=intents, shard_count=5)