#discord-bots

1 messages · Page 270 of 1

upbeat ice
left dew
#

author = user who runs the command
user = the user who is being referenced e.g you’re finding the info about a user in a whois command etc

#

@upbeat ice would this work?

upbeat ice
#

sure as long as the sql is doing what you want it to do

left dew
#

yea alright

upbeat ice
#

depends on your use case

left dew
upbeat ice
#

well what are you trying to do when the user enters info twice? Append it? Overwrite it?

ember mango
#

I guess there is no difference

left dew
#

append

upbeat ice
#

then you will want to check out the Update statement

left dew
#

but wouldn’t update overwrite it?

naive briar
#

What Author?

#

An attribute of an object? A class?

turbid condor
left dew
#

i don’t know what an index is

turbid condor
#

Like 1 2 3 4

left dew
#

oh

ember mango
left dew
#

what do you mean store them in an index instead of id? could you elaborate

turbid condor
copper gulch
ember mango
#

I say if you learn it yourself disnake very easy

turbid condor
turbid condor
turbid condor
turbid condor
upbeat ice
left dew
#

then

sql = "INSERT INTO … (column1, column2) VALUES (%s, %s)"

cursor.execute(sql, data)```?
upbeat ice
naive briar
ember mango
#

Because Easy

turbid condor
naive briar
#

A library being easy doesn't automatically make it better than others

turbid condor
left dew
#

okay

ember mango
turbid condor
#

Google it

naive briar
# turbid condor Feature wise

discord.py has CommandTree, disnake doesn't. discord.py's extension, cog, loading stuff is now async, which means you can do asynchronous setup stuff, disnake doesn't

#

I'm sure there are many more things that are very different

turbid condor
upbeat ice
naive briar
ember mango
naive briar
#

Any interaction commands

turbid condor
ember mango
naive briar
#

Are we talking about the same stuff

#

That's very random

turbid condor
#

Welp we are in a useless convo I'm here cuz am bored and sleepy

naive briar
#

And, of course, in the end it's all about your preference

grand moss
#

How can I set intents.message_content = True inside this

class Bot(commands.Bot):
    def __init__(self):
        super().__init__(
            #command_prefix="!",
            command_prefix=config.prefix, 
            activity=config.starting_activity,
            intents=discord.Intents.default(), 
            help_command=None
        )

        for filename in os.listdir("./cogs"):
            if filename.endswith(".py"):
                self.load_extension(f"cogs.{filename[:-3]}")
#

was looking at different ways people set things up

turbid condor
naive briar
turbid condor
#

Or put message_content=True inside the brackets

naive briar
#

!d discord.Intents.default

unkempt canyonBOT
#

classmethod default()```
A factory method that creates a [`Intents`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents "discord.Intents") with everything enabled except [`presences`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.presences "discord.Intents.presences"), [`members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members"), and [`message_content`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.message_content "discord.Intents.message_content").
naive briar
#

Doesn't accept arguments, so no

turbid condor
#

And surprisingly it worked

naive briar
#

I wouldn't be surprised if it actually didn't

turbid condor
#

Or it might have been an other lib

ember mango
#

How to remove ["]

#

When I ask questions, you all keep quiet💀

turbid condor
#

!e

Sel=['a','b','c']
X=','.join(Sel)
print(X)
unkempt canyonBOT
#

@turbid condor :white_check_mark: Your 3.11 eval job has completed with return code 0.

a,b,c
grand moss
turbid condor
upbeat ice
turbid condor
grand moss
#

yes

turbid condor
grand moss
#
def main():
    bot = Bot()
    TOKEN = os.environ.get("TOKEN")
    #keep_alive()
    bot.run(TOKEN)

if __name__=="__main__":
    main()```
ember mango
#

Oh

#

Alright

turbid condor
#

Define a variable outside of your class

Import discord

intents=....

class .....
#

@grand moss

#

And then inside your class do intents=intents

#

Should work

grand moss
#

ok i'll try

#

so inside the class its like intents(local)=intents(global)?

upbeat ice
#

global variables can be referenced anywhere

ember mango
#

What is this

upbeat ice
#
super().__init__(
            intents=intents)```
turbid condor
#

Nah just intents=intents should work

grand moss
#

thanks, I don't see the message intent waring anymore

turbid condor
slate swan
slate swan
ember mango
turbid condor
#

Show

ember mango
turbid condor
ember mango
slate swan
#

I dont see sending embed part here

ember mango
slate swan
#

Still no luck

#

Also

#

The x is a string

turbid condor
#

Tbh I'm confused shouldn't random.choice be an array?

ember mango
#

Help mee

slate swan
#

Why even use random.choices when you can do random.choice

ember mango
slate swan
#

..

#

You even understand what im typing

turbid condor
ember mango
turbid condor
#

Instead of random.choices just do random.choice

#

That will randomly choose 1 option from Selelct1

#

Likepy random.choice(Select1)

#

Instead of choices

ember mango
#

Ty

turbid condor
#

!e

import random

Sel=['a','b','c']
X=random.choice(Sel)
print(X)
unkempt canyonBOT
#

@turbid condor :white_check_mark: Your 3.11 eval job has completed with return code 0.

b
grand moss
#

its telling me to await main()

#from utils.keep_alive import keep_alive
from utils.bot import Bot
import os


async def main():
    bot = await Bot()
    TOKEN = os.environ.get("TOKEN")
    #keep_alive()
    bot.run(TOKEN)

if __name__=="__main__":
    main()```
upbeat ice
#

main~~ doesnt~~ shouldnt need to be async

#

and you dont need to await Bot()

#

import it and instantiate it

left dew
slate swan
left dew
#

okay

#

i did ask in thete but no one replied

feral timber
#

@sick birch it appears your assistance is needed

sick birch
#

why have you summoned me to this place

vale wing
grand moss
#

oh thanks. I haven't use asyncio so far

vale wing
#

And yeah the body of your function got no async stuff so you can just bring the code out from it

#
import os
from utils.bot import Bot

Bot().run(os.getenv("TOKEN"))
slate swan
#

do you load the cog

#

If you think the event is not being called add a print("blah") at the top

#

then you will know and not think

#

ok but where

#

And?

#

where is this code

#

Proper intents enabled?

#

...

#

how you make sure this code snippet is being run

#

Then it's not @commands.Cog.listener()...

#

where is that

#

im currently working on an economy bot and in my db im making a database table for power ups how is the best way to check if they have a power up as well as having all of them separately timed say it activates randomly for between an hour and 4 hours so i wanna set it so they have access to that power up for that time only i was thinking of using interval but im not getting my logic right here, any help is appreciated thank you im working with postgres here

#

It's @bot.listen or @bot.event considering you use bot and not some weird naming

slate swan
#

Then add logging

#

add this print after loading cogs : print(bot.cogs)

#

For example

#

after loading cogs

#

show it

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.

slate swan
#

No wonder if you have thousands of cogs kek

#

did you put it inside for loop

#

my god what kind of bot is that

#

nevermind

#

it's just in the loop so always prints everything again and again

#

how is the cog named you have this code in

#

cog not file

#

you know what a cog is?

#

its a class

#

that is subclass of commands.Cog

#

show full code of this cog

marble wasp
#

Possible to add custom buttons to a bots profile? Like how a rich presence works or not?

marble wasp
slate swan
#

like i said before no its not possible for bots

#

why not here?

#

no code no help Shrugdge

#

i dont see anything wrong for now cog is loaded so i need to see code maybe you did something wrong here

#

hm really weird its defined correctly

#

do you have any other on_message event in your bot?

vale wing
#

Bro you have 2 functions named on_message, only second takes effect

slate swan
vale wing
#

Yes way

slate swan
#

the Cog.listener() should take name of an event

#

so you can name your function something other

vale wing
#

☺️

vale wing
slate swan
#

yes, cool, but how can i set it for a specific amount of time

vale wing
#

Uh how exactly the time works

slate swan
#

thats what im trying to figure out

#

do i do like a timestamp or a interval or something

vale wing
#

You mean like what

  1. Powerups can be used only in certain time in day, eg. from 4am to 1pm UTC
  2. Powerups can be used after interval passed since their acquirance
slate swan
#

a power up has a duration

#

i understand it as powerups will be active for amount of time

#

yes

vale wing
#

Ah okay so user activates it and then it expires

slate swan
#

correct

vale wing
#

What db you using?

slate swan
#

postgres

vale wing
#

Ah great, datetime management will be easier then

#
CREATE TABLE IF NOT EXISTS powerups (
    user_id BIGINT NOT NULL,
    powerup_id WHATEVER NOT NULL,
    is_active BOOLEAN DEFAULT false NOT NULL,
    expiration_time TIMESTAMP
)
#

This should be pretty much sufficient table for desired functionality

#

When user acquires powerup, just insert user id and powerup id, when they activate powerup, update is_active and expiration_time

slate swan
#

what if they use more than 1 power up at time

vale wing
#

Just stack them

slate swan
#

oh so i just insert more or

#

then when it expires ill delete it

vale wing
#

If powerups of same type aren't allowed to be stacked just do unique key

UNIQUE (user_id, powerup_id)
slate swan
#

should the timestamp be a timestamp with timezone tho? a utc one or no

vale wing
# slate swan then when it expires ill delete it

Yeah there are several approaches you can use

  1. In python code, when checking for is_active also check for expiration_time
  2. Create loop and regularly run DELETE FROM powerups WHERE expiration_time < CURRENT_TIMESTAMP
  3. Create postgres rule that would essentially do the same thing as in 1 but on db level
vale wing
#

You just need datetime.now() + timedelta(...)

slate swan
#

oh okay nice idk why i use utc for other stuff probably because of discords weird timestamps

slate swan
vale wing
#

MIght be bit complicated for begginers but are a useful thing

slate swan
#

i think its the best approach however

#

and id use it how exactly? Just call it when they run the command

vale wing
#

Eh I need to remember how to use them by myself lol

#

Hang on a minute

slate swan
#

like

CREATE OR REPLACE RULE delete_expired_powerups
AS ON DELETE TO powerups
DO INSTEAD
   DELETE FROM powerups WHERE expirationTime < CURRENT_TIMESTAMP;```
#

ive used it once before lol im not too skilled

#
CREATE TABLE IF NOT EXISTS powerupnames(name TEXT, powerupSerial SERIAL PRIMARY KEY);

CREATE TABLE IF NOT EXISTS powerups(userID BIGINT powerupID INT, isActive BOOLEAN DEFAULT FALSE, expirationTime TIMESTAMP, FOREIGN KEY (powerupID) REFERENCES powerupnames(powerupSerial));``` i think as for tables this is a sufficient enough setup
vale wing
#

Sorry confused it with trigger, it's not a rule

slate swan
#

ah

#

no worries

vale wing
#

Nevermind triggers aren't for selects

slate swan
#

oh so what do i use

vale wing
slate swan
#

ah okay so when they run the command i check if the time is over and if it is i delete

#

or i can jam it into my task loop for giveaways

torn solar
#
        if select.values[0] == "01":
            category = discord.utils.get(guild.categories, name="CHECKING")
            channel = await guild.create_text_channel(f'{interaction.user.name}', category=category, overwrites=overwrites)
        elif select.values[0] == "02":
            category = discord.utils.get(guild.category, name="SAVINGS")
            channel = await guild.create_text_channel(f'{interaction.author.name}', category=category, overwrites=overwrites)```
Its saying guild object has no attribute category
#

but it literally does

upbeat ice
#

where have you defined guild

torn solar
#
    guild = interaction.guild
    role = discord.utils.get(guild.roles, name="Employee")
    overwrites = {
        guild.default_role: discord.PermissionOverwrite(view_channel=False),
        interaction.author: discord.PermissionOverwrite(view_channel=True),
        role: discord.PermissionOverwrite(view_channel=True)
    }
    
    select = Select(options=[
        discord.SelectOption(label="Checking Account", value="01", description="Talk to a representative about opening a checking account."),
        discord.SelectOption(label="Savings Account", value="02", description="Talk to a representative about opening a savings account")
    ])
    
    async def select_callback(interaction):
        if select.values[0] == "01":
            category = discord.utils.get(guild.categories, name="CHECKING")
            channel = await guild.create_text_channel(f'{interaction.user.name}', category=category, overwrites=overwrites)
        elif select.values[0] == "02":
            category = discord.utils.get(guild.category, name="SAVINGS")
            channel = await guild.create_text_channel(f'{interaction.author.name}', category=category, overwrites=overwrites)
            
    select.callback = select_callback
    view = View(timeout=None)
    view.add_item(select)
    await interaction.send(view=view)```
upbeat ice
#

any reason why you are using guild.category and not guild.categories

torn solar
#

oops

torn solar
#

wait no im not

#

it says interaction failed but its creating the channel how i want it to

#

@upbeat ice do you have any clue why

#

no errors either

#
    guild = interaction.guild
    role = discord.utils.get(guild.roles, name="Employee")
    overwrites = {
        guild.default_role: discord.PermissionOverwrite(view_channel=False),
        interaction.author: discord.PermissionOverwrite(view_channel=True),
        role: discord.PermissionOverwrite(view_channel=True)
    }
    
    select = Select(options=[
        discord.SelectOption(label="Checking Account", value="01", description="Talk to a representative about opening a checking account."),
        discord.SelectOption(label="Savings Account", value="02", description="Talk to a representative about opening a savings account")
    ])
    
    async def select_callback(interaction):
        if select.values[0] == "01":
            category = discord.utils.get(guild.categories, name="CHECKING")
            channel = await guild.create_text_channel(f'{interaction.user.name}', category=category, overwrites=overwrites)
        elif select.values[0] == "02":
            category = discord.utils.get(guild.categories, name="SAVINGS")
            channel = await guild.create_text_channel(f'{interaction.user.name}', category=category, overwrites=overwrites)
            
    select.callback = select_callback
    view = View(timeout=None)
    view.add_item(select)
    await interaction.send(view=view)```

Thats the code
#

i fixed it

lime crescent
#

does anyone know how to make a uploader bot?

#

i wanna make my bot upload stuff from yt tt etc

potent spear
torn solar
lime crescent
#

?

upbeat ice
upbeat ice
torn solar
slate swan
#

What’s wrong with this code

atomic yacht
#

Is there a free anti-raid security bot code i could have for my bot?

upbeat ice
upbeat ice
atomic yacht
#

like i have 5 mins before i have to leve

upbeat ice
#

no one is going to write it for you here

shrewd vapor
#

Hi guys, i need help for create a button open link for embed

upbeat ice
#

anything more specific?

#

!d discord.ui.Button

unkempt canyonBOT
#

class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.

New in version 2.0.
upbeat ice
#

!d discord.ButtonStyle.link

unkempt canyonBOT
naive briar
#

You're probably looking for discord.Client, with capitalized C

#

!d discord.Client

unkempt canyonBOT
#

class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

async with x Asynchronously initialises the client and automatically cleans up.

New in version 2.0.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
torn solar
#

every time my bot goes offline then back online, the selections and buttons stop working unless i re put them in

#

is there any way to prevent this cus its really irritating

upbeat ice
#

nope

#

you have to call the command every time

torn solar
#

that sucks

winter hare
#

class Client(discord.ext.commands.bot.Bot)
 |  Method resolution order:
 |      Client
 |      discord.ext.commands.bot.Bot
 |      discord.ext.commands.bot.BotBase
-- More  --```
does anyone know why this happened
winter hare
#

i dont know

naive briar
winter hare
#

it just randomly started showing up

torn solar
upbeat ice
torn solar
#

like when the bot starts up it automatically sets up?

naive briar
upbeat ice
#

this seems like a heavy handed approach to something thats not really a problem

winter hare
# upbeat ice what does the code look like
    def __init__(self):
         super().__init__(command_prefix='.', intents=discord.Intents.all())



    async def on_ready(self):
            prfx = (Back.RED + Fore.BLACK + time.strftime('%H:%M:%S UTC', time.gmtime())) 
            print(prfx + ' Logged in as ' + Fore.LIGHTCYAN_EX + client.user.name)
            print(prfx + " Python Version " + Fore.LIGHTCYAN_EX + str(platform.python_version()))
            synced = await client.tree.sync()
            guild = client.get_guild(1019500131747381249)
            syncs = await client.tree.sync(guild=guild)
            print(prfx + ' Slash CMDs synced '+ Fore.LIGHTCYAN_EX + str(len(synced)) + ' Commands')
            print(prfx + ' Guild Only Slash CMDs synced '+ Fore.LIGHTCYAN_EX + str(len(syncs)) + ' Commands')
            print(prfx + ' Current Discord Version '+ Fore.LIGHTCYAN_EX + str(discord.__version__))
            print('Bot is online!!!')```
torn solar
#
        guild.default_role: discord.PermissionOverwrite(view_channel=False),
        interaction.author: discord.PermissionOverwrite(view_channel=True),
        role: discord.PermissionOverwrite(view_channel=True)
    }
    overwrites_loans = {
        guild.default_role: discord.PermissionOverwrite(view_channel=False),
        interaction.author: discord.PermissionOverwrite(view_channel=True),
        role2: discord.PermissionOverwrite(view_channel=True)
    }```
#

its not adding the author to the ticket

naive briar
upbeat ice
torn solar
#

!haste

#

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

upbeat ice
#

you dont add the author anywhere

torn solar
#

line 29

#

channel = await guild.create_text_channel(f'checking-{interaction.user.name}', category=category, overwrites=overwrites_accounts)

#

i added the overwrites

upbeat ice
#

so its not adding it to the channel name?

#

or on the embed?

torn solar
#

its not adding them to the channel

#

so they create a ticket and theyre not in it

upbeat ice
#

do you have the members intent?

torn solar
#

yes

torn solar
upbeat ice
#

and no errors?

#

interaction.author: discord.PermissionOverwrite(view_channel=True) this should be interaction.user

torn solar
#

even though the docs literally say interactions has an attribute user

upbeat ice
#

are you trying to use slashcommands?

torn solar
#

no

#
async def setupTicket(ctx):
    embed = discord.Embed(color=cb_color, title='SUPPORT', description=ticket_desc)
    embed.set_thumbnail(url=bot.user.display_avatar)
    await ctx.send(embed=embed)
    await ticket(ctx)
    ctx.message.delete()```
#

thats the command to setup the ticket

upbeat ice
#

oh

#

usually people use ctx instead of interaction

naive briar
#

Context and interaction objects are not the same

torn solar
#

its an interaction though

torn solar
#

either way though, its not adding the members to the ticket they created

naive briar
#

Just because you name it interaction doesn't make it an interaction object

torn solar
upbeat ice
#

in your case it would be interaction.member

#

although you really should use ctx instead of interaction because that means something entirely different

torn solar
upbeat ice
#

im not entirely sure.. i almost never use context objects but let me look it up

turbid condor
#

Btw in your code u are using interaction.author whereas it should interaction.user

upbeat ice
#

well interaction is ctx for him

torn solar
#

its a context object

naive briar
#

That's why you should name variables properly

torn solar
#

so can you tell me how to fix???

naive briar
#

Fix what

upbeat ice
torn solar
#
        guild.default_role: discord.PermissionOverwrite(view_channel=False),
        interaction.user: discord.PermissionOverwrite(view_channel=True),
        role: discord.PermissionOverwrite(view_channel=True)
    }
    overwrites_loans = {
        guild.default_role: discord.PermissionOverwrite(view_channel=False),
        interaction.user: discord.PermissionOverwrite(view_channel=True),
        role2: discord.PermissionOverwrite(view_channel=True)
    }```
#

its not adding the author

#

its meant to say author not user btw

turbid condor
#

Wait is that a Select option? Or does it listen the bot listen to reply

#

Cuz if it's a select menu shouldn't you be putting that in a View and then send it along your message?

upbeat ice
#

he has a view - dont know what is in it though view = View(timeout=None)

turbid condor
torn solar
#

!hastebiin

#

!hastebin

upbeat ice
#

dont you have to call .update() on perm overwrite?

torn solar
#

idk but please help

#

how do i call that

upbeat ice
#

!d discord.PermissionOverwrite

unkempt canyonBOT
#

class discord.PermissionOverwrite(**kwargs)```
A type that is used to represent a channel specific permission.

Unlike a regular [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions"), the default value of a permission is equivalent to `None` and not `False`. Setting a value to `False` is **explicitly** denying that permission, while setting a value to `True` is **explicitly** allowing that permission.

The values supported by this are the same as [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions") with the added possibility of it being set to `None`.

x == y Checks if two overwrites are equal.

x != y Checks if two overwrites are not equal.

iter(x) Returns an iterator of `(perm, value)` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
upbeat ice
#

do you get any errors @torn solar

torn solar
#

idk what to do with that

#

!paste

#

well some of it

#

im using permission overwrite but its not working

upbeat ice
#

first off change ctx.user to ctx.author

torn solar
#

done

upbeat ice
#

now if you get any errors that would be helpful

#

also interaction.user.name should be interaction.author.name

#

interaction.user.mention -> interaction.author.mention

torn solar
#

well those actually work

#

cus they are actualy interactions

#

but i tried it out with author and it didnt work

#

no errors

#

ill try to ask chat gpt

upbeat ice
#

why don't you try subclassing

#

instead of doing this nested function

#

subclass discord.ui.Select

#

and subclass discord.ui.View while you are at it

#

@torn solar

torn solar
#

i dont know how to sub class

#

im just getting very pissed of at how this should work and it isnt

stark socket
#

i have a pretty simple oauth discord app that all it does is when a user click in the login with discord it pops the thing for the user to allows the perms it makes a request to dicord api for the access token, now i have the user data and i want to join him to discord server how can i make it?

#

i was trying with something like this

    response = requests.post(f'https://discord.com/api/v10/guilds/{guild_id}/members/{user_id}', headers=headers, json=data)
    print(response)
#
headers = {
    'Authorization': f'Bearer {access_token}',
    'Content-Type': 'application/json'
}
data = {
    'access_token': access_token,
    'nick': current_user.username
}
#

but it didnt work

obsidian fable
#

is it possible for slash commands to include 2 words? something like /ticket create

naive briar
#

Yes, and they're called subcommands

obsidian fable
hushed galleon
naive briar
unkempt canyonBOT
#
Nah.

No documentation found for the requested symbol.

obsidian fable
#

@naive briar one more question, I am currently using extensions, can I use it with @commands.hybrid_command()?

naive briar
#

There's hybird_group

#

!d discord.ext.commands.Bot.hybrid_group

unkempt canyonBOT
#

@hybrid_group(name=..., with_app_command=True, *args, **kwargs)```
A shortcut decorator that invokes [`hybrid_group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.hybrid_group "discord.ext.commands.hybrid_group") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.add_command "discord.ext.commands.Bot.add_command").
obsidian fable
#
@commands.hybrid_group()
async def ticket(interaction: discord.Interaction):
    pass```
#

something like this?

naive briar
#

Yeah

obsidian fable
#

let me try

hushed galleon
#

feels a bit weird for dpy groups to have several different syntaxes for using them but not having a single source describing them

naive briar
obsidian fable
#
@commands.hybrid_group()
async def minecraft(interaction: discord.Interaction):
    pass

@minecraft.command(name="status", description="Gets the status of a Minecraft server.")
async def status(interaction: discord.Interaction, ip: str):
    await interaction.response.defer()
    await interaction.send(f"Server: {ip}")

async def setup(bot):
    bot.add_command(minecraft)

Hybrid command raised an error: Command 'status' raised an exception: AttributeError: 'Context' object has no attribute 'response'

hushed galleon
#

hybrid group takes a commands.Context the same as hybrid commands do

obsidian fable
#

I am kinda confused about this subcommand thing

#

what should I add to hybrid_group?

hushed galleon
#

the first argument should be ctx: commands.Context

obsidian fable
#

I see

#

to the group or to the command?

naive briar
#

Both

obsidian fable
#

do I use ctx instead of interaction?

hushed galleon
#

are you using a type checker in your editor?

obsidian fable
hushed galleon
#

if its configured correctly it should give you warnings based on your definitions and typehints, like using the wrong variable

hushed galleon
# hushed galleon feels a bit weird for dpy groups to have several different syntaxes for using th...

from what i can recall, there's a group instance: py ticket = app_commands.Group(name="ticket", description="...") @ticket.command(name="create") async def ticket_create(interaction): ... bot.tree.add_command(ticket) a group subclass: py class TicketGroup(app_commands.Group, name="ticket"): @app_commands.command() async def create(self, interaction): ... bot.tree.add_command(TicketGroup()) a group instance within a cog: py class TicketCog(commands.Cog): ticket = app_commands.Group(name="ticket", description="...") @ticket.command(name="create") async def ticket_create(self, interaction): ... await bot.add_cog(TicketCog()) and a group for an entire cog: py class TicketCog(commands.GroupCog, group_name="ticket"): @app_commands.command() async def create(self, interaction): ... await bot.add_cog(TicketCog()) first is not mentioned in docs, first and second require manual teardown in extensions (source code says otherwise for this actually), third one only has subtle hints to its possibility in Cog docs, and second and fourth use app_commands.command() inside the class which isnt demonstrated in docs...

stark socket
#

not autorized

#

im gonna pass to that other theard than

torn solar
#

!paste

stark socket
#

ok nvm solved the issue thanks anyway ; )

hushed galleon
ivory crypt
#

I want to make a slash command named '/solitaire leaderboard' but it says that I can't use space bar in a command name. However, I have seen some commands which have a display name containing space bar inside. How can I make it?

torn solar
#
    channel = interaction.channel
    embed = discord.Embed(title="Closing Confirmation", color=cb_color, description="\nTo confirm closing this ticket, react with ✅. Otherwise react with ❌\n")
    confirm_close = Button(label="✅ Confirm", style=discord.ButtonStyle.gray)
    cancel_close = Button(label="❌ Cancel", style=discord.ButtonStyle.gray)
    view = View(timeout=None)
    view.add_item(confirm_close)
    view.add_item(cancel_close)
    message = await interaction.response.send_message(embed=embed, view=view)
    
    async def confirm_callback(interaction):
        await channel.delete()
        
    async def cancel_callback(interaction):
        await message.delete()
        
    cancel_close.callback = cancel_callback
    confirm_close.callback = confirm_callback```
For the `cancel_callback` function it says Nonetype has no attribute delete()
#

even though its a message, and it was working before but randomly stopped

naive briar
#

interaction.response.send_message doesn't return the sent message

#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by sending a message.
torn solar
#

can i not delete it?

golden portal
#

!d discord.Interaction.delete_original_response

unkempt canyonBOT
#

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

Deletes the original interaction response message.

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

could also get the InteractionMessage by Interaction.original_response

ivory crypt
shrewd apex
ivory crypt
#

Hmm I tried some methods like these but it seems not work (AttributeError: 'NoneType' object has no attribute 'app_command')

slate swan
#

cog is None

ivory crypt
narrow wadi
#

I've been trying to make a custom help command using the default one and subclassing it, but cogs aren't showing as categories and the help command won't show up in servers for some reason yet works in dms. I'd also prefer to have it list the categories then go help category to get the commands in that category, but I'm unsure exactly how to do that.

slate swan
#

!customhelp

unkempt canyonBOT
#
Custom help commands in discord.py

To learn more about how to create custom help commands in discord.py by subclassing the help command, please see this tutorial by Stella#2000

tidal hawk
#

Haven't made a discord bot for almost a year now, is disnake still superior? xD

naive briar
#

Have it ever been?

slate swan
rugged shadow
#

anything is good if you know how to use it :P

tidal hawk
#

Well discord bot libraries used to have pros and cons? For example disnake, pycord had slash commands while discord.py didn't natively.

slate swan
#

as well as all discord libraries

tidal hawk
#

So basically every library is equal feature wise?

slate swan
#

yeah

tidal hawk
#

Alriight

rugged shadow
#

i'd still recommend disnake today though

#

with discord.py, iirc you have to go through setting up a command tree yourself

slate swan
#

in nextcord or disnake its handled a bit different so you dont have to sync it

rugged shadow
#

yeah

#

i like disnake because of how you can just @bot.slash_command and it makes one for you

slate swan
#

its the same in nextcord though

naive briar
#

It's all preferences

#

I just keep using discord.py since I don't know any other

slate swan
#

use the raw discord API 🙏

rugged shadow
#

i have yet to see a discord bot made in bash using curl for interacting with the API

slate swan
ember mango
#

Hi, ☺️ Anyone Can help me?

thin raft
#

The bot does not have the necessary permissions

#

!d discord.TextChannel.send

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

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
ember mango
thin raft
#

then check it's docs for knowing what to check for

ember mango
thin raft
ember mango
#

Not prefix

thin raft
#

doesn't matter

naive briar
#

What does that have to do with anything

ember mango
#

Where to paste this?

thin raft
ember mango
#

verse

thin raft
#

you won't start to run before you can stand up

ember mango
left dew
#

im looking for a value in one list, then once i have this value, i will use its index position to find a value in another list, however the code i have now gives me an index number that doesnt work and idk why

      if "orange" in values:
        position = order_details.index("orange")
        print(position)
        multiplier = amount[position]
        print(multiplier)
        price = multiplier * 6.95
        total_price.append(price)
        print(price)```
thin raft
left dew
# thin raft can you show amount and position lists

its not a set list, its what a user has inputted.
amount should be smthn like ["1:" 200, "2:" 400].. and position is the order contents with the values, [100, "orange", 200 "apple"]. I then use a function to get the numbers and put them into a separate list

#

because the size of each list could vary

#

and therefore i need to get the corresponding values

thin raft
#

show whole code

naive briar
turbid condor
left dew
# thin raft show whole code
      con,cur = openCON()
      cur.execute(f"SELECT * FROM order_details WHERE userID = '{interaction.user.id}'")
      i = cur.fetchall()[0]

      order_details = i['order_contents']
      values = str(order_details.split(","))
      print(values)

      amount = extract_numbers_with_order(values)
      
      if "orange" in values:
        position = order_details.index("orange")
        print(position)
        multiplier = amount[position]
        print(multiplier)
        price = multiplier * 6.95
        total_price.append(price)
        print(price)```
ember mango
#

Some people who don't know anything tell me to learn python first

thin raft
ember mango
thin raft
ember mango
#

Good luck

thin raft
#

good luck

thin raft
naive briar
#

Love these conversation

left dew
# thin raft what's extract_numbers_with_order?
def extract_numbers_with_order(input_string):
    pattern = r'\d+' 
    numbers = re.findall(pattern, input_string)
    
    numbers_with_order = {}
    for i, num in enumerate(numbers, start=1):
        numbers_with_order[i] = int(num)
    
    return numbers_with_order```
#

gets all the numbers

thin raft
#

can you explain what you're trying to do

#

and paste the whole code on

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.

thorn grove
#

@client.event
async def on_raw_reaction_remove(reaction):
  if reaction.channel_id == 1129756575175819324:
      verified_role = get(reaction.member.guild.roles,name="Melon seedlings")
      await reaction.member.remove_roles(verified_role)
``` can anyone tell me why its telling me that "nonetype" object has no attribute `guild`
left dew
# thin raft can you explain what you're trying to do

so basically, a user will input their order into a modal. these values get stored in a database. then they can see the cost of their order. so to get the amount of each item i am extracting the numbers, however i dont know which item correspons to which amount. therefore i am looking through the data in the db ad=nd checking if "orange" is in the contents. then i was index this list to find the position and i can then use this position to find the amount of the oranges in the other list. once i have the amount i can multiply it by the price

naive briar
#

Do you have the members intent

#

!d discord.Intents.members

unkempt canyonBOT
#

Whether guild member related events are enabled.

This corresponds to the following events...

thorn grove
thin raft
thorn grove
#

uh yeah i have members intent enabled

thin raft
thin raft
thorn grove
#

how could i do that in code?

thin raft
#

you need to enable in code

#

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

thorn grove
#

intents.members = True?

thin raft
#

yup

left dew
thorn grove
#

oh alr tnx:)

left dew
#

['100', ' oranges', ' 20', ' apples']

thorn grove
#

@thin raft still throwing me that error

thin raft
#

use a dict

naive briar
#

!d discord.RawReactionActionEvent.member

unkempt canyonBOT
left dew
thin raft
left dew
#

int is for integer right?

thin raft
#

yeah

left dew
#

thays why

thin raft
#

im asking why would you use ints and not lists for example

#

if you want to add one and two

left dew
#

uhh

thorn grove
left dew
#

im not sure

thin raft
#

each data type has it's own usecase

#

in your case a dict would be suited better

left dew
#

how would i use a dict here?

thin raft
#

!e

amounts = {
  "oranges": 100,
  "apples": 5
}

for fruit, amount in amounts.items():
  print(fruit, amount)
unkempt canyonBOT
#

@thin raft :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | oranges 100
002 | apples 5
thin raft
#

se how easier it is?

left dew
#

oh yea that is easier

thin raft
#

Can you show the structure from your table

left dew
#

my db table?

thin raft
#

yeah

thorn grove
thin raft
left dew
thin raft
thin raft
left dew
#

i dont see the need

thin raft
#

orders(id INTEGER, user INTEGER)
items(order_id INTEGER, item STRING, amount INTEGER)

left dew
#

also howd i insert a dict into a db

thin raft
#

use another table

left dew
#

oh

#

is it possible to keep my code in a list atm?

thorn grove
# thin raft whole code after changing intents
import discord
from discord.utils import get

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

client = discord.Client(intents=intents)

@client.event
async def on_ready():
  print("online")

@client.event
async def on_raw_reaction_add(reaction):
  if reaction.channel_id == 1129756575175819324:
    if str(reaction.emoji) == "🍉":
      verified_role = get(reaction.member.guild.roles,name="Melon seedlings")
      await reaction.member.add_roles(verified_role)

@client.event
async def on_raw_reaction_remove(reaction):
  if reaction.channel_id == 1129756575175819324:
      verified_role = get(reaction.member.guild.roles,name="Melon seedlings")
      await reaction.member.remove_roles(verified_role)```
thin raft
thin raft
left dew
#

ill stick with lists for now then swtch later

naive briar
naive briar
naive briar
#

Called it

thin raft
#

Yup

#

Let me a sec

#

client.get_guild(event.guild_id).members

left dew
thorn grove
#

the rawreactionevent?

thin raft
#

yeah

naive briar
#

But there's orange, with a whitespace infront of it for some reason

thorn grove
slate swan
#

Actually oranges with an s

naive briar
#

Right

left dew
#

the orange and apples are just made up

#

i have different values in my real code

slate swan
#

Yeah then maybe actually give your code and not some nonsense

left dew
#

hows it nonsense if i replace a word with orange?

#

lol

slate swan
#

Because then it leads to such responses and you giving not even working code

left dew
#

it would work the same either way

thorn grove
thin raft
thorn grove
#
@client.event
async def on_raw_reaction_remove(reaction):
  if reaction.channel_id == 1129756575175819324:
      verified_role = get(client.get_guild(reaction.guild_id).members.guild.roles,name="Melon seedlings")
      await reaction.member.remove_roles(verified_role)
#

like this?

naive briar
#

You already have the guild that is returned by the get_guild method

#

Why would you need members.guild

thorn grove
#

oh alr

#

now it says it has no roles attributes

naive briar
#

Show the actual error

#

!traceback

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

thorn grove
naive briar
#

Why .members

#

Remove it

thorn grove
#

ok

#

@naive briar

naive briar
thorn grove
#

only on reaction_add

naive briar
#

The member attribute will always be None if you try to get it from a payload you get from the on_raw_reaction_remove event

thorn grove
#

what do i do then?

naive briar
#

Try to get the member from somewhere else?

left dew
#

@thin raft i found out why it’s bugging

#

it’s not giving me the index it’s giving me the number of characters before the value that i want

#

and idk why

thorn grove
ivory crypt
#

How do I make groups for commands in main.py by discord.py and use them in different cogs?

obsidian fable
#

how can I use choices in slash?

slate swan
#

!d discord.app_commands.choices

unkempt canyonBOT
#

@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.

Example...
obsidian fable
#

thank you

hushed galleon
obsidian fable
hushed galleon
obsidian fable
hushed galleon
#

gamemode would receive int, so gamemode.name isnt valid

obsidian fable
#

so only int?

#

cause it is not showing suggestions

@commands.hybrid_command(name="plancke", description="Says hello!")
@app_commands.describe(gamemode='Choose a Hypixel gamemode')
@app_commands.choices(gamemode=[
    discord.app_commands.Choice(name='Hypixel Level', value=1),
    discord.app_commands.Choice(name='Super Smash', value=2),
    discord.app_commands.Choice(name='Blitz', value=3),
])

async def plancke(interaction: discord.Interaction, gamemode: int, ign: str):
    await interaction.defer(ephemeral=False)
    await interaction.send(f'{gamemode.name}')```
hushed galleon
#

ya, also the interaction.defer/send methods dont exist in discord.py and should be replaced with interaction.response.defer() / interaction.followup.send() respectively (or interaction.response.send_message() if you decide to remove the defer)

obsidian fable
hushed galleon
#

oh right, in that case your first argument should have been typehinted with commands.Context

obsidian fable
#

intraction: commands.Context?

hushed galleon
#

id suggest clicking the curly braces on the bottom right of vscode to turn on type checking, you'll get a lot more helpful warnings that way (though only if you write your typehints correctly)

obsidian fable
#

I see

#

oh 💀

hushed galleon
obsidian fable
#

that seemed to work, thank you!

slate swan
#

oh its hypixel stats bot

obsidian fable
#

its just a lot of random stuff mashed together tbh

slate swan
#

i used to do one back in the days

#

my first discord bot project

#

like 1,5 year ago skull

obsidian fable
#

😭

#

this is the most random bot

slate swan
#

i see

obsidian fable
#

@hushed galleon hello, sorry for the mentions, how can I access the name in discord.app_commands.Choice(name='Hypixel Level', value=1),?

hushed galleon
#

you could set the value to the same thing as the name, but the Literal syntax suggested in docs is likely more appropriate for your use case

#

e.g. gamemode: typing.Literal["Hypixel Level", ...], which would replace your choices() decorator

hushed galleon
#

i did say it was likely more appropriate

#

so yes

obsidian fable
#

alright

#

thank you

halcyon acorn
#

Hey! is there an up to date guides on how to add and use cogs, my discord code being in 1 file is an absolute mess.

#

I have tried to find a tutorial but have had no luck.

Any help is greatly appreciated.

halcyon acorn
#

what would the file name be for a cog?

slate swan
#

doesnt matter

#
  1. dont share your bot token
  2. how is it supposed to know what testcog is
#

import it or use setup functions

halcyon acorn
#

hmm

slate swan
#

why you do Intents.all() and then still enable some

#

also bot.add_cog is awaitable if you use discord.py

sleek dagger
#

why does it say the file doesent exist when im sure it exists
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: FileNotFoundError: [Errno 2] No such file or directory: './logfile.txt'

#
lient = commands.Bot(command_prefix='.', intents=discord.Intents.all())

@client.command()
async def hello(ctx):
    ctx.send("Bonsoir, here are your logs. \\/")
    ctx.send(discord.File(r'logfile.txt'))
    with open('logfile.txt', 'w') as dalog:
        dalog.write("")


client.run('no token for u')
slate swan
#

Show file tree and from where you try to Access it

left dew
#

how can i get the time an embed was sent within a button class?

slate swan
#

you mean the message was sent?

#

!d discord.Message.created_at

unkempt canyonBOT
left dew
#

but how’d i use message within a button class

slate swan
#

what you mean by that?

left dew
#

so when a user clicks a button it send and embed and i want the embed to contain the time the message was sent

slate swan
#

you talking about embed timestamp?

left dew
#

yes

slate swan
#

!d discord.Embed

sick birch
unkempt canyonBOT
#

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

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

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

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
slate swan
#

pass timestamp kwarg^

left dew
#

ok ty

sick birch
#

I believe embed timestamps adjust themselves to the viewer's timezone (?)

slate swan
#

!d discord.Embed.timestamp

unkempt canyonBOT
#

The timestamp of the embed content. This is an aware datetime. If a naive datetime is passed, it is converted to an aware datetime with the local timezone.

torn solar
#
    channel = interaction.channel
    embed = discord.Embed(title="Closing Confirmation", color=cb_color, description="\nTo confirm closing this ticket, react with ✅. Otherwise react with ❌\n")
    embed.set_footer(text="Requested by " + interaction.user.name)
    confirm_close = Button(label="✅ Confirm", style=discord.ButtonStyle.gray)
    cancel_close = Button(label="❌ Cancel", style=discord.ButtonStyle.gray)
    view = View(timeout=None)
    view.add_item(confirm_close)
    view.add_item(cancel_close)
    message = await interaction.response.send_message(embed=embed, view=view)
    
    async def confirm_callback(interaction):
        await channel.delete()
        
    async def cancel_callback(interaction):
        await message.delete_original_response()
        
    cancel_close.callback = cancel_callback
    confirm_close.callback = confirm_callback```
#

The cancel_callback isnt working, it says Nonetype has no attribute delete_originial_response()

ornate sapphire
#

I need help

#

like rn... its really easy tho

#

I need to make my bot say a message.author.user

upbeat ice
#

!d discord.Member.mention

unkempt canyonBOT
ornate sapphire
# upbeat ice ?

im trying to make an embed

embed=discord.Embed(title=f"{message.author.user} etc", descirption="etc", color=discord.Color.purple())```
#

its not working tho

upbeat ice
#

what exactly do you want the title to do

#

there is no author.user

#

you could do message.author.name or message.user.display_name

short steppe
upbeat ice
#

i thought it just didnt ping

ornate sapphire
#

just his user

#

also can I do for the discord.Color.a_hex_code

full lily
#

hey guys

short steppe
short steppe
ornate sapphire
#

ok

#
embed=discord.Embed(title=f"{message.author.name} etc", descirption="etc", color=discord.Color.purple())```
#

would this work?

upbeat ice
#

try it

ornate sapphire
#

ya

#

ik fixed it a while ago

naive briar
short steppe
ornate sapphire
upbeat ice
#

use mention

short steppe
ornate sapphire
unkempt canyonBOT
#
I'm sorry Dave, I'm afraid I can't do that.

No documentation found for the requested symbol.

sick birch
#

Oh I'm dumb

#

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

There we are

thorn grove
#

how could i remove a role from a user that removed a reaction on on_raw_reaction_removed?

#
async def on_raw_reaction_remove(reaction):
  if reaction.channel_id == 1129756575175819324:
      verified_role = get(client.get_guild(reaction.guild_id).roles,name="Melon seedlings")

i have this but idk how to get the user that removed the role

vocal snow
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.
vocal snow
#

check there for the attributes of your reaction parameter

copper gulch
#

anyone knows the docs for the slash commands in discord.py?

rugged shadow
turbid condor
lean harbor
#

How would you make it that any arguments passed to the bot or if the bot is in a command parameter (E.g Send_Money) it just returns the commands without the command going through

left dew
#

how do i disable a dropdown menu after it has been interacted with?

naive briar
#

It depends on your preference, but my bias says discord.py

timber wren
#

any idea how I can mention such commands in normal messages aswell as in embeds??

naive briar
buoyant quail
#

</tag:1079848585027399791>

timber wren
buoyant quail
distant python
naive briar
#

</slashname:id>

timber wren
distant python
timber wren
#

id?! tf is that ong 😭

#

i am living under the rock

distant python
#

@timber wren

timber wren
#

nooo

timber wren
#

i am talking about mentioning slash commands

#

but how do I get the id of the slash command?

distant python
buoyant quail
#

!d discord.app_commands.AppCommand.mention

unkempt canyonBOT
timber wren
buoyant quail
distant python
timber wren
#

yea i did

buoyant quail
timber wren
distant python
#

"mention such commands"

timber wren
#

brother take a break, go rest youve been koding too long

#

yea wdyt?

buoyant quail
distant python
#

oh you mean like /alert

timber wren
#

nvm @distant python i got it

#

hey uh @buoyant quail can I

slash_command.mention(name = name)
#

i dont- think it is working that way

#

kinda confused in here

buoyant quail
#

Actually i don't see how do you retrieve AppCommand object in dpy, i see only just Command which has no needed attrs
Use mention by id

formal basin
#
counter = 0

@client.tree.command(name="counter", description="count up using a button")
async def counter(interaction: discord.Interaction):
  countbutton = Button(label="count",  style=discord.ButtonStyle.primary)
  view = View()
  view.add_item(countbutton)
  global counter
  counter = 0
  await interaction.response.send_message(f"{counter}", view=view)
          
  async def button_callback(interaction):
     global counter
     counter += 1
     response = await interaction.original_response()
     await response.edit(content=f"{counter}", view=view)
     
  countbutton.callback = button_callback
``` im making a button that everytime you press the number goes up

but I get this error

```Traceback (most recent call last):
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/ui/view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "/Users/zagzag/vscode/zagzag/zagzag.py", line 89, in button_callback
    response = await interaction.original_response()
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/interactions.py", line 397, in original_response
    data = await adapter.get_original_interaction_response(
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/webhook/async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
buoyant quail
#

You didn't respond anything, so there is no original response
You want interaction.message maybe

formal basin
# buoyant quail You didn't respond anything, so there is no original response You want `interact...

ok I fixed it it had to be in the command function and not the button function but every time its clicked it says the interaction failed even though it worked

counter = 0

@client.tree.command(name="counter", description="count up using a button")
async def counter(interaction: discord.Interaction):
  countbutton = Button(label="count",  style=discord.ButtonStyle.primary)
  view = View()
  view.add_item(countbutton)
  global counter
  counter = 0
  await interaction.response.send_message(f"{counter}", view=view)
  response = await interaction.original_response()
          
  async def button_callback(interaction):
     global counter
     counter += 1
     await response.edit(content=f"{counter}", view=view)
     
  countbutton.callback = button_callback
buoyant quail
#

Because editing some message is not a response to interaction

#

You can defer it if you don't want to send anything

formal basin
#

ok

naive briar
unkempt canyonBOT
#

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

Responds to this interaction by editing the original message of a component or modal interaction.
buoyant quail
#

But sill true that editing some message is not a response 😅

slate swan
#

it sends a web request when interacted with, so still a response

sick coyote
#

i have a selection menu, how can i disable it in the callback?

thin raft
slate swan
#

!d discord.ui.Select.disabled

unkempt canyonBOT
sick coyote
slate swan
#

code?

#

in callback you already get the select object

#

unless you are not using decorators

sick coyote
#
                async def callback(self, interaction: Interaction):
                    giveaway_json["boosted_roles"] = self.values
                    self.disabled = True
                    await interaction.response.edit_message(view=self)
#

this is my code

slate swan
#

where is that?

#

in what class

sick coyote
#

in the ui.Select class

slate swan
#

i belive you are using wrong method to edit the message

#

!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 "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.
sick coyote
#

ill try this

#

payload["components"] = view.to_components()
AttributeError: 'PERCENTAGE_DD' object has no attribute 'to_components'

still the same error

naive briar
#

You need to put it in a view first

north kiln
#

!d itertools.combinations

unkempt canyonBOT
#

itertools.combinations(iterable, r)```
Return *r* length subsequences of elements from the input *iterable*.

The combination tuples are emitted in lexicographic ordering according to the order of the input *iterable*. So, if the input *iterable* is sorted, the output tuples will be produced in sorted order.

Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeated values in each combination.

Roughly equivalent to:
left dew
#

howd i delete the embed a button is attatched to?

#

when it is clicked

slate swan
#

!d discord.Message.delete

unkempt canyonBOT
#

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

Deletes the message.

Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages").

Changed in version 1.1: Added the new `delay` keyword-only parameter.
left dew
#

await delete(embed..)?

naive briar
#

I used to do that, not sure if it still works

left dew
#

uh

#

i was gonna do m = await message.reply(embed=suc_embed, view=order())

#

then

#

await m.delete() in the button class but i cant access m

naive briar
#

!d discord.Interaction.delete_original_response

unkempt canyonBOT
#

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

Deletes the original interaction response message.

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

oh that would work

#

would it be orginal_response or original_message?

naive briar
#

What

left dew
#

would it be await delete_original_response() or await delete_original_message()

naive briar
#

Are you not using discord.py? Because that's a weird question since I just wrote delete_original_response

left dew
#

i know but original_message just makes more sense

#

nvmm

full lily
naive briar
#

!traceback and your code

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

potent spear
left dew
#
Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\Administrator\Desktop\alon_order\main.py", line 1513, in button_callback2
    await interaction.delete_original_response()
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 506, in delete_original_response
    await func
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook```

```py
class continue_order(discord.ui.View): # interaction_1st, main ticket button
    def __init__(self):
        super().__init__(timeout=None)
    @discord.ui.button(label="Proceed", style=discord.ButtonStyle.green, custom_id="continue_order2")
    async def button_callback1(self, button, interaction:discord.Interaction):
      for child in self.children:
          child.disabled = True

    @discord.ui.button(label="Redo ", style=discord.ButtonStyle.red, custom_id="continue_order3")
    async def button_callback2(self, button, interaction:discord.Interaction):
      for child in self.children:
        child.disabled = True
        await interaction.delete_original_response()```
naive briar
#

You can only call it once since it will delete the message that the component (view) is attached to

left dew
#

oh shoot its in the loop

#

thats unintentional

#

ok i mved it out the loop and still get the same error

naive briar
#

Are you sure it's the same?

left dew
#

same what?

naive briar
#

As the previous error you sent

left dew
#

yes

#

Unkown Webhook

buoyant quail
#

await interaction.message.delete() works \

left dew
eternal ether
#

how to disable allow command from pm(DM) ? i tried this one but failed ,
,

  if (message.author == bot.user) and (str(message.guild) == "None"):
    return
  else:
    await bot.process_commands(message)
#

this one also not working

message.guild is None 
naive briar
#

What do you mean by not working

eternal ether
#

it allows commands from dm

#

i wanna disable that

naive briar
#

Can you show your code

eternal ether
#
@bot.event
async def on_message(message):
  if (message.author == bot.user) and (str(message.guild) == "None"):
    return
  else:
    await bot.process_commands(message)
naive briar
slate swan
naive briar
#

Since even if the member.guild is None, if the message author isn't the bot, the and statement will make your conditions ends in False

eternal ether
#

i tried to check is it problem of string, because it returns as None but is it None none or string none

slate swan
#

message.guild is None

naive briar
#

!d or - try this instead of and

unkempt canyonBOT
#
or

6.11. Boolean operations


or_test  ::=  and_test | or_test "or" and_test
and_test ::=  not_test | and_test "and" not_test
not_test ::=  comparison | "not" not_test
``` In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: `False`, `None`, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a `__bool__()` method.

The operator [`not`](https://docs.python.org/3/reference/expressions.html#not) yields `True` if its argument is false, `False` otherwise.
eternal ether
#

does python works diffrent 😮 i didnt know it , i thought its double check

naive briar
#

What works different

eternal ether
#

in js or php and works as double check

#

if X returns true checks Y if its true too it executes

naive briar
#

!d and

#

It's the same

buoyant quail
naive briar
#

!e

print(False and False)
print(False and True)
print(True and True)
unkempt canyonBOT
#

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

001 | False
002 | False
003 | True
eternal ether
#

oke more simple question how to disable DM commands 🙂

#

nvm i changed my code

elif message.guild is not None:
    await bot.process_commands(message)
slate swan
#

!d discord.ext.commands.guild_only Also exists if you only want this for specific commands

unkempt canyonBOT
#

@discord.ext.commands.guild_only()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.

This check raises a special exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

If used on hybrid commands, this will be equivalent to the [`discord.app_commands.guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only "discord.app_commands.guild_only") decorator. In an unsupported context, such as a subcommand, this will still fallback to applying the check.
eternal ether
#

👍

young dagger
#

Do I need to reset the color back to the default?

    async def on_ready(self):
        total_members = sum([guild.member_count for guild in client.guilds])
        print('\u001b[31m' + f'Logged in as: {client.user} (ID: {client.user.id})' + '\u001b[0m')
        print('\u001b[31m' + f'Connected to {len(client.guilds)} servers' + '\u001b[0m')
        print('\u001b[31m' + f'Serving {total_members} members' + '\u001b[0m')
        print('\u001b[32m' + 'Bot is ready!' + '\u001b[0m')
        print('\u001b[31m' + '------------------------------' + '\u001b[0m')```
slate swan
young dagger
slate swan
#

!pypi colorama

unkempt canyonBOT
young dagger
#

Oh fancy

#

Thanks

eternal ether
#

i am trying to get command names and descriptions , but when i parse name into description it gives error , when i type manually it works..

My Code :

for command in self.bot.commands:          
        pkt = str(command).strip()
        print(pkt)
        print(self.bot.get_command(pkt).description)   
#Gives Error because get_command says its None but its not actually

Working One:

print(self.bot.get_command("ping").description)

Does anyone knows what is wrong 🤔 There is not enough info about custom help commands (which is im trying to do) in API

eternal ether
#

my commands

#

2023-07-16 23:15:00 INFO loggers Got command help from bybatu in bot
help
update
laws
status
mod
restart
ping

sick birch
eternal ether
#

get_command brings me description

#

i want descriptions + command names

sick birch
eternal ether
#

it gives error on that , i dunno why

sick birch
#

What error?

eternal ether
#

hold on let me show output

#

well 🤔 it worked now probably i did some typing errors

#
Shows the bot's latency.
Shows list of commands
Update the law and map.

Shows recent laws
Shows the status of the services working on background
Add a mod to the bot
#

@sick birch thaanks

sick birch
copper gulch
#

anyone here using replit?, how do I import a file(.py) from a different folder?

#

nvm got it

#

anyone knows the doc link for the discord.py buttons?

#

for slash commands?

copper gulch
#

thanks

sick birch
#

@copper gulch you don't need to use that, discord.py has built in support for slash commands and buttons

copper gulch
#

eh?

#

wait lemme check

#

is it this one?

sick birch
copper gulch
#

thank you thank you

torn solar
#
    channel = interaction.channel
    embed = discord.Embed(title="Closing Confirmation", color=cb_color, description="\nTo confirm closing this ticket, react with ✅. Otherwise react with ❌\n")
    embed.set_footer(text="Requested by " + interaction.user.name)
    confirm_close = Button(label="✅ Confirm", style=discord.ButtonStyle.gray)
    cancel_close = Button(label="❌ Cancel", style=discord.ButtonStyle.gray)
    view = View(timeout=None)
    view.add_item(confirm_close)
    view.add_item(cancel_close)
    message = await interaction.response.send_message(embed=embed, view=view)
    
    async def confirm_callback(interaction):
        await channel.delete()
        
    async def cancel_callback(interaction):
        await message.delete_original_response()
        
    cancel_close.callback = cancel_callback
    confirm_close.callback = confirm_callback```
#

The cancel_callback isnt working, it says Nonetype has no attribute delete_originial_response()

faint rapids
shrewd apex
#

u won't be able to run a gpt model in replit

#

replit is underpowered for that

abstract kindle
#

Heyo, a while ago, when I would do cntrl^C on my discord bot, it would stop immediately. I started using Botbase from pydis_core and a couple of other things, and now it takes a while for the program to terminate. Any ideas why?

torn solar
#

@discord.ui.select(label="Checking Account", value="01", description="Talk to a representative about what a checking account offers.", custom_id="ticket_checking")
It says select got an unexpected keyword argument 'label'

slate swan
#

!d discord.ui.Select

unkempt canyonBOT
#

class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu with a list of custom options. This is represented to the user as a dropdown menu.

New in version 2.0.
slate swan
#

cause select does not have label

torn solar
#

yeah im dumb

torn solar
#

!paste

#

its not doing anything when the option is selected

naive briar
#

The select.values doesn't return the selected options' label, but their values

#

It's in the attribute's name

torn solar
#

so use the value and not the label?

naive briar
#

Yes??

torn solar
#

ok sorry some stack overflow post used the label same way i was

naive briar
#

Not every SO answer can be accurate

#

Or are you reading the question and not answers

torn solar
#

also @naive briar while your here since your so much help

#

why does it say interaction failed when it worked?

torn solar
#
async def on_member_join(member):
    guild = member.guild
    role = discord.utils.get(guild.roles, name="Customer")
    await member.add_roles(roles=role)```
#

does anyone know why it isnt giving the member the role?

slate swan
#

Dont pass it as keyword

slate swan
slow fog
#

thought only bots can do it

slate swan
#

the new discord markdown feature allows normal users to do so

#

its rolling out slowly*

plucky sun
#

how to edit haidisql in table CREATE code:

#

And I want to put this:
CREATE TABLE bans (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id VARCHAR(255),
username VARCHAR(255)
);

#

@slow fog

slow fog
#

i don't know anything about "haidisql"

plucky sun
#

And do you know how to connect to ban command to save information ?

vale wing
vale wing
vale wing
unkempt canyonBOT
#

@languid wagon :white_check_mark: Your 3.11 eval job has completed with return code 0.

DiscordFlag.HOUSE_BALANCE, DiscordFlag.ACTIVE_DEVELOPER
sharp whale
#
async def ticket_callback(interaction):
    guild = interaction.guild
    Moderator_role = guild.get_role(config.MODERATOR_ROLE)
    overwrites = {
        guild.default_role: discord.PermissionOverwrite(view_channel=False),
        interaction.user: discord.PermissionOverwrite(view_channel=True),
        Moderator_role: discord.PermissionOverwrite(view_channel=True)
    }
    minecraftemojiID = "1127972711193391267"
    discordemojiid = "1127973464179998780"
    
    discordemoji = await interaction.guild.fetch_emoji(discordemojiid)
    minecraftemoji = await interaction.guild.fetch_emoji(minecraftemojiID)
    selectmenu = ui.Select(placeholder="Select a platform", options=[
        discord.SelectOption(
            label= "Minecraft",
            value="01",
            emoji = minecraftemoji
        ),
        discord.SelectOption(
            label= "Discord",
            value="02",
            emoji = discordemoji
        )
    ])
    view = ui.View(timeout=None)
    view.add_item(selectmenu)
    await interaction.response.send_message("Select a platform", view=view)
    async def selectmenu_callback(interaction):
        if selectmenu.values[0] == "01":
            category = discord.utils.get(guild.categories, id=1130129162489827389)
            channel = await guild.create_text_channel(f"ticket-{interaction.user.display_name}", category=category, overwrites=overwrites)
            await interaction.response.send_message("Opened a ticket", ephemeral=True)
    selectmenu.callback = selectmenu_callback```
#

When i select the minecraft select option, it says the "opened ticket" message but it isn't creating the channel

#

where's the problem???

left stirrup
#

Is it possible to get the python discord bot @unkempt canyon to my own server?

slate swan
unkempt canyonBOT
#

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

Retrieves a custom [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji") from the guild.

Note

This method is an API call. For general usage, consider iterating over [`emojis`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.emojis "discord.Guild.emojis") instead.

Changed in version 2.0: `emoji_id` parameter is now positional-only.
sharp whale
#

emoji works

slate swan
#

look at the docs (especially at the types)

sharp whale
#

._.

slate swan
rugged shadow
sharp whale
rugged shadow
#

!src

unkempt canyonBOT
left stirrup
sharp whale
#

i used interaction.guild.fetch_emoji()

rugged shadow
slate swan
slate swan
sharp whale
sharp whale
slate swan
slate swan
#

if selectmenu.values[0] == "01": this one

sharp whale
sharp whale
slate swan
sharp whale
#

oh

slate swan
#

then everything under it is not ran

#

so the channel is not created

sharp whale
#

but its sending the message

#

so it means that the if statement is running