#discord-bots

1 messages · Page 177 of 1

potent spear
#

that's not what the link says

#

that's not your issue

#

your issue is that the bot is not registering your command

#

have you first of all verified that the cog is loaded?

#

you should surely add that on top of on_message as a decorator though, to state that it's an event~listener

onyx rapids
potent spear
#

you haven't shown your main file either

onyx rapids
potent spear
potent spear
shrewd apex
onyx rapids
shrewd apex
#

bro ur code

#

where u got it from

potent spear
shrewd apex
#

i need to wash my eyes ;-; so many no no mistakes

#

a while loop in on_ready 💀

potent spear
shrewd apex
#

also process commands goes after your on_message stuff also use a setup hook for db

potent spear
#

you have to add that process command shit at the END of your event

#

also, I highly suggest you to add an else statement in that on_command_error event which also prints other errors

onyx rapids
shrewd apex
#

wait did u use binary | or in the if statement

#

damn

onyx rapids
shrewd apex
#

code definitely from chatgpt 💀

errant pecan
potent spear
shrewd apex
#

why message and client

potent spear
shrewd apex
#

guys atleast make an effort read the docs or atleast watch a old yt tutorial even those are better than current code rn here Cry

potent spear
#

meaning that on_ready shouldn't be the event used to do things like "oh, let me set things up before my bot actually comes ready"

errant pecan
shrewd apex
potent spear
errant pecan
shrewd apex
#

imagine actually trying to learn before attempting

potent spear
#

so the best option here would be "send me the link of the docs" and then say what you don't understand about it instead of just avoiding it in general

#

NO

#

it will not work because it first of all is missing a decorator
and second of all, your main file has some errors

errant pecan
#

I already understood about the main file. I'm asking if I fix everything basically will it work or not

#

it is not necessary to make a reference to the main file in each message

potent spear
errant pecan
potent spear
#

I answered your question

errant pecan
#

because of the abbreviation in the form of "ofc". I have a bad translation of your message

errant pecan
#

@potent spear can I make the command in another file ?

potent spear
errant pecan
potent spear
errant pecan
#

@potent spear in my cog. 4 files with commands

#

did you mean to add this?
await bot.process_commands(message)

#

@potent spear

potent spear
potent spear
errant pecan
potent spear
shrewd apex
#

damn new respect for sniper so much patience awee

slate swan
#

Hello everyone

potent spear
shrewd apex
#

👋

slate swan
#

when im use bot.send_message i have this error

ERROR discord.client Ignoring exception in on_message_delete
Traceback (most recent call last):
File "C:\Users\Saúl\PycharmProjects\pythonDiscordmusic\venv\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Saúl\PycharmProjects\pythonDiscordmusic\main.py", line 28, in on_message_delete
await bot.send_message(message.channel, "{}:{}".format(autor, contenido))
AttributeError: 'Bot' object has no attribute 'send_message'

#

do you know why i have this?

shrewd apex
shrewd apex
#

saw that catpeek

slate swan
shrewd apex
#

👍

slate swan
#

Thanks

potent spear
slate swan
shrewd apex
#

reminds me the discord.py github repo has a few examples u can refer them

#

basic stuff is still present there

shut elk
#

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

shut elk
#

https://paste.pythondiscord.com/tizuxahefe
Can someone tell me why EVERY command is not existent (not showing and not in integrations), despite there being 0 errors?

The only exception is the command, create_verify_button, and I would like to know why this is the case, what makes it still work and functional. All the existent buttons still work, but just all other commands than the create verify button do not show up / used

full lily
#

has anyone successfully added a rich presence with an image to their bot?

#

I see how to do it with just the text, but adding a caption thing makes the image go away

#

now im starting to doubt i had the image in the first place, i cant seem to get it back

white citrus
#

Can someone help me with the tracker network api

#

I don't understand how to use the connection

hushed galleon
full lily
#

thanks for your response

shut elk
#

https://paste.pythondiscord.com/tizuxahefe
Can someone tell me why EVERY command is not existent (not showing and not in integrations), despite there being 0 errors?

The only exception is the command, create_verify_button, and I would like to know why this is the case, what makes it still work and functional. All the existent buttons still work, but just all other commands than the create verify button do not show up / used

hushed galleon
potent spear
#

there might not be an "error" in your IDE, but there are definitely some bad implementations
most obvious one being the on_ready spaghetti

hushed galleon
#

even better is syncing via command, but their on_ready is sufficient - boolean flags are preventing it from re-syncing twice and change_presence is acceptable since re-identifying resets your activity iirc

shut elk
hushed galleon
#

no its totally correct from what i see

hushed galleon
#

could be as barebones as writing an on_message and looking for a message from you saying to sync (it'll still receive message content if you DM / ping the bot)

#

or writing a slash command in your development guild and getting it synced once beforehand

#

either way the advantage is you only sync whenever you need to, rather than every time you restart the bot - there's a daily ratelimit on syncing so you'd want to avoid hitting it

cloud dawn
#

I think syncing always on the setup_hook in the dev guild and make a sync guild for global syncs.

hushed galleon
cloud dawn
#

Thus not including guild syncs.

potent spear
#

sidenote: put the presence in the constructor of your bot 😉

hushed galleon
potent spear
#

changing 200 commands a day would be optimistic

shut elk
potent spear
shut elk
#

Ok

#

Thank you :)

potent spear
cloud dawn
#

It's also time to learn OOP.

hushed galleon
shut elk
#

Ik it I’m just doin this before that cuz I don’t know the name of those are for discord I just started discord coding

#

Probably will revamp code when I have time

potent spear
shut elk
#

But it was a rushed code for an event

shut elk
#

Rn just trying to fix it

potent spear
cloud dawn
#

It's a global ratelimit not specific.@hushed galleon

shut elk
#

So I have to change the on ready thing and the pre scenes

shut elk
hushed galleon
potent spear
shut elk
potent spear
cloud dawn
cloud dawn
potent spear
#

anyways, I'd prevent that by just having a dev bot lol

hushed galleon
shut elk
#

So the problem is not based on the commands functions nothing like that just on the starting of the bot and the server limit that is causing it

cloud dawn
potent spear
hushed galleon
unkempt canyonBOT
#

Hey @thin trout!

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

potent spear
slate swan
#

Hey I am having a error

#
@bot.command(name='play', help='Plays a song from YouTube.')
async def play(ctx, url: str):
    # Make sure the user is in a voice channel
    if not ctx.author.voice:
        await ctx.send("You must be in a voice channel to play music!")
        return

    # Join the user's voice channel
    channel = ctx.author.voice.channel
    await channel.connect()

    # Play the YouTube video
    ydl_opts = {
        'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
    }
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        info = ydl.extract_info(url, download=False)
        song = info.get('url', None)
        if song:
            player = nextcord.PCMVolumeTransformer(nextcord.FFmpegAudio(url))
            player.volume = 0.5
            voice_client.play(player, after=lambda e: print(f'Player error: {e}') if e else None)

    # Send a message when the song starts playing
    await ctx.send(f'Now playing: {info["title"]}')
thin trout
slate swan
unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
potent spear
# slate swan

you might wanna type that AttributeError out in Google, you'll find something

potent spear
hushed galleon
potent spear
#

yt tutorial alert
or maybe an outdated copy pasted gh repo

shut elk
#

Thanks guys for all ur help!

thin trout
#

Someone know if there’s a complete guide or tutorial on how to create a complete music bot (private usage) that can support YouTube with link and song name and also Spotify with playlist link

naive briar
#

!ytdl

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
bold surge
#

Im trying to implement autocomplete into my slash commands but whenever its in a cog the slash command seems to stop registering

potent spear
bold surge
#

I cant seem to find anything in the docs and the same format works in main.py but not in a cog

#
    @nextcord.slash_command(name="driver", description="Get information about a current Formula One Driver")
    async def driver(self, interaction: nextcord.Interaction, driver_arg: str = SlashOption(description="The driver to get information about", required=True)):
        drivers = await handler.get_drivers(int(await handler.get_current_year())-1, 1)
        for driver in drivers:
            full_name = " ".join([driver["givenName"], driver["familyName"]])
            if str(full_name).lower() == str(driver_arg).lower():
                picture = await handler.get_driver_picture(full_name)
                code = str(driver["code"])
                embed = nextcord.Embed(title=f"{full_name} [{code}]")
                embed.add_field(name="Nationality", value=str(driver["nationality"]))
                embed.add_field(name="Date Of Birth", value=str(driver["dateOfBirth"]))
                embed.add_field(name="Number", value=str(driver["permanentNumber"]))
                embed.set_thumbnail(url=picture)
                await interaction.response.send_message(embed=embed)

    @driver.on_autocomplete("driver_arg")
    async def driver(self, interaction: nextcord.Interaction, driver_arg: str):
        drivers = await drivers()
        if not driver_arg:
            return await interaction.response.send_autocomplete(drivers)
        get_closest_driver = [driver for driver in drivers if driver.lower().startswith(driver_arg.lower())]
        await interaction.response.send_autocomplete(get_closest_driver)    

heres my code if anyone notices anything that i dont

junior terrace
#

on message blocks the entire code from working discord.py

#

why

#

found

#

it is about await bot.process_commands(message)

sick birch
fading marlin
#

client ;-;

sick birch
#

The unfortunate fact of the matter is people still call their bots client

fading marlin
#

😔

rare echo
sick birch
thin trout
#

i got a problem with viewing the class in the interaction.send

#
class ticket_launcher(discord.ui.View):
        def __init__(self) -> None:
            super().__init__(timeout= None)

        @discord.ui.button(label= "Create a Ticket", style=discord.ButtonStyle.blurple, custom_id= "ticket_button")
        async def ticket(self, interaction: discord.Interaction, button: discord.ui.Button):
            ticket = utils.get(interaction.guild.text_channels, name = f"ticket{interaction.user.name}-{interaction.user.discriminator}")
            if ticket is not None: await interaction.response.send_message(f"You already have a ticket open at {ticket.mention}", ephemeral= True)
            else:
                overwrites = {
                    interaction.guild.default_role: discord.PermissionOverwrite(view_channel = False),
                    interaction.user: discord.PermissionOverwrite(view_channel = True, send_messages = True, attach_files = True, embed_links = True),
                    interaction.guild.me: discord.PermissionOverwrite(view_channel = True, send_messages = True, read_message_history = True)
                }
                channel = await interaction.guild.create_text_channel(name = f"ticket-{interaction.user.name}-{interaction.user.discriminator}", overwrites= overwrites, reason=f"Ticket for {interaction.user}")
                await channel.send(f"{interaction.user.mention} created a ticket!")
                await interaction.response.send_message(f"I've opened a ticket for you at {channel.mention}", ephemeral= True)

        @app_commands.command(name="ticketing", description="Launch the ticket system")
        async def ticketing(self, ctx, interaction: discord.Interaction):
            embed = discord.Embed(title= "Ticket tool", color=discord.Color.red())
            await interaction.channel.send(embed=embed, view=ticket_launcher())
            await interaction.response.send_message("Ticketing system launched", ephemeral= True)```
fading marlin
#

An application command inside a view? pithink

thin trout
#

it was outside before

#

i just tried to put it inside the view because it wasn't working

fading marlin
#

That will make it "less work" lol

thin trout
#

sorry i didn't know

fading marlin
#

Did you sync your commands?

thin trout
#

yes

#

@commands.command()
async def sync(self, ctx) -> None:
fmt = await ctx.bot.tree.sync(guild=ctx.guild)
await ctx.send(f"Synced {len(fmt)} commands.")

sick birch
#

Did you run it?

thin trout
#

can't run the ticket code

sick birch
#

Also I'm pretty sure you need copy_global_to

thin trout
#

it gaves me error

sick birch
#

It would be helpful to know the error

thin trout
fading marlin
#

You're syncing to a guild, yet your command is global

sick birch
#

It copies your global commands to a guild

#
tree = ctx.bot.tree
tree.copy_global_to(guild=ctx.guild)
await tree.sync(guild=ctx.guild)
thin trout
sick birch
#

You just edit your existing code to reflect that

#

It's not meant to be a copy paste solution :P

#

You just need to .copy_global_to before you .sync

fading marlin
#

Or don't sync to a guild, or add a guild to your app commands

shut elk
#

Is there a decorator for this to call, like has_permissions? I tried commands.has_permissions but it did not work

#

its slash commands

fading marlin
#

!d discord.app_commands.default_permissions I'd suggest using this instead of a check

unkempt canyonBOT
#

@discord.app_commands.default_permissions(**perms)```
A decorator that sets the default permissions needed to execute this command.

When this decorator is used, by default users must have these permissions to execute the command. However, an administrator can change the permissions needed to execute this command using the official client. Therefore, this only serves as a hint.

Setting an empty permissions field, including via calling this with no arguments, will disallow anyone except server administrators from using the command in a guild.

This is sent to Discord server side, and is not a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check"). Therefore, error handlers are not called.

Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
shut elk
#

@potent spear I changed the syncing, but the bot still goes down after 2 hours

#

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

shut elk
potent spear
shut elk
potent spear
shut elk
#

I mean the only thing is this

#

But then that's the server's thing

potent spear
#

mhm, I'm not really using v2 stuff, so I can't really tell

naive briar
#

!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.
shut elk
#

or is it not

potent spear
potent spear
# shut elk alr

so you're telling me your slash commands work for 2 hours, and then some disappear?

shut elk
#

i'd have to run it again for it to start working again for 2 hours, etc

#

but all buttons still work and that one cmd works too, create_verify_button

potent spear
shut elk
#

ye

#

if i didnt have it, the slash cmds wouldnt work at all right

#

I can try re-inviting it?

potent spear
shut elk
#

alr

naive briar
shut elk
#

"await tree.sync"?

unkempt canyonBOT
#

examples/app_commands/basic.py lines 22 to 28

# In this basic example, we just synchronize the app commands to one guild.
# Instead of specifying a guild to every command, we copy over our global commands instead.
# By doing so, we don't have to wait up to an hour until they are shown to the end-user.
async def setup_hook(self):
    # This copies the global commands over to your guild.
    self.tree.copy_global_to(guild=MY_GUILD)
    await self.tree.sync(guild=MY_GUILD)```
hushed galleon
#

have you tried making your commands global instead of syncing them to a guild?

potent spear
#

found the issue lol

shut elk
#

ok

potent spear
#

you missed a self.sync.tree(...) in your line 276

#

that's uhm, painful

hushed galleon
#

nah they have the tree in their global scope

#

commands disappearing after some time is really weird

potent spear
#

ah yeah, mb
wouldn't change a thing

shut elk
#

it doesn't show either

potent spear
shut elk
shut elk
slate swan
#

#currency system
connection = sqlite3.connect("currencysystem.db")
cursor = connection.cursor()

#table: balances
cursor.execute("CREATE TABLE IF NOT EXISTS balances (user_id INTEGER PRIMARY KEY, balance INTEGER)")
connection.commit()


cursor.execute('''CREATE TABLE IF NOT EXISTS items
                  (item_name TEXT, price INTEGER)''')
connection.commit()
shut elk
#

should i remove the self.synced thing

slate swan
#
@bot.slash_command(name="buy", description="Buy an Item from the Shop!")
@commands.cooldown(1, 10, commands.BucketType.user)
async def buy(ctx, item:Option(str, "Input the item name you wanted to purchase! (lowercase only)",
                               required=True), quantity: Option(int, "Input the quantity of the item you want to purchase.", required=True)):
    cursor.execute("SELECT price FROM items WHERE item_name=?", (item,))
    result = cursor.fetchone()
    if result:
        item_price = result[0]
        user_id = ctx.author.id
        cursor.execute("SELECT balance FROM balances WHERE user_id=?", (user_id,))
        result = cursor.fetchone()
        if result:
            user_balance = result[0]
            if user_balance >= (item_price * quantity):
                cursor.execute("UPDATE balances SET balance = balance - ? WHERE user_id = ?", ((item_price * quantity), user_id))
                for i in range(quantity):
                    cursor.execute("INSERT INTO inventory (user_id, item_name) VALUES (?, ?)", (user_id, item))
                em = discord.Embed(title="You brought an item!", description=f"Purchase complete! {quantity} x {item} has been added to your inventory! :0")
                em.set_footer(icon_url = ctx.author.avatar, text=f"Invoked by {ctx.author.name}")
                await ctx.respond(embed=em)
                connection.commit()
            else:
                em = discord.Embed(title="You brought an item!", description=f"Insufficient Aww Pika Coins!")
                em.set_footer(icon_url = ctx.author.avatar, text=f"Invoked by {ctx.author.name}")
                await ctx.respond(embed=em)
                await ctx.respond("Oh no...Insufficient Aww Pika Coins!")
#

else:
                em = discord.Embed(title="You brought an item!", description=f"Oh wait...You don't have an account. Please run `/balance` to create an account.")
                em.set_footer(icon_url = ctx.author.avatar, text=f"Invoked by {ctx.author.name}")
                await ctx.respond(embed=em)
    else:
        em = discord.Embed(title="Your brought an item!", description=f"Oh wait...That item doesn't exist")
        em.set_footer(icon_url = ctx.author.avatar, text=f"Invoked by {ctx.author.name}")
        await ctx.respond(embed=em)
shut elk
#

👀

naive briar
#

Not necessary since setup_hook only get called once

slate swan
#
@bot.slash_command(name="inventory", description="Check your inventory!")
@commands.cooldown(1, 20, commands.BucketType.user)
async def inventory(ctx):
    user_id = ctx.author.id
    cursor.execute("SELECT item_name, COUNT(item_name) FROM inventory WHERE user_id = ? GROUP BY item_name", (user_id,))
    result = cursor.fetchall()
    if result:
        items = ""
        for item in result:
            items += f"item name: {item[0]} amount: {item[1]}\n"
        em = discord.Embed(title="Your inventory contains:", description=f"\n{items}")
        em.set_footer(icon_url = ctx.author.avatar, text=f"Invoked by {ctx.author.name}")
        await ctx.send(embed=em)
    else:
        em = discord.Embed(title="Your inventory contains:", description=f"Your inventory is empty.")
        em.set_footer(icon_url = ctx.author.avatar, text=f"Invoked by {ctx.author.name}")
        await ctx.send(embed=em)
hushed galleon
#

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

shut elk
#

so i should change it

potent spear
#

since setup_hook doesn't rerun like on_ready does

hushed galleon
shut elk
naive briar
potent spear
naive briar
#

It's not working doesn't explain anything

naive briar
#

There's literally an example I just sent

shut elk
#

💀

unkempt canyonBOT
#

examples/app_commands/basic.py lines 10 to 20

class MyClient(discord.Client):
    def __init__(self, *, intents: discord.Intents):
        super().__init__(intents=intents)
        # A CommandTree is a special type that holds all the application command
        # state required to make it work. This is a separate class because it
        # allows all the extra state to be opt-in.
        # Whenever you want to work with application commands, your tree is used
        # to store and work with them.
        # Note: When using commands.Bot instead of discord.Client, the bot will
        # maintain its own tree instead.
        self.tree = app_commands.CommandTree(self)```
shut elk
#

currently i have this, so should I be removing line 278 and adding that ?

#

along with the client

naive briar
#

Just click on the example link

#

It literally shows you everything you need to know

shut elk
#

aight

shut elk
#

I'll have to wait like 2 hours for the results, I'll let you know abt it later. Thanks though

fresh fern
#

i need help in my code

torpid hare
#

does anyone know how to set permission for a user

fresh fern
#

yes

#

i know

torpid hare
#

how

#

I did it and it worked and it randomly stopped

fresh fern
#

oh

#

so u r saying that it worked earlier?

torpid hare
#

yes

fresh fern
#

ok

#

send me your full code

#

ill look into it

torpid hare
#

then like 5 to 10m ago it stopped working

torpid hare
#

okay, whats the paste site

fresh fern
#

idk

#

just dm me

torpid hare
#

okay

fresh fern
#

i need help how to reply to a message in discord.py

#

i tried ctx.reply and ctx.respond but it didnt work

#

anyone?

slate swan
#

code (just this section): https://pastebin.com/is6MWXvR
pycord, sqlite3

Only the balance command is working. The database is created. But

cursor.execute('''CREATE TABLE IF NOT EXISTS items
                  (item_name TEXT, price INTEGER)''')
connection.commit()

this second table doesnt create

and the bet, buy and inventory, slash command does not work

slate swan
#

so i could help you better

fresh fern
#

umm ok

#

@client.slash_command(guild_ids=[guild_id], description="Test 1") async def hello(ctx): await ctx.reply("Hello")

slate swan
#

have you specified the guild id?

#

and are you getting any errors in your terminal?

vale wing
#

Imagine replying to slash command

vale wing
slate swan
#

^

fresh fern
#

yes

fresh fern
vale wing
#

Depending on lib it's mostly inter.send or inter.response.send_message

grim oar
loud junco
#

look humanic?

fresh fern
#

what do i do

vale wing
#

You can't "reply" to an interaction

slate swan
#

^

vale wing
#

What lib are you using

fresh fern
loud junco
vale wing
#

That's prefix command then

slate swan
#

you're trying to make the bot reply to an interaction, wouldn;t work just use ctx.send

fresh fern
loud junco
#

ctx.reply

fresh fern
#

like im replying u guys

fresh fern
loud junco
#

💀

#

this is what i found on github

fresh fern
#

the tutorial guy used ctx.respond which is also not working

loud junco
#

try this

fresh fern
#

not worked

loud junco
#

what error are u getting

#

it doesnt work doesnt mean the thing doesnt work

#

maybe other thing is not working

#

like me screwing up my database for one month straight

vale wing
#

@fresh fern you can only reply in prefix command, what you currently have is slash command

loud junco
#

prefix command means
example: m.help
slash commands means
/help

vale wing
#

And in slash command you can only respond to interaction

fresh fern
vale wing
#

There is no message

fresh fern
#

error - Command raised an exception: AttributeError: 'Interaction' object has no attribute 'respond'

fresh fern
#

Discord

loud junco
#

!d discord

vale wing
#

Rename ctx to inter and do inter.response.send_message

fresh fern
#

ok

#

no but im having ctx as a parameter

#

so nothing will happen after changing the name if the parameter

vale wing
#
async def cmd(inter):
    await inter.response.send_message(...)```
#

Spoonfeed intensifies

fresh fern
#

lemme try

loud junco
#

cuz some new concept are hard to understand without examples

fresh fern
slate swan
vale wing
vale wing
vale wing
fresh fern
#

inter thing not worked

fresh fern
#

i guess i have to stay on prefix

vale wing
#

You could just switch to disnake

loud junco
#

and rework on the whole thing

vale wing
#

Cause it's easy for non-advanced users

fresh fern
#

hmm

vale wing
#

Rewriting code is good

loud junco
#

yes

fresh fern
#

yea

loud junco
#

not until u finished 90% of the bot with 35 commands that has a total of 6k lines of code

vale wing
#

Cause you replace constructions you created while you were stupid with new more effecient and elegant stuff

loud junco
#

i mean you are right

#

but if they are all intertwined to one another

#

u get fed up trying to fix one error but ended up creating a whole new one

slate swan
#

I use sub types in this situation for my ide to type hint my code

shrewd apex
#

exenifix prolly just lazy to type

slate swan
#
@bot.slash_command(name="bet", description="Gamble some money!")
@commands.cooldown(1, 20, commands.BucketType.user)
async def bet(ctx, amount:Option(int, "Input the amount you wanna bet.", required=True)):
    balance = handle_balance(ctx.author.id)
    if amount > balance:
        em = discord.Embed(title="Your gambled some money! :0", description=f"Oh wait... You do not have enough money to make that bet.")
        em.set_footer(icon_url = ctx.author.avatar, text=f"Invoked by {ctx.author.name}")
        await ctx.respond(embed=em)
        return
    outcome = random.choice(["True", "False"]) # generate outcome randomly
    if outcome == "True":
        cursor.execute("UPDATE balances SET balance = ? WHERE user_id = ?", (2 * amount, user_id))
        conn.commit()
        em = discord.Embed(title="Your gambled some money! :0", description=f"You won {2 * amount} AwwPika Coins!")
        em.set_footer(icon_url = ctx.author.avatar, text=f"Invoked by {ctx.author.name}")
        await ctx.respond(embed=em)
    if outcome == "False":
        cursor.execute("UPDATE balances SET balance = ? WHERE user_id = ?", (-amount, user_id))
        conn.commit()
        em = discord.Embed(title="Your gambled some money! :0", description=f"You lost {amount} AwwPika Coins!")
        em.set_footer(icon_url = ctx.author.avatar, text=f"Invoked by {ctx.author.name}")
        await ctx.respond(embed=em)

my balance slash command works well.. how come this bet command not work?
if user win they get 2x the amount betted
if user lose they lose all the amount betted

slate swan
#

the database works completed fine... it shows "Application does not respond" when i run the slash command....

naive briar
#

Then you should get an error

#

And use aiosqlite instead of sqlite3

#

!pypi aiosqlite

unkempt canyonBOT
slate swan
slate swan
slate swan
slate swan
# slate swan no...

You're more prone to running into blocking-related issues with the standard sqlite3 library though.

faint merlin
#

Hello, I've faced with one problem. Can somebody help me? The script was created by AI. And it's completely fine just in the last step it crashes, because of stale element. PLEAAAAASElemon_hyperpleased

slate swan
#

Consider aiosqlite or asqlite instead

faint merlin
#

Find the message input field

def new_func(driver):
message_input = driver.find_element('xpath','/html/body/div[1]/div[2]/div/div[1]/div/div[2]/div/div[1]/div/div[2]/div[3]/div[2]/main/form/div/div[1]/div/div[3]/div/div[2]/div')
return message_input

message_input = new_func(driver)
time.sleep(15)

Iterate over the messages

for message in messages[:100]:
# Send the message
message_input.send_keys(message)
time.sleep(7)
message_input.send_keys(Keys.RETURN)
time.sleep(19)
message_enter = driver.find_element('xpath','/html/body/div[1]/div[2]/div/div[1]/div/div[2]/div/div[1]/div/div[2]/div[3]/div/main/form/div/div[2]/div/div[2]/div/div/div/span[1]/span/span')
message_enter.send_keys(Keys.RETURN)
time.sleep(5)
message_input = new_func(driver) # re-find element
# Wait for 120 seconds before sending another message
time.sleep(6)

Close the browser

driver.close()

It doesn't second message after first iteration

naive briar
#

I probably don't have to guess which AI generated this

naive briar
slate swan
faint merlin
slate swan
#

I think the best solution would be to not use an AI to write your bot's code.

faint merlin
#

I am too close to the solution. I changed this little script over 5 hours yersteday

#

And still can't resolve it fully, after first iteration I have this error:
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
(Session info: chrome=109.0.5414.87)

slate swan
slate swan
#

I didn't know that :-)

#

Thanks

vale wing
#
  • idk dpy interaction command-specific type 🤓
#

!d disnake.ApplicationCommandInteraction disnake best lib

unkempt canyonBOT
#

class disnake.ApplicationCommandInteraction```
Represents an interaction with an application command.

Current examples are slash commands, user commands and message commands.

New in version 2.1.
slate swan
#

dpy has only one interaction class and it's discord.Interaction, sucks

cerulean lichen
#

Tried lightsail for the last week, it's functioning really bad 😂
you have any idea why?
it just crashes sometimes and stop working, I have to reboot it from the AWS console

slate swan
#

the table is created successfully and somehow just this single command doesnt work, both balance and buy command works well

slate swan
#

can anyone help me pls? mimu_sob_cry

faint merlin
upbeat otter
faint merlin
upbeat otter
faint merlin
upbeat otter
slate swan
upbeat otter
#

imagine not using hastebin itself

slate swan
#

......

tough lance
#

Hi, best way to debug memory leaks in the discord bot?

unkempt canyonBOT
#

Hey @slate swan!

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

slate swan
slate swan
#

Do I take the cake for least readable discord.py code yet?

stats_embed.add_field(name='Top 5 Text Channels:', value='\n'.join([f'> {ctx.guild.get_channel(entry[0]).mention if ctx.guild.get_channel(entry[0]) else "`Unknown Channel`"}**: {"{:,}".format(entry[1])} Messages**' for entry in sorted_message_count_by_channel[:5]]))
naive briar
#

Use generator expression

slate swan
#

can someone help me make a inventory slash command? with pycord and sqlite3

#

ive been trying for so long... all my balance / buy / currency commands / database all is working... but somehow i just cant find a way to make a inventory command 😐 😭

tough fern
#

hello, how to add options in discord.py slash command?
what i have:

@bot.hybrid_command(name = "Shop", description = "Give your coins in exchange for an item")
async def shop(ctx, type="basic"): #codes for shop```
what i want is like the one shown in pic
unkempt canyonBOT
#

examples/app_commands/transformers.py lines 80 to 87

# In order to support choices, the library has a few ways of doing this.
# The first one is using a typing.Literal for basic choices.

# On Discord, this will show up as two choices, Buy and Sell.
# In the code, you will receive either 'Buy' or 'Sell' as a string.
@client.tree.command()
@app_commands.describe(action='The action to do in the shop', item='The target item')
async def shop(interaction: discord.Interaction, action: Literal['Buy', 'Sell'], item: str):```
naive briar
#

Provide an error then

slate swan
#

Error: "Application does not respond"

slate swan
#

i even tried to put error handling code and it give me nothing...

#

its just this single command of my entire code is not working :/

naive briar
#

Then there's an error

slate swan
#

the whats the error

#

??

naive briar
#

How can anyone tell what's the error if you don't even know it's there

slate swan
#

😭

#

sure

naive briar
#

How come there's no error but it's not working, what could it be? A ghost maybe?

slate swan
#

the buy command works fine

#

it is pycord and sqlite3

#

embed=em works fine

#

check line 64, it works for buy command

naive briar
slate swan
#

wait lemme fix it

#

😅

naive briar
#

And I just said use aiosqlite instead of sqlite3

#

And pycord sucks

slate swan
#

"Application does not respond" when i run /inventory command

#

okie

#

still same error

#

i replaced it to await ctx.reply()

#

i dont think thats the issue

young dagger
#

Is it better to use use asyncio and the aiohttp library instead of requests to reduce the time for a command?

naive briar
young dagger
slate swan
#

async code isn't essentially faster than sync code
but yeah you're on the bright side when using async code in an async environment

slate swan
#

or is it just fire and forget

young dagger
slate swan
#

!d asyncio.gather

unkempt canyonBOT
#

awaitable asyncio.gather(*aws, return_exceptions=False)```
Run [awaitable objects](https://docs.python.org/3/library/asyncio-task.html#asyncio-awaitables) in the *aws* sequence *concurrently*.

If any awaitable in *aws* is a coroutine, it is automatically scheduled as a Task.

If all awaitables are completed successfully, the result is an aggregate list of returned values. The order of result values corresponds to the order of awaitables in *aws*.

If *return\_exceptions* is `False` (default), the first raised exception is immediately propagated to the task that awaits on `gather()`. Other awaitables in the *aws* sequence **won’t be cancelled** and will continue to run.

If *return\_exceptions* is `True`, exceptions are treated the same as successful results, and aggregated in the result list.

If `gather()` is *cancelled*, all submitted awaitables (that have not completed yet) are also *cancelled*.
young dagger
#

Next time you run the command, it should receive new data from the API

gloomy bramble
#

Yo btw guys for some reason on_member_join is not work

import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!')

@bot.event
async def on_ready():
    print(f'{bot.user} has connected to Discord!')


@bot.command()
async def ping(ctx):
    await ctx.send('Pong!')

@bot.event
async def on_member_join(member):
    print('testing')
    welcome_message = discord.Embed(
        title='Welcome to the server!',
        description=f'Hello {member.mention}, we are glad you are here!',
        color=discord.Color.green()
    )
    channel = bot.get_channel(1042913508779634770) # Replace 'id' with the channel ID you want the welcome message to be sent in
    await channel.send(embed=welcome_message)

bot.run('TOKEN') # Replace 'TOKEN' with your bot's token
sick birch
#

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

gloomy bramble
sick birch
#

See how in this codeblock they included intents=intents?

errant pecan
#

please tell me how it is calculated. Well , like how much exp does it take to level up ?
if cur_xp >= round((4 * (cur_lvl ** 3)) / 5):

#

just don't need me to throw documentation with a description for round()

naive briar
errant pecan
naive briar
#

From what

#

Other bots?

errant pecan
#

@naive briar 4 * (cur_lvl ** 3) / 5
that 's how it counts ?

slate swan
#

there's no fixed way, every bot has it's own calculations

errant pecan
#

for example, I want to change it so that 100 messages are needed to get level 1, twice as many for level 2, and so on

slate swan
naive briar
slate swan
#

!e ```py
a = 100
b = 235
c = 1295
print(a//100, b//100, c//100)

unkempt canyonBOT
#

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

1 2 12
errant pecan
#

OMG. I just want to understand how it works, how to understand how much exp is needed for up level. And whether it is possible to change it somehow.

shrewd apex
shut axle
#

Why is the cogs not showing in the help commands and I can't use them as a command?

#main.py
@client.command(hidden=False)
@commands.has_permissions(administrator=True)
async def load(ctx, extension: str = None) -> None:
    """ Loads a cog.
    :param extension: The cog. """

    await ctx.message.delete()
    if not extension:
        return await ctx.send("**Inform the cog!**")
    client.load_extension(f'cogs.{extension}')
    return await ctx.send(f"**{extension} loaded!**", delete_after=3)


@client.command(hidden=False)
@commands.has_permissions(administrator=True)
async def unload(ctx, extension: str = None) -> None:
    """ Unloads a cog.
    :param extension: The cog. """

    await ctx.message.delete()
    if not extension:
        return await ctx.send("**Inform the cog!**")
    client.unload_extension(f'cogs.{extension}')
    return await ctx.send(f"**{extension} unloaded!**", delete_after=3)

@client.command(hidden=False)
@commands.has_permissions(administrator=True)
async def reload(ctx, extension: str = None) -> None:
    """ Reloads a cog.
    :param extension: The cog. """

    await ctx.message.delete()
    if not extension:
        return await ctx.send("**Inform the cog!**")
    client.unload_extension(f'cogs.{extension}')
    client.load_extension(f'cogs.{extension}')
    return await ctx.send(f"**{extension} reloaded!**", delete_after=3)


for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        client.load_extension(f'cogs.{filename[:-3]}')
#information.py
import discord
from discord.ext import commands


class Information(commands.Cog):
    """Information Cog."""

    def __init__(self, client):
        self.client = client

    # Events
    @commands.Cog.listener()
    async def on_ready(self):
        print('information cog is ready!')

    # Commands
    ..............
    

def setup(client):
    client.add_cog(Information(client))
shrewd apex
#

cog load is now async

shut axle
#

What do you mean?

#

!cogs

#

What should I change?

slate swan
errant pecan
#

@shrewd apex there are examples where only normal ones are given, and not as in the documentation ???

slate swan
vale wing
#

Never seen anyone using "subtype" term and I am still unsure what you mean by it

slate swan
#

type hinting is when you call the arg in function

#

IIRC

vale wing
#

Mm where's that info from

vocal snow
#

but not like this

shut axle
#

I heard something about new async load and I didn't understand

#

How can I fix it that it will show on help command and it 'll work?

slate swan
#

yea thats all wrong

young dagger
young dagger
#

Why is the the bot not staying online with the following function?

        time.sleep(5)

schedule.every(3600).seconds.do(update_elo_ratings)

while True:
    schedule.run_pending()
    time.sleep(10)```
#

Is there anything with this function that makes the bot no staying online?

#

It's updating the elo, the only issue is that the bot is not online as it supposed to be.

peak loom
#
Traceback (most recent call last):
  File "main.py", line 77, in <module>
    bot.run(os.getenv('Token'))
  File "/home/runner/juicebot/venv/lib/python3.8/site-packages/discord/client.py", line 828, in run
    asyncio.run(runner())
``` It keeps giving me this error.
vocal snow
#

is that the full traceback you got?

#

why do you need to transfer it?

errant pecan
peak loom
vocal snow
#

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

vocal snow
#

if it's too long

shut axle
#

@vocal snow Can you give me an example of a cog command? pls

vocal snow
#
from discord.ext import commands

class MyCog(commands.Cog):

    @commands.command()
    async def foo(self, ctx):
        ...
shut axle
vocal snow
#

are you getting an error?

shut axle
#

No

#

it is not showing me the command on help cmd and it is not work! @vocal snow

#

None errors

vocal snow
#

which commands is it not showing

#

or is it not showing anyt commands at all

shrewd apex
shrewd apex
vocal snow
#

i even linked migration docs but it seems no use

shrewd apex
#
async def setup(bot):
  await bot.add_cog(Cog(bot))
await bot.load_extension('cogs.Cog')
junior terrace
#

and why client is a problem?

tawny junco
#

Bruh why is discord.ext.commands so weird

shrewd apex
#

coz u can have multiple listeners

#

but a single event

vocal snow
# junior terrace why

because you aren't trying to override the bot's internal on_message event, which is what the event decorator does

vocal snow
junior terrace
#

hm

tawny junco
# vocal snow what's weird?

The arguments passed. You can grab all the arguments and place them in a tuble uses *args but it breaks when you use qoutes in your arguments.

#

See:

discord.ext.commands.errors.UnexpectedQuoteError: Unexpected quote mark, '「', in non-quoted string
#

#

#

These things break it

#

Why does it do this :v

#
@bot.command()
async def translate(ctx, *args):
cold forge
#

how do i make a slash command

vocal snow
vocal snow
cold forge
sick birch
cold forge
vocal snow
peak loom
cold forge
#

oh tysm

peak loom
#

I really want that dev badge.

sick birch
#

Why?

vocal snow
sick birch
#

It's worthless

peak loom
vocal snow
#

you're being ratelimited; you should make sure you don't send make too many API calls at once

peak loom
#

It pings the web server of the bot every 15 minutes but it hasn’t gave me that error until I turn it to 5 minutes.

errant pecan
#
        member = ctx.author if not member else member
        member_id = str(member.id)

        if not member_id in self.users:
            await ctx.send("участник не имеет уровня")
        else:
            embed = discord.Embed(colour=0x2F3136)
            embed.set_author(name="Вы были замучены на сервера")
            embed.set_author(name= f"Уровень - {member}")

            embed.add_field(name= 'Уровень', value= self.users[member_id]["level"])

            embed.add_field(name= 'Опыт', value= self.users[member_id]["exp"])

            await ctx.send(embed=embed)```
how to transfer this information from embed to another file located in cog?
tawny junco
blazing condor
# errant pecan ```py member = ctx.author if not member else member member_id = ...

use the pickle module to save the information to a file, and then use pickle.load() to load the information from the file into another cog or script.


import pickle

# Saving the information to a file
with open('member_info.pickle', 'wb') as handle:
    pickle.dump(self.users[member_id], handle, protocol=pickle.HIGHEST_PROTOCOL)

# Loading the information from the file
with open('member_info.pickle', 'rb') as handle:
    loaded_member_info = pickle.load(handle)
shut axle
errant pecan
blazing condor
#

yes @errant pecan

#
import pickle

# Saving the level to a file
with open('member_level.pickle', 'wb') as handle:
    pickle.dump(self.users[member_id]["level"], handle, protocol=pickle.HIGHEST_PROTOCOL)

# Loading the level from the file
with open('member_level.pickle', 'rb') as handle:
    loaded_member_level = pickle.load(handle)
pearl pollen
#

import pygame

class Player(pygame.sprite.Sprite):
def init(self,width, height, pos_x,pos_y,color):
super().init()
self.image = pygame.Surface(width,height)
self.image.fill(color)
self.rect = self.image.get_rect()

#general setup
pygame.init()

#game screen

screen_width = 640
screen_height = 480
screen = pygame.display.set_mode(screen_width,screen_height)

player = crosshair(50,50,100,100,(255,255,255))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()

pygame.display.flip()
blazing condor
pearl pollen
tawny junco
errant pecan
errant pecan
blazing condor
#

most things are till u learn it really.

#

but once u learn it, it can be very helpful

#

and less complicated

#

just like anything u learn

#

added u so we can chat

errant pecan
#

I tried it and it didn't work out

blazing condor
#

add me real quick

abstract kindle
#

How does this python bot manage subfolders in the cogs folder?

#

I see that it has some folders in the extensions folder, but I can't follow the code enough to find how it loads the sub folders. The closest I can get is self.bot.all_extensions, but that looks external

unkempt canyonBOT
#

pydis_core/utils/_extensions.py line 28

def walk_extensions(module: types.ModuleType) -> frozenset[str]:```
frail notch
#

Hi there, I'm getting a problem with this code... the bot works fine, theres no errors, but it simply stops responding in the discord chat once I untag the part at the bottom... How can I fix this? ```py
@client.event
async def on_message(message):
if message.author == client.user:
return
print(f"Server: {message.guild.name} Channel: {message.channel.name} User: {message.author} : {message.content}")
#Problem is from here onwards
server_id = str(message.guild.id)
channel_id = str(message.channel.id)
user_id = str(message.author.id)
if server_id not in messages:
messages[server_id] = {}
if channel_id not in messages[server_id]:
messages[server_id][channel_id] = {}
if user_id not in messages[server_id][channel_id]:
messages[server_id][channel_id][user_id] = []
messages[server_id][channel_id][user_id].append(message.content)
with open("messages.json", "w") as f:
json.dump(messages, f)

slate swan
#

What is the if statement for a member that has been moved from one voice channel to another?

#

I remember it has to deal with if before.channel == None and after.channel != None: something like this

shut elk
#

@naive briar it doesn’t work

young dagger
#

Can somebody please tell me why the bot never goes online after adding this code?

def update_elo_ratings():
    # Get all the users in the collection
    users = collection.find()
    for user in users:
        summoner_id = user['summoner_id']
        summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
        tier, rank = get_tier_and_rank(summoner_name, summoner_id, RIOT_API_KEY)
        elo_rating = get_elo_rating(summoner_name, summoner_id, RIOT_API_KEY)
        collection.update_one({"summoner_id": summoner_id}, {"$set": {"tier": tier, "rank": rank, "elo_rating": elo_rating}})
        time.sleep(2)

while True:
    update_elo_ratings()
    time.sleep(600)```
#

Should I use the threading library to create a new thread for the while True loop?

unkempt canyonBOT
#

class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.

The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
young dagger
sick birch
#

Yeah, that's what I linked

young dagger
# sick birch Yeah, that's what I linked

You mean like this?

@tasks.loop(minutes=10)
async def update_elo_ratings():
    # Get all the users in the collection
    users = collection.find()
    for user in users:
        summoner_id = user['summoner_id']
        summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
        tier, rank = get_tier_and_rank(summoner_name, summoner_id, RIOT_API_KEY)
        elo_rating = get_elo_rating(summoner_name, summoner_id, RIOT_API_KEY)
        collection.update_one({"summoner_id": summoner_id}, {"$set": {"tier": tier, "rank": rank, "elo_rating": elo_rating}})
        await asyncio.sleep(2)

update_elo_ratings.start()```
#
sys:1: RuntimeWarning: coroutine 'Loop._loop' was never awaited```
sick birch
#

Or is it just free-floating

young dagger
sick birch
#

What's the .create_task doing in there?

young dagger
# sick birch What's the `.create_task` doing in there?

So

@client.event
async def on_ready():
    update_elo_ratings.start()
    # Set the bot's activity
    activity = discord.Activity(name="League of Legends", type=discord.ActivityType.playing)
    await client.change_presence(activity=activity)
    print('Bot is ready!')

@tasks.loop(minutes=10.0)
async def update_elo_ratings():
    # Get all the users in the collection
    users = collection.find()
    for user in users:
        summoner_id = user['summoner_id']
        summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
        tier, rank = get_tier_and_rank(summoner_name, summoner_id, RIOT_API_KEY)
        elo_rating = get_elo_rating(summoner_name, summoner_id, RIOT_API_KEY)
        collection.update_one({"summoner_id": summoner_id}, {"$set": {"tier": tier, "rank": rank, "elo_rating": elo_rating}})
        await asyncio.sleep(2)```
potent spear
#

also, you should start tasks in a setup_hook 🙂
=> on_ready is to be avoided in general

sick birch
#

!d discord.Member.timeout

unkempt canyonBOT
#

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

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.11)").

You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
shut elk
potent spear
shut elk
#

That might be why only that cmd shows up

#

@potent spear do u happen to know anything abt this?

potent spear
shut elk
#

How do i remove view

potent spear
#

Remove the until=
So just …timeout(short_timeout, reason=“yes”)

potent spear
shut elk
#

The view is updated i think, just the instance I meant

#

I only had add view to the create verify button button

#

Before I added more add_view()'s

#

So I was thinking it might have been staggered somehow

young dagger
potent spear
young dagger
potent spear
#

Strange

#

Maybe try member.edit(timed_out_until=…) ?

potent spear
#

Ctrl+f subclassed bot here, you’ll find examples

shut elk
potent spear
#

Check if you’re not accidentally running it in some other task… if you have no idea, just rebooting whatever you’re hosting it on will do, should stop ALL instances

shut elk
potent spear
#

On…

shut elk
#

on the server I use, and when testing I use visual studio code

#

but visual studio code I have ran it even after the update

shut elk
#

it might be runingo on studio code, how would i stop an instance on thre?

young dagger
potent spear
#

Mhm, seems about right. Try and see

young dagger
potent spear
shut elk
potent spear
shut elk
potent spear
#

then a terminal output screen would pop up

#

on the right, you'll see that most likely, a few of these terminals are opened
just close them all with the 🗑️

young dagger
#

Since you told me to use the activity in the constructor of my bot

potent spear
shut elk
#

@potent spear I clicked the trash can thing already since I have not used the visual studios in a long time and it still does not work

young dagger
#

or am I wrong?

naive briar
#

Just test it

potent spear
#

you could even put that on_ready in your subclassed bot if you'd want to... (you don't need that even decorator anymore then)

young dagger
potent spear
shut elk
potent spear
shut elk
#

also if it was the same server that was causing the issue, how come the same server can cause more than one views, like when I use create verify thing I said that it shows 2 embeds and 2 buttons

#

Does that mean views save if on the same server?

potent spear
shut elk
shut elk
potent spear
potent spear
shut elk
#

Yeah but then does that mean the more I run in the future the same problem will arise*

shut elk
potent spear
potent spear
shut elk
#

Ah, I just reinstalled the server and it still shows 2 buttons

shut elk
potent spear
shut elk
shut elk
potent spear
young dagger
# potent spear you could even put that on_ready in your subclassed bot if you'd want to... (you...

The first or second one?

class MyClient(commands.Bot):
    async def setup_hook(self):
        update_elo_ratings.start()
    async def on_ready():
        activity = discord.Activity(name="League of Legends", type=discord.ActivityType.playing)
        await client.change_presence(activity=activity)
    print('Bot is ready!')

client = MyClient(command_prefix=['!', '>'], intents=INTENTS, help_command=None)```

```python
class MyClient(commands.Bot):
    async def setup_hook(self):
        update_elo_ratings.start()
    async def on_ready():
        activity = discord.Activity(name="League of Legends", type=discord.ActivityType.playing)
    print('Bot is ready!')

client = MyClient(command_prefix=['!', '>'], intents=INTENTS, activity=activity, help_command=None)```
shut elk
#

I always run the thing on the hosting server

#

Rarely do on visual code, nothing else

potent spear
potent spear
young dagger
potent spear
# young dagger Can you show me an example please?
class MyClient(commands.Bot):
    async def setup_hook(self):
        update_elo_ratings.start()
    async def on_ready():
      print('Bot is ready!')

activity = discord.Activity(name="League of Legends", type=discord.ActivityType.playing)
client = MyClient(command_prefix=['!', '>'], intents=INTENTS, activity=activity, help_command=None)```
shut elk
#

So my pc runs the code at any time?

young dagger
potent spear
young dagger
potent spear
potent spear
shut elk
potent spear
shut elk
#

ok, I think I quit it

#

Let me restart my bot

#

It still creates 2 verify buttons

#

2 embeds too

torpid hare
#

hello, can someone help my bot isnt setting user permissions for a channel

if str(message.author) == bot_name:
        return
    if isinstance(message.channel, discord.DMChannel):

        name = 'MODMAIL'
        guild = bot.get_guild(991639918243741757)
        guild = discord.utils.get(guild.categories, name=name)
        channels = []
        for channel in guild.channels:
            channels.append(channel.name)
        if str(message.author.id) in channels:
            channel = discord.utils.get(guild.channels, name=f"{message.author.id}")
            await message.author.send(f"You already have a ticket open! <#{channel.id}>")
        else:
            guild = await guild.create_text_channel(name=f"{message.author.id}")
            await guild.set_permissions(message.author, send_messages=True)
            await guild.set_permissions(message.author, read_messages=True)
            await guild.set_permissions(message.author, read_message_history=True)
            channel = bot.get_channel(guild.id)
            await channel.send(f"<@{message.author.id}>\nUser: {message.author}\nUser ID: {message.author.id}\nMessage: {message.content}")
            await message.author.send(f"I have created you a ticket in Lab Games <#{guild.id}>")
shut elk
#

one unupdated, one updated

young dagger
# potent spear ```py class MyClient(commands.Bot): async def setup_hook(self): upda...
[2023-01-13 01:35:19] [ERROR   ] discord.client: Ignoring exception in on_ready
Traceback (most recent call last):
  File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^
TypeError: MyClient.on_ready() takes 0 positional arguments but 1 was given```
potent spear
potent spear
young dagger
# potent spear remove the `self`
  File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 828, in run
    asyncio.run(runner())
  File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 817, in runner
    await self.start(token, reconnect=reconnect)
  File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 745, in start
    await self.login(token)
  File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 589, in login
    await self.setup_hook()
          ^^^^^^^^^^^^^^^^^
TypeError: MyClient.setup_hook() takes 0 positional arguments but 1 was given```
young dagger
potent spear
torpid hare
potent spear
torpid hare
#

i did

potent spear
#

I said, you're using
guild = guild.create_text_channel(...)
this makes no sense
use
new_text_channel = guild.create_text_channel(...)

torpid hare
#

oh

potent spear
#

get it? then rewrite the other bit and the error will speak for itself

torpid hare
#

yea, lemme try

young dagger
potent spear
young dagger
# potent spear new error + current code?
class MyClient(commands.Bot):
    async def setup_hook():
        update_elo_ratings.start()
    async def on_ready():
        print('Bot is ready!')

activity = discord.Activity(name="League of Legends", type=discord.ActivityType.playing)
client = MyClient(command_prefix=['!', '>'], intents=INTENTS, activity=activity, help_command=None)```
potent spear
young dagger
# potent spear yup, run that, should be fine
  File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 828, in run
    asyncio.run(runner())
  File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 817, in runner
    await self.start(token, reconnect=reconnect)
  File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 745, in start
    await self.login(token)
  File "C:\Users\Gamer\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 589, in login
    await self.setup_hook()
          ^^^^^^^^^^^^^^^^^
TypeError: MyClient.setup_hook() takes 0 positional arguments but 1 was given```
young dagger
#

Ofc

potent spear
potent spear
torpid hare
# potent spear good
async def on_message(message: discord.Message):
    if str(message.author) == bot_name:
        return
    if isinstance(message.channel, discord.DMChannel):

        name = 'MODMAIL'
        guild = bot.get_guild(1062991670674731098)
        guild = discord.utils.get(guild.categories, name=name)
        channels = []
        for channel in guild.channels:
            channels.append(channel.name)
        if str(message.author.id) in channels:
            channel = discord.utils.get(guild.channels, name=f"{message.author.id}")
            await message.author.send(f"You already have a ticket open! <#{channel.id}>")
        else:
            new_text_channel  = await guild.create_text_channel(name=f"{message.author.id}")

            await new_text_channel.set_permissions(message.author, send_messages=True)
            await new_text_channel.set_permissions(message.author, read_messages=True)
            await new_text_channel.set_permissions(message.author, read_message_history=True)

            channel = bot.get_channel(new_text_channel.id)
            
            await channel.send(f"<@{message.author.id}>\nUser: {message.author}\nUser ID: {message.author.id}\nMessage: {message.content}")
            await message.author.send(f"I have created you a ticket in Lab Games <#{new_text_channel.id}>")
#

its still not working

slate swan
#

since none of my discussions/forum responses are ever responded to (LIKE USUAL. doesnt matter if its in discord or not)

[Discord PY 2.0, PY 3.11] Text version of Hybrid command wont work with arguments
simple explaination: arguments work fine in the slash command but not in the text command it'self

Command Code:

@client.hybrid_command(name="setstatus", with_app_command=True, description="Change the status of the bot")
async def setstatus(self, ctx: commands.Context, type: int, status: str):
        await ctx.reply(f"Set the status to '{str(status)}' with activity type to **{int(type)}**")
        await client.change_presence(activity=discord.Activity(type=int(type), name=str(status)))

(I dont get any error messages as only the slash command itself works but not the textcommand of itself)

potent spear
#

do you realize how redundant this is?

torpid hare
#

huh

#

i see what you mean

#

but that wont solve what im trying to fix

torn sail
#

wow discord updated the python code blocks

potent spear
potent spear
torn sail
slate swan
#

will anyone actually help ?!

torpid hare
naive briar
torpid hare
#

even in my log file

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...
potent spear
naive briar
slate swan
#

should i just use like statustype ?

slate swan
torn sail
slate swan
#

i am currently not in a cog

potent spear
# torpid hare none

let's shorten this a bit, alr?

channels = []
        for channel in guild.channels:
            channels.append(channel.name)
        if str(message.author.id) in channels:

# should become
channel = discord.utils.get(guild.channels, name=str(message.author.id))
if channel:```
potent spear
#

also str(status) is redundant, since status is already a string

slate swan
potent spear
slate swan
#

since hybrid is both slash and normal

potent spear
#

that's default...

naive briar
#

I mean, you don't have to remove it

#

Not like it's gonna break everything if it's there

potent spear
#

unless you make stuff unreadable or just more complicated

slate swan
#

pov: unorganized/messy code

potent spear
#

it all starts with bad variable names
that's a mess to debug

slate swan
#

anyways, is ther any other errors within my code?

torpid hare
#
if str(message.author) == bot_name:
        return
    if isinstance(message.channel, discord.DMChannel):

        name = 'MODMAIL'
        guild = bot.get_guild(1062991670674731098)
        guild = discord.utils.get(guild.categories, name=name)
        channels = []
        for channel in guild.channels:
            channels.append(channel.name)

        if str(message.author.id) in channels:
            await message.author.send(f"You already have a ticket open! <#{channel.id}>")
            pass
        
        channel = discord.utils.get(guild.channels, name=str(message.author.id))

        if channel:
            try:
                new_text_channel = await guild.create_text_channel(name=f"{message.author.id}")

                await new_text_channel.set_permissions(message.author, send_messages=True)
                await new_text_channel.set_permissions(message.author, read_messages=True)
                await new_text_channel.set_permissions(message.author, read_message_history=True)


                await new_text_channel.send(f"<@{message.author.id}>\nUser: {message.author}\nUser ID: {message.author.id}\nMessage: {message.content}")
                await message.author.send(f"I have created you a ticket in Lab Games <#{new_text_channel.id}>")
            except Exception as e:
                print(e)
potent spear
potent spear
slate swan
#
@client.hybrid_command(name="setstatus", description="Change the status of the bot")
async def setstatus(ctx: commands.Context, statustype: int, status: str):
        await ctx.reply(f"Set the status to '{status}' with activity type to **{statustype}**")
        await client.change_presence(activity=discord.Activity(type=statustype), name=status)
torpid hare
slate swan
#

changed the "type" variable

slate swan
#

gonna see if the text cmd works

potent spear
slate swan
#

still doesnt work as text

#

how do i click a xpath in seleium

potent spear
# torpid hare if the user already has a ticket open with their user id as a name

still, close

if message.author == bot.user:
     return

if isinstance(message.channel, discord.DMChannel):

        category_name = 'MODMAIL'
        guild = bot.get_guild(1062991670674731098)
        modmail_category = discord.utils.get(guild.categories, name=category_name)
        author_modmail_channel = discord.utils.get(modmail_category.channels, name = str(message.author.id))
         if author_modmail_channel is None:
            return
         # ...

go ahead

#

ofc, not perfect format, but you can do that with your IDE

potent spear
torpid hare
#

i j want it to work

slate swan
torpid hare
#

it was working yesterday then it randomly stopped

potent spear
torpid hare
#

i couldnt find a way to do that

hardy spear
#

Hey I have a question

potent spear
torpid hare
#

no i mean in the code

hardy spear
#

About pde, heat equations analytical solution. Where to ask?

slate swan
#

I had to re add with_app command because the whole cmd itself wasnt working

potent spear
slate swan
#

it only typed a response and did nothing else

potent spear
slate swan
#

change status type and whatever string

torpid hare
potent spear
potent spear
slate swan
potent spear
torpid hare
#
if message.author == bot.user:
     return

    if isinstance(message.channel, discord.DMChannel):

        guild = bot.get_guild(1062991670674731098)
        modmail_category = guild.get_channel(1062991672465698914)
        author_modmail_channel = discord.utils.get(modmail_category.channels, name = str(message.author.id))
        if author_modmail_channel is None:
            try:
                new_text_channel = await guild.create_text_channel(name=f"{message.author.id}")
                await new_text_channel.set_permissions(message.author, send_messages=True)
                await new_text_channel.set_permissions(message.author, read_messages=True)
                await new_text_channel.set_permissions(message.author, read_message_history=True)
                await new_text_channel.send(f"<@{message.author.id}>\nUser: {message.author}\nUser ID: {message.author.id}\nMessage: {message.content}")
                await message.author.send(f"I have created you a ticket in Lab Games <#{new_text_channel.id}>")
            except Exception as e:
                print(e)
            return
        await message.author.send(f"You already have a ticket open! <#{author_modmail_channel.id}>")
slate swan
torpid hare
#

i think i did that right

slate swan
#

when it was a normal, it worked just fine

slate swan
#

main problem is, if i make a hyrbdi command without any sort of arguments, it works fine, both slash and text command

#

however if i add arguements, it stops working as a text cmd

young dagger
#

Can I use other time units for @tasks.loop(minutes=30.0) example @tasks.loop(hours=12)?

slate swan
#

i explained the problem in context

torpid hare
potent spear
slate swan
#

oh, not yet

potent spear
#

you have to add a kwarg
category = mod_category or whatever it's called

potent spear
#

maybe I need to see the whole code, I think there's more to it

#

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

torpid hare
#

create_category_channel?

potent spear
#

create_text_channel(......, category = <your modmail category> )

torpid hare
#

oh im stupid

slate swan
# potent spear create_text_channel(......, category = <your modmail category> )
import discord, typing
from discord.ext import commands
from discord import app_commands
from typing import Union
import random

client = commands.Bot(command_prefix="s!", intents=discord.Intents.all())

Token = "<censored for various reasons>"

@client.event
async def on_ready():
    await client.change_presence(activity=discord.Activity(type=0, name="Splatoon 3"))
    print("Bot is ready")
    try:
        synced = await client.tree.sync()
        print("Slash commands should have been synced")
    except Exception as e:
        print("I wasnt able to sync slash commands ;w;")

# hybrid commands

@client.hybrid_command(name="ping", description="shows bot ping, nothing else")
async def ping(ctx: commands.Context):
    await ctx.reply(f"pong! bot ping is {round(client.latency * 1000)} ms")

@client.hybrid_command(name="test", description="A test Hybrid command.")
async def test(ctx: commands.Context):
    await ctx.reply("This is a test hybrid command.")

@client.hybrid_command(name="setstatus", with_app_command=True, description="Change the status of the bot")
async def setstatus(ctx: commands.Context, statustype: int, status: str):
        await ctx.reply(f"Set the status to '{str(status)}' with activity type to **{int(statustype)}**")
        await client.change_presence(activity=discord.Activity(type=int(statustype), name=str(status)))

client.run(Token)
#

for the int() and str() it sstopped aworking safter i removed it

potent spear
#

also, are your intents enabled in the dev portal?

torpid hare
#

okay it works now but its only setting await new_text_channel.set_permissions(message.author, read_message_history=True) permission

young dagger
potent spear
torpid hare
#
if message.author == bot.user:
     return

    if isinstance(message.channel, discord.DMChannel):

        guild = bot.get_guild(1062991670674731098)
        modmail_category = guild.get_channel(1062991672465698914)
        author_modmail_channel = discord.utils.get(modmail_category.channels, name = str(message.author.id))
        if author_modmail_channel is None:
            try:
                new_text_channel = await guild.create_text_channel(name=f"{message.author.id}", category=modmail_category)

                await new_text_channel.set_permissions(message.author, send_messages=True)
                await new_text_channel.set_permissions(message.author, read_messages=True)
                await new_text_channel.set_permissions(message.author, read_message_history=True)

                await new_text_channel.send(f"<@{message.author.id}>\nUser: {message.author}\nUser ID: {message.author.id}\nMessage: {message.content}")

                await message.author.send(f"I have created you a ticket in Lab Games <#{new_text_channel.id}>")
            except Exception as e:
                print(e)
            return
        await message.author.send(f"You already have a ticket open! <#{author_modmail_channel.id}>")
potent spear
torpid hare
#

figured

potent spear
#

you could've done it like so
set_permissions(...., read_messages=True, send_messages = True, ...)

torpid hare
#

but it was setting them all yesterday

potent spear
#

yesterday isn't today

torpid hare
#

but what makes yesterday any different lol

#

i barely changed the code

potent spear
#

you can do insanely sexy shit btw

overwrites = {
  message.author: discord.PermissionOverwrite(
    read_messages=False,
    send_messages=False,
  ),
  Role1: discord.PermissionOverwrite(
    read_messages=True,
    send_messages=True,
  )
}

... create_text_channel(......, overwrites=overwrites)```
#

get it? that's an all-in-one

potent spear
#

that Role1 is just an example of how you could add more than 1 user / role/ whatever

torpid hare
#

but yea i do get what you're saying

potent spear
torpid hare
#

true

#

ill do the all in one

potent spear
young dagger
potent spear
young dagger
sick birch
sick birch
#

That's one of the main points of the tasks extensions, is to handle cases like these

potent spear
potent spear
torpid hare
#

@potent spear that seems to work thanks for all your help 🙂

sick birch
young dagger
#

@sick birch @potent spear So it's not recommended to use try-except block around the entire code block at all?

sick birch
#

Don't, for your own sake

potent spear
sick birch
#

Hi doggo
Don't see you much 'round these parts

young dagger
feral timber
sick birch
#

I would return
Non terrae plus ultra

torpid hare
young dagger
# sick birch I would return Non terrae plus ultra
Getting elo rating for Rapierknight3
Getting elo rating for Miraa Opast
[2023-01-13 02:30:04] [INFO    ] discord.gateway: Shard ID None has successfully RESUMED session 44c54ee8c27fccf6346343bce5ad02b9e4.
Getting elo rating for Toukah
[2023-01-13 02:30:19] [INFO    ] discord.gateway: Shard ID None has successfully RESUMED session 44c54ee8c27fccf6346343bce5ad02b9e4.
Getting elo rating for VivyFluoriteEyes
Getting elo rating for msxuctae```
slate swan
potent spear
potent spear
young dagger
#

Hmh I can't install the package. any idea?

[01:40] [server.beerhunter ~] # pip3 install discord.ext.tasks
ERROR: Could not find a version that satisfies the requirement discord.ext.tasks
ERROR: No matching distribution found for discord.ext.tasks```
naive briar
rare echo
naive briar
#

I hate you

young dagger
rare echo
#

from discord.ext import tasks?

#

if i remember correctly

naive briar
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
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 "discord.ext.tasks.Loop").
primal token
sick birch
#

doggy

feral timber
sick birch
#

no sir i would never

primal token
#

I expected better from you robin

paper sluice
#

Robin is acting too sus these days

slate swan
#

robin amongus

sick birch
#

mogus

manic knoll
#

could anyone help with this code?

#

its for

#

so it basically looks like this

#

its going to be used to sign people like “You have been signed by” the authors role that preformed the command

#

so basically give the role to the person that was signed

#

@sick birch

#

@slate swan

sick birch
#

Please don't ping random people

manic knoll
#

sorry

sick birch
#

Are you looking to just give the user a role?

sick birch
#

!d discord.Member.add_roles

unkempt canyonBOT
#

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

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.

You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
manic knoll
#

also send a embed at the same time

manic knoll
#

but

#

the thing is i just the want the user to get any specific role it has to be the authors role

sick birch
#

The author has many roles, which one?

rare echo
#

or do you mean only get the role if the author also has it?

manic knoll
#

hmm it would just be smart to put a string to make the author pick a role for the member

lament cosmos
#

yo new to python and discord bots

rare echo
#

welcome to the hole of "its probably really easy but idk"

lament cosmos
#

lol

manic knoll
#

@sick birch do you know how i can add another option where its a role option like it would say “role” because the other would pick a role for the member to get roled

#

like the member part

sick birch
#

Yeah just typehint to discord.Role

manic knoll
#
async def sign(interaction: discord.Interaction, member: discord.Member) -> None:
    msg = f"{member.mention} has been signed by {interaction.user.mention}!"

    if 854573259030921256 not in [role.id for role in member.roles]:
        msg = f"Sorry, but you don't have the head coach role to perform this command."
    elif member.bot:
        msg = f"You cannot sign bots since they are sentient beings, thus are immortal."
    elif interaction.user.id == member.id:
        msg = f"Hey {member.mention}! You cannot sign yourself."

    await interaction.response.send_message(msg)```
#

@sick birch so like where in this coding would i put a "discord.Role"

sick birch
#

In the async def sign

#

role: discord.Role

#

after member: discord.Member

manic knoll
sick birch
#

yeah

manic knoll
#

im getting better at this

#

thanks robin

torpid hare
#

hi, does anyone know how to get user id from when they react to a message

@bot.event
async def on_raw_reaction_add(reaction: discord.Reaction):
    if reaction.emoji.name == '👍':
        print('hi')
@bot.event
async def on_raw_reaction_remove(reaction: discord.Reaction):
    if reaction.emoji.name == '👍':
      print('hi')
manic knoll
#

@sick birch i have a huge problem ```@client.tree.command(name="sign", description="Where athletic directors & head coaches sign players")
async def sign(interaction: discord.Interaction, member: discord.Member, role: discord.Role) -> None:
msg = f"{member.mention} has been signed by {interaction.user.mention}!"

if 854573259030921256 not in [role.id for role in member.roles]:
    msg = f"Sorry, but you don't have the head coach role to perform this command."
elif member.bot:
    msg = f"You cannot sign bots since they are sentient beings, thus are immortal."
elif interaction.user.id == member.id:
    msg = f"Hey {member.mention}! You cannot sign yourself."

await interaction.response.send_message(msg)``` so theres a big problem like where i did the author had to have a certain role to preform the command and it gave a error like "you dont have the role to preform this command" that worked and all but now it does that if the member dosnt have the role that is used to preform the command which is what i dont want
manic knoll
#

@sick birch

vocal snow
torpid hare
vocal snow
#

!d discord.RawReactionActionEvent

unkempt canyonBOT
#

class discord.RawReactionActionEvent```
Represents the payload for a [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") or [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") event.
manic knoll
vocal snow
#

you can get the user from it

torpid hare
#

yea

vocal snow
manic knoll
vocal snow
manic knoll
slate swan
#
@bot.command()
async def alert(ctx, amt, time, *text):
    print(amt)
    for i in amt:
        print(i)
        text2 = " ".join(text)
        await ctx.send("{}".format(text2))
        time.sleep(time)```
manic knoll
#

let me test

slate swan
#

This sends the message once and then never again

vocal snow
slate swan
#

would amt:int work

vocal snow
#

sure. but you can't iterate over an int directly. use range

slate swan
#

ahhh I see

vocal snow
#

also you should use asyncio.sleep instead of time.sleep

#

and make sure that you wait a minimum of 5 seconds before sending the next message, or you'll get ratelimited

slate swan
#

!alert 10000000 0 amongus

slate swan
vocal snow
#

perhaps you forgot to await it

manic knoll