#discord-bots

1 messages ยท Page 114 of 1

obtuse blaze
#

my problem is always using a = 0
a +=1

#

if it makes sense

shrewd apex
#

i saw a connection to db.db in the function pithink

obtuse blaze
#

oh ye

#

but it was told to me I always need to open them and close inside commands etc

#

for security purposes

shrewd apex
#

nah

#

use enumerate for the a = 0 and +1

#

!d enumerate

unkempt canyonBOT
#

enumerate(iterable, start=0)```
Return an enumerate object. *iterable* must be a sequence, an [iterator](https://docs.python.org/3/glossary.html#term-iterator), or some other object which supports iteration. The [`__next__()`](https://docs.python.org/3/library/stdtypes.html#iterator.__next__ "iterator.__next__") method of the iterator returned by [`enumerate()`](https://docs.python.org/3/library/functions.html#enumerate "enumerate") returns a tuple containing a count (from *start* which defaults to 0) and the values obtained from iterating over *iterable*.

```py
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
```  Equivalent to...
shrewd apex
lucid galleon
#

any help?

obtuse blaze
shrewd apex
#

just a sec lemme check docs i have used asyncpg and aiomysql not sure abt aiosqlite lemme check

#

too less context to find out

lucid galleon
shrewd apex
#

send more code ducky_wizard

lucid galleon
#

ok

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


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

@bot.command(name="ping")
async def test_msg(ctx):
    await ctx.send("pong")

bot.run(os.getenv("TOKEN"))
obtuse blaze
#

btw this line

await con.execute("UPDATE character_items SET item_quantity = item_quantity - ? WHERE item_ID = ? AND character_ID = ?",(int(quantity_item[a][a] * int(self.quantity.value[0])),quantity_item[a][a+1],interaction.user.id,))```
is not commiting for some reason the values that its sending is 10,5,id 
all matches on db but still doesn't update ![ThonkSpin](https://cdn.discordapp.com/emojis/460087594865131531.webp?size=128 "ThonkSpin")
shrewd apex
lucid galleon
#

yup!

#

This one is perfectly working```
@bot.event
async def on_message(message):
if message.author == bot.user:
return

if message.content.startswith('hello'):
    await message.channel.send('Hello!')
shrewd apex
#

bru

#

add await bot.process_commands(message)

#

last line of the on_message event

chilly dove
#

or change event to listen

obtuse blaze
#

thats the problem

#

there is no error

shrewd apex
#

is this inside some view? and did u use start method to start the bot with no logger setup?

obtuse blaze
#

inside modal

#

but its strange bcs all other queries above work

shrewd apex
#

definitely some error

#

add it in a try except and print

#

and setup a logger

#

coz on_command_error dosent catch interaction errors iirc

lucid galleon
chilly dove
#

did you add () at the end of listen?

shrewd apex
#

can u show me ur on message event

obtuse blaze
# shrewd apex definitely some error
 for i in quantity_item:
            try:
              await con.execute("UPDATE character_items SET item_quantity = item_quantity - ? WHERE item_ID = ? AND character_ID = ?",(quantity_item[a][a] * int(self.quantity.value[0]),quantity_item[a][a+1],interaction.user.id,))
              await con.execute("INSERT INTO character_items (character_id,item_ID,item_quantity) VALUES (?,?,?) ON CONFLICT (character_ID,item_ID) DO UPDATE SET item_quantity = item_quantity + ?",(interaction.user.id,quantity_item[a][a+1],int(quantity_item[a][a]) * int(self.quantity.value[0]),int(quantity_item[a][a]) * int(self.quantity.value[0]),))
              await con.commit()
            except:
                raise Exception("An error occured while crafting!")

I did this try catch rq and still no error

shrewd apex
lucid galleon
shrewd apex
obtuse blaze
shrewd apex
#

check ur db again

obtuse blaze
#

db not updating it should add item to inv not adding nor removing

shrewd apex
#

or use some arbitrary values instead to check

shrewd apex
obtuse blaze
#

imma put a checker under commit to check if it reaches tehre

#

it did ThonkSpin

#

found problem

#

its second query

#

it does not raise error prob bcs it has ON Conflict

shrewd apex
#

fair enough

obtuse blaze
#

now trynna find the problem anyways tysm asher bow

shrewd apex
#

๐Ÿ‘

shrewd apex
obtuse blaze
#

mhm I found problem, a wrong value was being passed so it was not doing anything

shrewd apex
#

๐Ÿ’

slate swan
#

hello i have a problem and i cant resolve it

#

can someone help me ?

shrewd apex
#

if u put the actual question before a request for help u would have a better chance i suppose

slate swan
#

i cant start my bot

chilly dove
#

gotta reset your token now

shrewd apex
#

open ur discord go to applications page

slate swan
#

yes np

shrewd apex
#

open ur bot

slate swan
#

i just cretaed it for the screen

shrewd apex
#

go to bot settings page

slate swan
#

and next

shrewd apex
#

enable the intents

#

the little slider buttons

#

and save ur settings

slate swan
#

here ?

shrewd apex
#

yep

slate swan
#

i can put the 3?

#

or just one

chilly dove
#

probably enable all of them

#

then you can change default to all

slate swan
slate swan
chilly dove
#

well there you go your bots online

slate swan
#

yes but it doesnt printed in the terminal

#

'on'

chilly dove
#

you didnt put a @

#

it needs to be @bot

slate swan
#

nvm i stupid

#

i just realized

#

thanks

bright wedge
#
rand_colors = ["0x"+''.join([random.choice('ABCDEF0123456789') for i in range(6)])]

await role.edit(colour=rand_colors[0])

Error:
payload['color'] = colour.value AttributeError: 'str' object has no attribute 'value'

sick birch
#

!d discord.Colour

unkempt canyonBOT
#

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

There is an alias for this called Color...
sick birch
#

British people be like

bright wedge
#

huh?

sick birch
#

!d discord.Colour.random @bright wedge

unkempt canyonBOT
#

classmethod random(*, seed=None)```
A factory method that returns a [`Colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour "discord.Colour") with a random hue.

Note

The random algorithm works by choosing a colour with a random hue but with maxed out saturation and value.

New in version 1.6.
sick birch
#

There's a built in random method for you

bright wedge
#

oh

shrewd apex
#

anyone got any good leader board image template?

honest shoal
shrewd apex
#

umm 10 around is fine

#

5 is also ok

bright wedge
honest shoal
#

and this

shrewd apex
#

nice but are these under mit or cc license pithink

honest shoal
#

free license

shrewd apex
#

oh fine then thanks

honest shoal
slate swan
#

Is it possible to make the bot answer a hello without the person having put an prefix in front of it?

slate swan
#

ill look in the documentation

honest shoal
#

!d discord.on_message

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.

This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.

Warning

Your botโ€™s own messages and private messages are sent through this event. This can lead cases of โ€˜recursionโ€™ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
gritty canopy
sick birch
gritty canopy
#

thats what i use

sick birch
#

First step is to figure out what you're using

sick birch
gritty canopy
shrewd apex
#

pycord 90% sure

sick birch
#

What library did you use as you were coding the bot?

shrewd apex
#

i think its cloned from a git repo

sick birch
#

Pycord.. discordpy... disnake..?

gritty canopy
#

i bought the bot but they was using visual studio to code it all

shrewd apex
#

...

#

hmm boostbot ๐Ÿ‘€

#

plus the whole situation looks sus

sick birch
#

No offense I mean

gritty canopy
#

nah the guy who i bought it from like it works for him but not for me

sick birch
#

Generally buying discord bots are scams

shrewd apex
#

^^

gritty canopy
#

thats the line thats erord

sick birch
#

But the cause of the issue is probably a pycord and discord.py conflicting install

shrewd apex
#

first of all u need to figure out what module is being used second if u have the module installed in your env

sick birch
#

Not sure why the person making the bot decided to use a subpar library like pycord.. but it's there

shrewd apex
#

i mean i never knew people were ready to pay for bots ๐Ÿ‘€

sick birch
#

Me neither lol

#

I suppose that's a thing people do

slate swan
sick birch
#

Well not rhythm I guess

#

< insert popular discord bot here >

slate swan
#

wdym? those bots only do specific things

sick birch
#

They're meant to be general purpose

#

In fact YAGPDB stands for "yet another general purpose discord bot"

slate swan
#

to a certain extent yes

sick birch
#

The only reason I can think of people paying for their bots is to have it custom tailored to a very specific usecase

#

For all else you have your generic popular discord bot

slate swan
#

how can i check if the author is in a tempchannel already if they try to override the tempchannel settings with a vc which is already a tempchannel
is it necessary i commit the channel id and all in db, coz i dont really want to do that

chilly dove
#

depending on how long the temp channel lasts you could store the id in memory or have a naming convention in discord that identifies the channel

shrewd apex
slate swan
#

just the name is nukebot, it doesnt really nuke servers

shrewd apex
#

oops my bad

slate swan
slate swan
#

coz the tempchannel might last due to user's choice, and idk if any method exists in pycord to check if its a tempchannel or not

slate swan
chilly dove
#

i dont think discord has any sort of temp channel but they do have threads which you can use like one other then that you need a way to identify them

slate swan
#

yea i was about to say there is no such thing as a temp channel w discord api

slate swan
slate swan
slate swan
#

hello, I need help with a command.
let's say I create a recipe command I create a list of recipes 'pasta', 'cake' and with my bot discord when the order I give the recipe of the dish requested for example I want the recipe of the cake I do >recipe cake and it gives me the ingredients of the recipe and the same for >pasta but with the ingredients of the pasta and not the cake

#

use sub cmds

#

what does it means

chilly dove
#

thats going into more general python tho then library

slate swan
#

I don't understand can you redirect me to the documentation or a video?

slate swan
chilly dove
#

well they can ask for help in the normal help channels if they are confused

meager chasm
chilly dove
#

more efficient both on memory and processing

meager chasm
#

How tho

#

Dict is just str: str mapping

#

Hashing str is not costly

chilly dove
#

you could but then you would be repeating ingredients per recipe

#

its also more concise and easier to understand with bitmask

#

at least code wise not the result without processing

slate swan
#

!dcosw

#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

slate swan
#
@bot.command()
async def mute(ctx, member: discord.Member, muted : time = None, *, reason=None):
  muted = discord.utils.get(ctx.guild.roles, id=1019274735516909578)
  time = humanfriendly.parse_timespan(time)
  member = ctx.author.mention
  if member == None:
        await ctx.send("Please please mention a member you want to mute")
  elif time == None:
        await ctx.send("Please mention the time you want the member to be muted!")
  elif reason == None:
        reason = "None"
  else:
        await member.add_roles(muted)
        await member.up
        await ctx.send(f"{member.mention} was muted by {ctx.author.mention} for: {reason}")```

Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\PC\Desktop\Among Us IL Bot\main.py", line 120, in on_message_edit
async def mute(ctx, member:discord.Member, time, *, reason):
AttributeError: module 'datetime' has no attribute 'now'
PS C:\Users\PC\Desktop\Among Us IL Bot> py main.py
2022-10-25 21:43:18 INFO discord.client logging in using static token
Among Us IL is online!
Synced 0 command(s)
2022-10-25 21:43:20 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 4bf55f17b43eed189d19fe473d2764b8).
2022-10-25 21:43:29 ERROR discord.client Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\converter.py", line 1214, in _actual_conversion
return converter(argument)
TypeError: time.time() takes no arguments (1 given)

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

Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\PC\Desktop\Among Us IL Bot\main.py", line 361, in on_command_error
raise error
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 978, in invoke
await self.prepare(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 895, in prepare
await self._parse_arguments(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 802, in _parse_arguments
transformed = await self.transform(ctx, param, attachments)
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 672, in transform
return await run_converters(ctx, converter, argument, param) # type: ignore
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\converter.py", line 1323, in run_converters
return await _actual_conversion(ctx, converter, argument, param)
File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\converter.py", line 1223, in _actual_conversion
raise BadArgument(f'Converting to "{name}" failed for parameter "{param.name}".') from exc
discord.ext.commands.errors.BadArgument: Converting to "time" failed for parameter "muted".```

vocal snow
#

why are you typehinting muted to time? What is time?

sick birch
vocal snow
#

haha out of context python is very philosophical

languid sandal
#

Hi, is it better a task loop with a minute delay or a while loop with an asyncio.sleep(60)?

vocal snow
#

task loop will give you the builtin control features such as being able to stop it and stuff

languid sandal
#

okay ^^ ty

sick birch
#

Also reconnect logic is handled for you

astral ether
#

hello I am looking for how to do so that when my bot sends a message, I answer it, and I would like my bot to be able to retrieve my response

nocturne cypress
#

Good Morning

#

i have returned to ask more cringe/noob help with python on my discord bot that was running perfectly fine and now something happend and its dead

slate swan
tawdry mural
#

Hi id like to know how do I make the bot's errors that appear in the terminal to be sent to a discord channel of choiceCatHmm

nocturne cypress
#

but both kept giving me same error

primal token
unkempt canyonBOT
#

discord.ext.commands.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.

A default one is provided ([`Bot.on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.on_command_error "discord.ext.commands.Bot.on_command_error")).
tawdry mural
tawdry mural
#

Hmm did i do this right? because errors that occur in the terminal isnt appearing in the channel

@commands.Cog.listener()
  async def on_command_error(self, ctx, error):
    channel = self.bot.get_channel(removedid)
    await discord.ext.commands.on_command_error(ctx, error, channel)
    embed=discord.Embed(title="Error",
                        description=f"{error}",
                        color=discord.Color.orange())
    await ctx.send(embed=embed)```
primal token
tawdry mural
primal token
tawdry mural
#

thing is i want to show the errors because the bot is hosted in a virtual machine and i cannot always be there to check on the console, thus i want it to be sent in a specific channel

primal token
#

Well, on_command_error can only catch errors from context based commands

slate swan
#

why is my discord bot sending 5x the amount that its suppost to

#

and it runs when i dont have any terminals open

winged coral
#

It's running in other places

#

In the background somehow

round lily
jaunty musk
#

Do I only need one of these to get commands working?

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

oh I guess I only need commands and not client.

alpine cove
#

remove client

alpine cove
jaunty musk
#

anyone know why, when I do emoji = await bot.wait_for("message", check=check, timeout=60) it's coming back as \ud83e\udee7 and how can I get it to save as :bubbles:

hushed galleon
jaunty musk
#

When I reply with ๐Ÿซง it comes out as that weird unicode...

#

is there a proper way to have a wait for message get :bubbles: ?

hushed galleon
hushed galleon
#

you can either find some name mapping discord uses if that exists, create your own, or use something close enough like the builtin module unicodedata to get the emoji's name

#

!e py import unicodedata emoji = '\U0001fae7' print(unicodedata.name(emoji))

unkempt canyonBOT
#

@hushed galleon :white_check_mark: Your 3.11 eval job has completed with return code 0.

BUBBLES
sick birch
#

discord.EmojiConverter might work, don't quote me on it though

hushed galleon
#

nah thats for custom emoji only, PartialEmojiConverter too (annoyingly)

#

i had to use a pypi package like emoji and a custom converter to check if a character(s) was standard emoji

#

hmm emoji actually has its own localizations, but it doesnt seem to match the ones in discord (at least for one emoji that i checked)

faint mural
#

works with twemoji_parser

jaunty musk
#
async def addrole(ctx):
    await ctx.send("What is the role name?")
    def check(m):
        return m.author == ctx.author and m.channel == ctx.channel
    msg = await bot.wait_for('message', check=check, timeout=60)
    role_name = msg.content
    await ctx.send("What is the emoji?")
    msg = await bot.wait_for('message', check=check, timeout=60)
    emoji = msg.content
    await ctx.send("What is the description?")
    msg = await bot.wait_for('message', check=check, timeout=60)
    description = msg.content
    ## check if role_name is a valid string
    if not isinstance(role_name, str):
        await ctx.send("Role name must be a string.")
        return
    ## check if role_name is already in use
    with open(configFileLocation, "r") as configFile:
        configData = json.load(configFile)
        roles = configData["roles"]
    for role in roles:
        if role == role_name:
            await ctx.send("Role name is already in use.")
            return
    ## check if emoji is a valid string
    if not isinstance(emoji, str):
        await ctx.send("Emoji must be a string.")
        return
    ## check if description is a valid string
    if not isinstance(description, str):
        await ctx.send("Description must be a string.")
        return
    ## append to roles array in config/config.json
    with open(configFileLocation, "r") as configFile:
        configData = json.load(configFile)
        roles = configData["roles"]
    roles.append({
        "react": emoji,
        "react_id": 0,
        "role": role_name,
        "description": description,
        "role_id": 0
    })
    with open(configFileLocation, "w") as configFile:
        json.dump(configData, configFile, indent=4)
    await ctx.send("Role added.")
    await role_system()```

This is the code I'm using right now :/ still getting weird input into my json

```        {
            "react": "\ud83e\udee7",
            "react_id": 0,
            "role": "water_buddies",
            "description": "15 Min drink reminder",
            "role_id": 1034626366181748866
        }```
simple kettle
#
async def red_button_press(self, interaction : discord.Interaction, button : discord.ui.Button):
TypeError: 'Button' object is not callable
#

i keep getting that in error

#
Traceback (most recent call last):
  File "C:\Users\Nathan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 851, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "C:\Users\Nathan\Downloads\Python\GPO\test.py", line 70, in button
    button_views = red_button()
  File "C:\Users\Nathan\Downloads\Python\GPO\test.py", line 20, in __init__
    async def red_button_press(self, interaction : discord.Interaction, button : discord.ui.Button):
TypeError: 'Button' object is not callable

full error

faint mural
#

You can create a subclass with discord.ui.Button (class MyButton(discord.ui.Button)) or as shown in your example you need to use discord.ui.button

hushed galleon
simple kettle
#

im getting new error

Traceback (most recent call last):
  File "C:\Users\Nathan\Downloads\Python\GPO\test.py", line 16, in <module>
    class red_button(discord.ui.View):
  File "C:\Users\Nathan\Downloads\Python\GPO\test.py", line 21, in red_button
    async def red_button_press(self, interaction : discord.Interaction, button : discord.ui.Button):
TypeError: 'Button' object is not callable

code

class red_button(discord.ui.View):
    def __init__(self, *, timeout = 180):
        super().__init__(timeout=timeout)

    @discord.ui.Button(label="Press", style=discord.ButtonStyle.red)
    async def red_button_press(self, interaction : discord.Interaction, button : discord.ui.Button):
        await interaction.response.send_message("You pressed button")
hushed galleon
#

oh you made a typo in your decorator

#

@discord.ui.button is the correct name, lowercase b

simple kettle
#

omg

#

im so dumb

simple kettle
#
class PurgeView(discord.ui.View):
    def __init__(self, *, timeout = 180):
        super().__init__(timeout=timeout)
    @discord.ui.button(label="Delete", style=discord.ButtonStyle.red)
    async def button_press(self, interaction : discord.Interaction, button : discord.ui.Button):
            mycursor.execute(f"DROP TABLE `{interaction.guild.id}`")
            mycursor.execute(f"DROP TABLE {interaction.guild.id}_custom")
            mycursor.execute(f"DROP TABLE {interaction.guild.id}_blox")
            await interaction.response.send_message("Devil Fruit Tables successfully deleted")
            log = f"Deleted Devil Fruit Jornal from {interaction.guild.id} ({interaction.guild.name})"
            write_log(log)

how do i make it so this button only works for the person who sent the command?

sick birch
unkempt canyonBOT
#

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

A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.

This is useful to override if, for example, you want to ensure that the interaction author is a given user.

The default implementation of this returns `True`.

Note

If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.on_error "discord.ui.View.on_error") is called.
simple kettle
#

what does the slash mean

sick birch
drifting arrow
#

In discordpy to create an embed you just create it in the command itself or wherever you want embed = discord.Embed, is there an equivalent for modals?

vale wing
#

Modals are different, check examples on github repos

#

@drifting arrow

austere vale
#
#delete invite links
@bot.event
async def on_message(message):
  if message.guild is None:
    return
  discordInviteFilter = re.compile("(...)?(?:https?://)?discord(?:(?:app)?\.com/invite|\.gg)/?[a-zA-Z0-9]+/?")
  modrole=937402417069293589
  if discordInviteFilter.match(message.content) and modrole not in message.author.roles:
    await message.delete()
  await bot.process_commands(message)

this code deletes messages if they are an invite link, but it wont delete messages if it contains text + invite link. how can i change it so that if an invite link is any part of a message, it will delete it?

bright wedge
slate swan
#

What is the difference between discord.py and pycord

#

pycord is a fork of dpy

unkempt canyonBOT
#

@austere vale Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!

Our server rules can be found here: https://pythondiscord.com/pages/rules

austere vale
# bright wedge ```py https://discord.gg/ <- in message.content ```
@bot.event
async def on_message(message):
  if message.guild is None:
    return
  modrole=937402417069293589
  invitestring='dscord.gg/'
  if invitestring in message.content and modrole not in message.author.roles:
    await message.delete()
  await bot.process_commands(message)```
this works but if i (a mod) send out an invite link, it still deletes it. any idea why it might be passing the modrole check?
(also i purposefully misspelled the invitestring link so the bot doesnt delete the message)

my intents are `intents=nextcord.Intents.all())`
bright wedge
#

this is how you define the role

unkempt canyonBOT
#

@bright wedge Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!

Our server rules can be found here: https://pythondiscord.com/pages/rules

austere vale
#

that fixed it. thank you!

bright wedge
#

you are welcome!

urban trout
#

Hi

astral ether
#

hello I am looking for how to do so that when my bot sends a message, I answer it, and I would like my bot to be able to retrieve my response

placid skiff
#

!d discord.ext.commands.Bot.wait_for there are some examples if you open the doc

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
tough lance
#

global check in disnake for slash_commands?

slate swan
#

how can i update a button on click?

slate swan
#

this bot keeps deleting my message

austere vale
#

what should i put then? you can just misspell it a bit like dscord.gg

slate swan
slate swan
#

like invite/vanity

#

thats why his way of using re is better

austere vale
slate swan
#

i tried to install slash commands bit it failed

placid skiff
#

Bruh you don't need them D_D
d.py>=2.0 supports slash commands

upbeat gust
placid skiff
#

Probably lmao

slate swan
#

how can i see what version of dpyy i have ?

slate swan
upbeat gust
upbeat gust
slate swan
#

wtf

upbeat gust
#

That's not what I said

#

what do you expect

slate swan
#

?

upbeat gust
#

I told you to do something, and you did a different thing.

slate swan
#

i have 2.0.1

upbeat gust
#

good, then

slate swan
#

then what

upbeat gust
#

Follow this guide instead of the tutorial you had

slate swan
#

need i to install the new dpy version?

upbeat gust
slate swan
#

I read the GitHub but to do slash command it's not with

@slash.slash(name="name")
``` ?
upbeat gust
slate swan
#

yes but i dont understand whati havez to do now

#

it doesnt explain howto installslash commands

austere vale
#

thank youu

austere vale
# slate swan thats why his way of using re is better

but if i use that, i get this:

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\kouxi\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 502, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\kouxi\Runa\main.py", line 91, in on_message
    if discordInviteFilter in message.content and modrole not in message.author.roles:
TypeError: 'in <string>' requires string as left operand, not re.Pattern
@bot.event
async def on_message(message):
  if message.guild is None:
    return
  modrole=message.guild.get_role(937402417069293589)
  discordInviteFilter = re.compile("(...)?(?:https?://)?discord(?:(?:app)?\.com/invite|\.gg)/?[a-zA-Z0-9]+/?")
  if discordInviteFilter in message.content and modrole not in message.author.roles:
    await message.delete()
  await bot.process_commands(message)
paper sluice
#

thats not how you use a regular expression

#

you probably want discordInviteFilter.search(<string>)

whole sparrow
#

`26.10 06:11:25 [Bot] disnake.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.

Discord Developer Portal

Integrate your service with Discord โ€” whether it's a bot or a game or whatever your wildest imagination can come up with.

#
26.10 06:11:25 [Bot] disnake.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.
#

I have a bot that sends welcome message with an image wheneever a user joins, can this be the reason why my bot is being ratelimited>

#

The server is very popular on where this bot is

upbeat gust
#

Maybe before the actual error

whole sparrow
#
26.10 04:15:31 [Bot] disnake.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.
26.10 04:28:26 [Bot] Ignoring exception in on_member_join
26.10 04:28:26 [Bot] Traceback (most recent call last):
26.10 04:28:26 [Bot] File "/.local/lib/python3.9/site-packages/disnake/client.py", line 612, in _run_event
26.10 04:28:26 [Bot] await coro(*args, **kwargs)
26.10 04:28:26 [Bot] File "/cogs/listeners.py", line 77, in on_member_join
26.10 04:28:26 [Bot] await channel.send(f"Hey {member.mention}, welcome to **{member.guild.name}**",file=disnake.File(welcome_file_path))
26.10 04:28:26 [Bot] File "/.local/lib/python3.9/site-packages/disnake/abc.py", line 1523, in send
26.10 04:28:26 [Bot] data = await state.http.send_files(
26.10 04:28:26 [Bot] File "/.local/lib/python3.9/site-packages/disnake/http.py", line 401, in request
26.10 04:28:26 [Bot] raise HTTPException(response, data)
26.10 04:28:26 [Bot] disnake.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.
#

its just a repeat of this over

upbeat gust
#

You only have 3 seconds to respond.

#

Idk I don't use that lib

whole sparrow
#

For popular bots, is there a timer for the welcome message for a user?

#

Im assuming it's because too many users joined at once

upbeat gust
#

I mean it says what the problem is

#

you can't convert '%mention tach' to int

upbeat gust
#

I don't think anyone cares anwyay

#

figure out why you're trying to convert '%mention tach' to int

whole sparrow
#

It sends a custom image of the user's profile picture along with custom text with the welcome message

whole sparrow
upbeat gust
#

Your lib should be automatically slowing down

#

you need to do some real messed up stuff to get 429s

whole sparrow
#

Im using disnake

#

And not sure. it depends of course on how often user's join so its variable

upbeat gust
#

I guess you could make a queue of messages to send

#

Then send one like every few seconds inside a tasks.loop

whole sparrow
#

Yeah I was thinking of that.

upbeat gust
#

Read the error

#

it says what's wrong

slate swan
upbeat gust
#

Deferring just says "I acknowledge this interaction, I'll followup later"

slate swan
#

it should be interaction.response.send_message
defer doesn't have any arguments

upbeat gust
upbeat gust
#

Yes-

#

defer then send a follow-up

#

Then send it when you want to

#

You have 15 mins

#

what error

slate swan
whole sparrow
#

Nope, pebblehost

slate swan
#

Did you try changing ip

whole sparrow
#

Im hosting from my computer atm and it is working. but this has happened twice now

upbeat gust
whole sparrow
#

Im now adding a 1s timer to the message

whole sparrow
#

Thats why never went to a vps

#

its cheap and was easy to setup for my clients

upbeat gust
#

It's good until you really need it to do something

whole sparrow
#

But having a bad server/host lead to a 429 ratelimit?

#

How does it stop dpy from automatically stopping the message spam

upbeat gust
whole sparrow
#

yeah weird

vale wing
whole sparrow
#

$3 per month

vale wing
#

VPS on galaxygate costs the same yet provides more functionality

whole sparrow
#

Looks good, ill look into it

#

thanks

cerulean atlas
#

@unkempt canyon

primal token
#

channel is None

slate swan
primal token
lucid galleon
#

Multiple commands isn't working ```
from email import message
import os
from dotenv import load_dotenv
import discord
from discord.ext import commands

load_dotenv()

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

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

@bot.event
async def on_connect():
print(f'I am awaken {bot.user}')

@bot.event
async def on_message(message):
if message.author == bot.user:
await bot.process_commands(message)

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

@bot.command(name="ping")
async def test_msg(ctx):
await ctx.send("pong")

@bot.command(name="quote")
async def test_quote(ctx):
await ctx.send("quote")

bot.run(os.getenv("TOKEN"))

vocal snow
lucid galleon
#

ok so what to do?

vocal snow
#

do you understand what this code does

lucid galleon
vocal snow
#

...

#

I don't know how to explain this

#

this checks if the message author is the bot

#

so you're only processing commands if the author is the bot

lucid galleon
#

but i want to process my commands

vocal snow
#

you can process it after the if statement

lucid galleon
#

will it work๐Ÿค”

jagged adder
#

how would i go about ending a specific instance of a class?

lucid galleon
#

@vocal snow great it's working

jagged adder
#

if someone quits a session of my game, im doing 2-3 things. 1 is making their text channel invisible except to admins (for review purposes)

#

secondly i want to break their current game instance so it resets the game stats

#

usually i do that by either restarting bot or by deleting the channel

#

without deleting the channel tho idk how to break the players current game instance

#

oh and third is renaming the channel

lucid galleon
#

why is it showing me error?```
Exception ignored in: <function _ProactorBasePipeTransport.del at 0x000001B534007160>
Traceback (most recent call last):
File "F:\pyenv\lib\asyncio\proactor_events.py", line 116, in del
File "F:\pyenv\lib\asyncio\proactor_events.py", line 108, in close
File "F:\pyenv\lib\asyncio\base_events.py", line 751, in call_soon
File "F:\pyenv\lib\asyncio\base_events.py", line 515, in _check_closed
RuntimeError: Event loop is closed

vale wing
#

I would keep the game data inside the command and bring the host's ID into global list (I don't mean global var)

shrewd apex
#

by function i mean scope this instance is present in

ocean dragon
#

is there an implementation of decorator where u can set cooldown for command to a specific role

ocean dragon
#

also currently my bots are like this

class MyCogStaff(commands.Cog):
    def __init__(self, bot:commands.Bot) -> None:
        self.bot = bot

    @app_commands.command(name="ping")
    async def ping(self, interaction: discord.Interaction) -> None:
        await interaction.response.send_message("pong", ephemeral=True)

async def setup(bot: commands.Bot) -> None:
    await bot.add_cog(MyCogStaff(bot))
intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)
async def main():
    for _folder in os.listdir("./commands/staff/"):
        for _file in os.listdir(f"./commands/staff/{_folder}"):
            if _file.endswith(".py"):
                await bot.load_extension(f"commands.staff.{_folder}.{_file[:-3]}")

    async with bot:
        await bot.start(config.token)

if __name__ == "__main__":
    asyncio.run(main())

How can I

  1. Get the slash commands to show on discord when I type the slash /
  2. Set StaffCog commands to show only to members with staff-role
hushed galleon
# ocean dragon also currently my bots are like this ```py class MyCogStaff(commands.Cog): d...
  1. you need to sync your app commands to discord, usually done in a setup_hook or a prefix command like so: ```py
    @bot.event
    async def setup_hook():

    Synchronizes global commands:

    await bot.tree.sync()

    or for a specific guild via ID:

    await bot.tree.sync(guild=discord.Object(267624335836053506))``` 2. discord doesnt allow you to do this from the bot directly, i.e. an admin has to configure the slash command in Server Settings > Integrations to specify which roles are allowed (the closest thing you could do would be using the @app_commands.default_permissions() decorator to limit visibility based on permissions)
slate swan
#

how to send a private message with the py slash commands of discord?

hushed galleon
#

get the user from the interaction and use their send() method

slate swan
#

how get user ?

hushed galleon
#

!d discord.Interaction.user

unkempt canyonBOT
hushed galleon
#

for example: py @bot.tree.command() async def my_command(interaction: discord.Interaction): # Respond to the interaction (always required in some form) await interaction.response.send_message('Hello in this channel!') # DM the user await interaction.user.send('Hello in your DM!')

#

as usual you might get a discord.Forbidden error if the user has their DMs closed

sly hedge
#

could anyone help me figure out why I cant import that?

vale wing
#

Isn't it in ext

sly hedge
#

whaT?

vale wing
#

Nvm

#

@sly hedge do pip show discord.py

slate swan
#

Anyone know I can make my bot automatically send a message once a certain amount of messages are sent in my general chat by users

vale wing
vale wing
slate swan
sly hedge
vale wing
sly hedge
#

no

vale wing
#

Do that

sly hedge
#

aight I try

#

thanks

#

hmmm, that did not help

vale wing
#

Is there only one interpreter installed on your machine and are you using venv

velvet compass
#

Hey random question: is it possible to have a bot do prefix commands and slash commands? I'm having an issue where I enabled a basic slash command but now the previous prefixed commands do not work (the bot does not respond). I'm using nextcord and I'm fairly certain I have all of the scopes / intents enabled for both

vale wing
#

To my knowledge, discord.py supports hybrid commands, not sure about nextcord

velvet compass
#

Ah

#

Each command has its own cog currently, not sure if that makes a difference

vale wing
#

Tbh they only differ by decorators

#

And the type of ctx can either be Context or Interaction, depending on how the command was called

velvet compass
#

Right

#

I can get a basic "echo" slash command, but my previous ~ping command is no longer picked up by the bot

hushed galleon
#

i havent heard that happening before, but there's a lot of things that could go wrong for prefix commands to not work

lucid galleon
#

why is it showing me error?```
Exception ignored in: <function _ProactorBasePipeTransport.del at 0x000001B534007160>
Traceback (most recent call last):
File "F:\pyenv\lib\asyncio\proactor_events.py", line 116, in del
File "F:\pyenv\lib\asyncio\proactor_events.py", line 108, in close
File "F:\pyenv\lib\asyncio\base_events.py", line 751, in call_soon
File "F:\pyenv\lib\asyncio\base_events.py", line 515, in _check_closed
RuntimeError: Event loop is closed

hushed galleon
#

thats a bug with asyncio, you can usually ignore it

vale wing
#

In nextcord anything can go wrong

velvet compass
#

I see I see

hushed galleon
#

@velvet compass the last point wouldnt be the case right? does your prefix and slash command have different function names?

velvet compass
#

They do have different names

primal token
#

Have you loaded the cog?

velvet compass
#

Here are the cogs that get loaded:

ocean dragon
#

is there an implementation of decorator where u can set cooldown for command to a specific role

sick birch
#

Hey Brad! Fancy seeing you here

primal token
velvet compass
#

And here is where I set up the bot:

# some stuff above

intents = nextcord.Intents.default()
intents.message_content = True


class Bradbot(commands.Bot):
    """
    Bradbot core.
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.name = "Bradbot"
        self.dev_log = int(DEV_LOG)

    def add_cog(self, cog: commands.Cog) -> None:
        """
        Delegate to super to register `cog`.
        This only serves to make the info log, so that extensions don't have to.
        """
        super().add_cog(cog)
        logger.info(f"Cog loaded: {cog.qualified_name}")


bot = Bradbot(command_prefix="~", intents=intents)

#more stuff below
unkempt canyonBOT
sick birch
#

I also don't think prefix commands and slash commands should interfere unless you've set them up as hybrids?

velvet compass
#

(a lot of this is heavily inspired from @lament depot )

velvet compass
primal token
#

Can you show both of the commands?

sick birch
#

have you configured them as hybrids?

primal token
velvet compass
#

I am now wondering though, should I modify the prefix commands where I initialize them?

sick birch
hushed galleon
#

@ocean dragon what do you mean by "a specific role"? do you want the cooldown to only apply to that role? there's several different ways to design it with dpy 2.0

velvet compass
#

So some code blocks:

Ping command (prefix)

from loguru import logger
from nextcord import Embed
from nextcord.ext import commands


class Ping(commands.Cog):
    "Send an embed about the bot's ping."

    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @commands.command(name="ping")
    async def ping(self, ctx: commands.Context) -> None:
        """Ping the bot to see its latency and state."""
        logger.debug(f"Command `{ctx.invoked_with}` used by {ctx.author}.")
        embed = Embed(
            title=":ping_pong: Pong!",
            description=f"Gateway Latency: {round(self.bot.latency * 1000)}ms",
        )

        await ctx.send(embed=embed)


def setup(bot: commands.Bot) -> None:
    """Load the Ping cog."""
    bot.add_cog(Ping(bot))

New slash "echo" command:

from nextcord import slash_command, Interaction
from nextcord.ext import commands


class SlashTester(commands.Cog):
    """Testing slash command implementation."""

    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @slash_command(guild_ids=[redacted], description="Echo command")
    async def slash_echo(self, interaction: Interaction, arg: str):
        """Testing a slash echo command"""
        await interaction.response.send_message(f"{arg}")


def setup(bot: commands.Bot) -> None:
    """Load the SlashTester cog."""
    bot.add_cog(SlashTester(bot))
ocean dragon
hushed galleon
#

ah, so that would require a dynamic cooldown

#

what library and version are you using? discord.py 2.0 comes with @dynamic_cooldown()

#

and so does nextcord and disnake

paper sluice
ocean dragon
#

I'm rewriting my spaghetticode ๐Ÿคฃ

velvet compass
hushed galleon
ocean dragon
#

2.0.1

unkempt canyonBOT
#

examples/application_commands/cog_example.py line 19

@nextcord.message_command(guild_ids=[TESTING_GUILD_ID])```
hushed galleon
#

aight good

#

!d discord.ext.commands.dynamic_cooldown

unkempt canyonBOT
#

@discord.ext.commands.dynamic_cooldown(cooldown, type)```
A decorator that adds a dynamic cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")

This differs from [`cooldown()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.cooldown "discord.ext.commands.cooldown") in that it takes a function that accepts a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Cooldown "discord.app_commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.

A command can only have a single cooldown.

New in version 2.0.
hushed galleon
primal token
#

wut

hushed galleon
#

thats what you linked

sick birch
primal token
#

ahhh, yeah, sorry for the confusion

#

what an interesting namespace

velvet compass
paper sluice
primal token
velvet compass
primal token
velvet compass
hushed galleon
# hushed galleon !d discord.ext.commands.dynamic_cooldown

@ocean dragon the BucketType can be whatever you want, but for changing the cooldown you can pass a function that returns a Cooldown only if the user doesnt have your membership role, for example: ```py
def cooldown_callback(ctx):
if <user has membership role>:
return None
return app_commands.Cooldown(1, 10) # 1/10s

@bot.command()
@commands.dynamic_cooldown(cooldown_callback, commands.BucketType.member)
async def my_command(ctx):
...```

velvet compass
paper sluice
velvet compass
primal token
velvet compass
#

They are all loaded in alphabetical order

primal token
#

And the context commands work if the SlashTester cog isnt loaded?

obtuse blaze
#

I need to call a async fuction on __init__ but I can't sync its not async. So my question is how can I make __init__ async?

obtuse blaze
#

so make a class

#

put fuction in there and call class?

velvet compass
hushed galleon
#

hm nextcord's source is a bit odd, they chose to introduce the concept of cogs to discord.Client in order to implement slash commands inside them

primal token
primal token
#

because you forgot it in your constructor(__init__())

#

In this case it would be bot so add another argument

#

you forgot self in the parameters of the constructor

#

No worries๐Ÿ˜…

velvet compass
#

I'm going to chalk it up to a lag on the perms being set up on discord's side. Will come back to this later

fading marlin
#

don't sync globally

primal token
#

i'm pretty sure it shows what events get received

slate swan
#

Hey,
I'm trying to make my slash command into an prefix command.

Here is my code:

@bot.command()
async def activity(ctx, str):
activity: discord.Option(str,"Change the bot activity",required=True):
if not isAdmin(ctx):
embed = discord.Embed( description="Access Denied: You are not an admin.",
color=0x3dad5b)
return await ctx.send(embed=embed)
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{activity}"))
embed = discord.Embed(description=f"Bot activity changed to {activity}",
color=0x3dad5b)
await ctx.send(embed=embed)

I'm trying to make it into $. Right now, I have troubles with the option.

primal token
#

It's not indented in the class!

fading marlin
slate swan
fading marlin
#

!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.
fading marlin
#

ah, there we go

slate swan
#

What does that do?

fading marlin
primal token
#

Because theyre in the class and cant access an instance

#

Cant you just use commands to setup the app commands?

fading marlin
primal token
#

actually i think its app_commands

ocean dragon
#

can I create a custom decorator using default_permissions so I can actually hide the commands from those who do not have a role?

#

(I'm bad at decorators) :D

primal token
#

well then it's commands

fading marlin
ocean dragon
#

ok

velvet compass
velvet compass
#

I have no idea, but it worked after that

primal token
#

๐Ÿค”

whole sparrow
#

Guys, any good vps servers that are good for discord bots that are around $10 a month?

#

or $15, pricing isnt really an issue

#

It's for a server with 5k+ people

#

I've tried pebblehost but it buckled under load

paper sluice
mental hollow
#

kinda off topic but does anyone know any packages which convert seconds into things like "1 minute" if my seconds = 60?

primal token
#

!pypi time-str | something like this?

unkempt canyonBOT
primal token
#

You can also use regex

white citrus
#

How do i get all channels in the SlashOption

weary flume
#

how do i check if a user has a role in a completely different server

slate swan
#

??

limber pagoda
#
guild = bot.get_guild(completely_different_guild_id)
user = guild.get_member(user_id)
role = guild.get_role(role_id)
if role in user.roles:
    #user has the role
else:
    #user does not have the role```
slate swan
#

Is there a way to do if interaction.custom_id == "..." but in modal class?

slate swan
#

can someone explain to me what exactly the benefits are if switching from autosharded client to "horizontallly sharding" or "traditional sharding"?

austere vale
austere vale
#

?

slate swan
#

someone else already answered u

austere vale
#

where ?

prisma prism
#

Hi guys!

server.unban(user)

Will this work, if the user is a string with a valid user ID. and the server is a string with a valid guild ID?

slate swan
#

no

prisma prism
#

is there a correct way to write it?

slate swan
#

unbans are weird

#

u need to get user object

slate swan
# slate swan autoshard just does it for u

autosharded doesn't make any sense though? It's running all shards in the same process so if my process goes down, so do all my shards. Whereas vertical and horizontal sharding don't work that way and I want to know how they work

austere vale
pine lava
#

https://paste.pythondiscord.com/uluropifev so
i'm making a currency bot
and a crash command
and in the paste on line 47
the removed_players dict doesn't update the command
on line 5, i print removed_players and this is a screenshot from my console even after i used the CashOut view

prisma prism
slate swan
#

Hello

austere vale
#

i dont think server.unban is the same as await ctx.guild.unban

prisma prism
#

yeah

slate swan
prisma prism
#

I need a way to manually specify a server and user then unban

slate swan
slate swan
prisma prism
#

will Bot.fetch_user(id) get me a user object?

slate swan
#

he is using interactions dude lol

#

ctx is ctx interaction is interaction

slate swan
#

Inter is better in this situation tho

pine lava
prisma prism
#

so does anyone know a way I can unban someone on a specified server?

#

I don't want CTX as it's a predefined server ID

slate swan
#

just pass guild: int as a parameter

hushed galleon
prisma prism
#

where do I pass it in?

sick birch
#

your command

#

that should take the guild as a parameter

slate swan
#

actually youll also have to use large int

prisma prism
#

oh it's not a command

#

it's raw code

slate swan
#

that doesn't make sense?

sick birch
slate swan
#

yes you do

#

i use python

#

because of the new id update

sick birch
#

Did the ID go up a digit or?

slate swan
#

ye

sick birch
#

Hm. It should still work, python doesn't have trouble with large integers

slate swan
#
async def transfer(self, inter: disnake.ApplicationCommandInteraction, server_id: int = Param(large=True), old_server_id: int = Param(large=True)):

i have to do like this cause if i just pass server_id:int when u input an int if its too large, it won't accept it and let u invoke the cmd

#

how to print the new messages sent in a specific channel?

prisma prism
#

this might do it

sick birch
zealous jay
#

where do I get the url to install the discord.py version before 2.0?

#

the one that didn't support slash commands

unkempt canyonBOT
zealous jay
#

I forgot I could just ==version

granite plume
#

hello

#

does anyone know what the issue is here

#
import discord 

client = discord.Client(intents=discord.Intents.default())

@client.event
async def on_ready():
    print(f"Logging in as {client.user}...")

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.content.lower() == "hello":
        await message.channel.send("Hello")
        

 
client.run('TOKEN')
#

this is my error

harsh creek
#
import discord

client.discord

@client.event
async.client sub How do I fix the bug?

if setA <= setB
if setA true setB false
if setA false setB true
simple kettle
#
@discord.ui.select(placeholder="Pick Devil Fruit table...", max_values=1, min_values=1, options=options)
    async def callback(self, interaction : discord.Interaction, drop : discord.ui.Select):
        lengeth = len(drop.values)
        self.pick = drop.values[lengeth-1]

do i have to have a interaction with the user everytime they change something in the menu

#

i want them to be able to pick what they want on the menu then press a button to submit it

granite plume
wispy spade
granite plume
#

it works on other IDEs such as spyder

#

but VSC is what i'm using to run my bot

#

how do i fix the error there

slate swan
#

Is this something to be worried about? My bot is taking really long to startup

wispy spade
#

or it could be something else, that's the reason I wanted the complete error

granite plume
obtuse blaze
#

how can I call an async fuction insdie __init__

wispy spade
# granite plume

Ok yeah, notice how in the traceback it imports the urllib module in your folder rather than the standard library one, hence the error.

granite plume
slate swan
#

does anyone know how to fix this 'clear' is not recognized as an internal or external command, operable program or batch file.

pallid igloo
#

Hello, I can't install discord.py on Python 3.11.

The command: py -3 -m pip install -U discord.py

The Errors: ERROR: Failed building wheel for multidict

wispy spade
slate swan
pallid igloo
#

note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for yarl Failed to build frozenlist multidict yarl ERROR: Could not build wheels for frozenlist, multidict, yarl, which is required to install pyproject.toml-based projects

pallid igloo
slate swan
#

go in terminal and type pip freeze then send a pic of it

pallid igloo
granite plume
#

idk WHY TF i have a file named after that in the first place

pallid igloo
#

How can I check?

slate swan
#

@pallid igloopython -m pip install -U pip

pallid igloo
#

Requirement already satisfied

slate swan
#

pip install --upgrade pip

pallid igloo
slate swan
#

damn bru

granite plume
#

GREAT

slate swan
#

r u putting ur bot token?

#

or your own token

#

@granite plume

granite plume
slate swan
#

Dang

pallid igloo
#

error: subprocess-exited-with-error

slate swan
#

good luck fixing that last time i tried it didnt work

wispy spade
slate swan
#

But im not sure it helped fixed someones but idk

wispy spade
# granite plume

Pretty clear error, check if you are actually providing a correct token.

slate swan
#

How do you use python obfusticator

pallid igloo
#

ERROR: Could not build wheels for frozenlist, multidict, yarl, which is required to install pyproject.toml-based projects

granite plume
#

i am

wispy spade
#

well you likely aren't, given the error

pallid igloo
granite plume
#

i'll just reupdate the token

#

or ykw just recopy it

#

alright yeah that was my fault

slate swan
#

it wont log u in and it gives u that error

granite plume
#

neat

pallid igloo
#

I installedd 3.10 and now it works. Thank you

slate swan
#

Hello, how can I make so that as many events as there are that answer me as many times to the orders with the same embed but different information of the events?

#

Hello!

Ive been trying to figure out how to do this

Can anyone help me?

#

If you click on the blue it redirects you to a liink

pallid igloo
slate swan
alpine cove
#

or the other way around

slate swan
#

ty

alpine cove
#

np

alpine cove
slate swan
#

with the () []?

alpine cove
#

yup

slate swan
#

ty

mighty pilot
#

is there a way to make a number increase each time in the output of a for loop? for instance im making a leaderboard command and i did it with for result in results: embed.add_field(name=f'{result[1]}', etc... but id like for each result to have 1), 2), etc for each line

alpine cove
#

!d enumerate

unkempt canyonBOT
#

enumerate(iterable, start=0)```
Return an enumerate object. *iterable* must be a sequence, an [iterator](https://docs.python.org/3/glossary.html#term-iterator), or some other object which supports iteration. The [`__next__()`](https://docs.python.org/3/library/stdtypes.html#iterator.__next__ "iterator.__next__") method of the iterator returned by [`enumerate()`](https://docs.python.org/3/library/functions.html#enumerate "enumerate") returns a tuple containing a count (from *start* which defaults to 0) and the values obtained from iterating over *iterable*.

```py
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
```  Equivalent to...
mighty pilot
#

ooo but how would i put that inside of the embed? embed.add_field(enumerate())?

alpine cove
#

bruh

#
for i, result in enumerate(results):
    embed.add_field(name=f'{i + 1}) {result[1]}',
mighty pilot
#

ohhh ok thanks

obtuse blaze
upbeat gust
#

!xy

unkempt canyonBOT
#

xy-problem

The XY problem can be summarised as asking about your attempted solution, rather than your actual problem.

Often programmers will get distracted with a potential solution they've come up with, and will try asking for help getting it to work. However, it's possible this solution either wouldn't work as they expect, or there's a much better solution instead.

For more information and examples, see http://xyproblem.info/

obtuse blaze
#

cause I want to call a fuction that touched DB so it has "await"

upbeat gust
#

What is this the init of

obtuse blaze
#

and I can't call it on __init__ of a diff fuction since its not async

#
        con = sl.connect('db.db')
        cur = con.execute("SELECT items.item_name FROM items INNER JOIN character_items ON items.id = character_items.item_id WHERE character_items.character_id = ? AND items.item_category != 'Weapon' ", (user_ID,))
        row = cur.fetchall()
        return row```

```class _Unequipitems(discord.ui.Select):
    def __init__(self,invoke_interaction) -> None:
        self.user = invoke_interaction
        items = get_equipped_items(self.user)
....```
#

this is an example

primal token
primal token
primal token
alpine cove
primal token
#

Yep and i was telling you which was the correct one by replying to the message that shows the correct syntax!

ocean dragon
#

I'm not getting any error messages, but I still get "Application did not respond" from the bot

ocean dragon
#

no

orchid bear
orchid bear
chilly dove
#

@orchid bearthe decorator add_command doesnt except any arguments

orchid bear
#

fixed

#

How to use numpy for loop?

ocean dragon
# vale wing Do you have error handlers
class MyCog(commands.Cog):
    def __init__(self, bot:commands.Bot) -> None:
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self) -> None:
        print(f"Logged in as {self.bot.user} (ID: {self.bot.user.id})")

    @commands.Cog.listener()
    async def on_command_error(self, ctx, error):
        print(error)

async def setup(bot: commands.Bot) -> None:
    await bot.add_cog(MyCog(bot))

added on_command_error, but still doesn't print any errors

vale wing
#

You either shouldn't have any error handlers at all or they should raise the error if it wasn't handled by them

slate swan
#

hey!

I was wondering how to do something:

I want for when the bot joins a new server it makes there role change to the top of the roles

slate swan
#

so I cant have the bot make its own role go to the top?

vale wing
#

And everything higher than it

#

Indeed you can't

#

Nobody can

slate swan
#

can a bot add a role to themselves if the role is higher then theres?

vale wing
#

No

#

That breaks all logic โ€” everyone would be able to make themselves admins

slate swan
slate swan
slate swan
#

u need to use big int

alpine cove
#

number might be too large

#

oh yea nvm

slate swan
#
from discord.ext.commands import Param


memberid: int = Param(large=True)
#

@slate swan

alpine cove
#

reason: str = "No Reason" also works

alpine cove
slate swan
#

its always been a thing

alpine cove
slate swan
#

do lowercase

#

param

#

it might not even be the same for discord hold on

#

ok so apparently with dpy u have to use a str then convert it to an int lmfao

#

another reason why i like disnake

slate swan
slate swan
#

pycord same thing

#

gotta use str then convert to int

#

javascript doesnt accept that long integer, and so does discord

#

accepting a string and converting it to int is the only choice here

viral dock
#

Hello, When I type in my terminal: pip install discord
The terminal responds with: bash: pip: command not found
So is pip uninstalled or sumn?

slate swan
#

love the wrapper :p

viral dock
slate swan
pale turtle
#

Maybe pip3?

viral dock
slate swan
#

i'd just suggest installing pip properly with python

#

download this file and run it using python

paper sluice
dull terrace
#

means that result[0] is not a number

slate swan
#

can someone give me an example of button persistency in cogs?

whole sparrow
#

Guys any good hosting services?

slate swan
silent portal
#

Is it bad to have multiple scripts with the same bot token?

slate swan
#

why not just combine them? @silent portal

silent portal
slate swan
#

it's simple dude

silent portal
slate swan
silent portal
#

discordpy 2.0

slate swan
#

Hm, what all do you have.

silent portal
#

lol basically many things

#

Leaderboard system, for voice and chat

#

level system and temp voice channels

#

all that kind of stuff

slate swan
#

0-0

#

I would rewrite it in cogs but that sounds like a ton.

silent portal
#

exactly lmao

slate swan
#

wait show me ur current workspace

#

0-0 im sweating at the thought

#

just like 500 subprocess command chainlinked starting each part of the bot

spice scroll
#

keep getting this when I try my bot out. It gives an error on the prefix line:

client = commands.Bot(command_prefix=">")

I get:

  File "C:\Users\User\PycharmProjects\pythonProject\main.py", line 6, in <module>
    client = commands.Bot(command_prefix=">")
TypeError: __init__() missing 1 required keyword-only argument: 'intents'

It never needed intents before, what's changed and how do i fix it?

vale wing
#

A lot

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

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

from discord import Intents
from discord.ext import commands

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

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

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

orchid bear
#

fastest loop?

#

and tut for it ? pls

slate swan
#
@bot.event
async def on_message(*, msg, member: discord.Member):
  channel = bot.get_channel(996119147337494538)
  embed = discord.Embed(title=f"New feedback! \n \n User: {member.mention} \n \n Feedback: {msg}", timestamp=datetime.now() , color=0x4e80cf)
  embed.set_thumbnail(icon=member.display_avatar.url)
  embed.set_footer(text=f"Requested by {member.name} | {member.guild.name}")
  await channel.send(embed=embed)
  await embed.add_reaction('![Fishy](https://cdn.discordapp.com/emojis/998098439948730368.webp?size=128 "Fishy")')```

[2022-10-27 16:28:39] [ERROR ] discord.client: Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
TypeError: on_message() takes 0 positional arguments but 1 was given

vale wing
alpine cove
vale wing
vale wing
slate swan
vale wing
#

That's what causes the error btw

#

And yeah

slate swan
#

like blah blah

vale wing
#

There's no message arg in on_message

vale wing
slate swan
#

OH

#

okay

vale wing
#

Generally in python it means "all args after are keyword-only"

slate swan
#

TypeError: on_message() missing 1 required positional argument: 'member'

vale wing
#

I already said

#

There's no such argument in on_message

slate swan
#

oh

vale wing
#

You access member via message.author

#

why the heck I said message.member

slate swan
vale wing
#

Yeah that's ping

slate swan
#

[2022-10-27 16:38:44] [ERROR ] discord.client: Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Noas Bot\main.py", line 377, in on_message
await channel.send(embed=embed)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\abc.py", line 1536, in send
data = await state.http.send_message(channel.id, params=params)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\http.py", line 744, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.title: Must be 256 or fewer in length.

vale wing
#

Clearly understandable, not gonna explain such an obvious thing, sorry

unkempt canyonBOT
#

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.

vale wing
#

And google "how to read python traceback"

slate swan
#

tysm

spice scroll
#

ugh

alpine cove
#
import discord
from discord.ext.commands import Bot as BotBase

class Bot(BotBase):
  def __init__(self, *args, **kwargs):
    self.channel_cache: dict[int, discord.abc.GuildChannel] = {}
    super().__init__(*args, **kwargs)
  
  async def get_channel_from_cache(self, channel_id: int):
    if int(channel_id) not in self.channel_cache:
      self.channel_cache[channel_id] = self.get_channel(channel_id)
    return self.channel_cache[channel_id]

@bot.event
async def on_message(msg: discord.Message):
  channel = await bot.get_channel_from_cache(996119147337494538)
  if str(msg.channel.id) == "specified channel":
    embed = discord.Embed(title=f"New feedback! \n \n User: {member.mention} \n \n Feedback: {msg}", timestamp=datetime.now() , color=0x4e80cf)
    embed.set_thumbnail(icon=member.display_avatar.url)
    embed.set_footer(text=f"Requested by {member.name} | {member.guild.name}")
    await channel.send(embed=embed)
    await embed.add_reaction(':Fishy:')
#

do something like that

alpine cove
#

I have no idea of that works

#

try it first

spice scroll
#

I had it alive for a split second, I added the intents part but now it's messed up, dunno how to fit

client = discord.Client()

in without coming up with the intents error still

alpine cove
#

dont use discord.Client its deprecated

spice scroll
#

what instead?

alpine cove
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.

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

New in version 2.0.
spice scroll
#

last time I did anything with discord.py was late 2020 so it's been awhile

alpine cove
slate swan
alpine cove
#

yea i relized

#

try ahain

#

*again

slate swan
#

the same code?

alpine cove
#

yep

slate swan
alpine cove
#

but does it work?

slate swan
#

the self

alpine cove
#

ohh the init

#

fix it

#

*fixe

#

*fixed

lime grove
#
self.FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
ctx.voice_client.play(discord.FFmpegPCMAudio(executable="./ffmpeg/ffmpeg", source="./a.mp3", **self.FFMPEG_OPTIONS))
        await ctx.send("playing")

It runs through the code, joins vc without any error or warning even send the "playing message" but no audio at all. any clue?

#

ffmpegpcmaudio dont play any sound

#

any clue why?

slate swan
alpine cove
#

wooos wait

#

fixed

wicked atlas
#

discord.ext.commands

slate swan
#

[2022-10-27 16:53:37] [ERROR ] discord.client: Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\Noas Bot\main.py", line 387, in on_message
channel = bot.get_channel_from_cache(996119147337494538)
AttributeError: 'Bot' object has no attribute 'get_channel_from_cache'

alpine cove
#

wait

wicked atlas
#

you donโ€™t need the from_cache part

slate swan
#

oh

wicked atlas
#

get_channel does just get the channel from the cache

alpine cove
slate swan
#

ill try

alpine cove
wicked atlas
#

Wait, are you trying to create a cache yourself?

slate swan
alpine cove
#

show me your Bot()

wicked atlas
#

Why? Discord.pyโ€™s bot already has one im pretty sure

alpine cove
#

*bot = Bot()

wicked atlas
#

Granted, their cache is slow

slate swan
#

bot = commands.Bot(command_prefix="-", help_command=None, intents=discord.Intents.all())

slate swan
#

oh okay

wicked atlas
#

Do it after you define your Bot class

alpine cove
#

yea

slate swan
wicked atlas
#

Itโ€™s not deprecated?

alpine cove
#

not?

wicked atlas
#

Yeah

#

Itโ€™s just the base class

#

No problem with using Client, just you donโ€™t get all the command stuff that Bot has

slate swan
#
  def __init__(self):
      super().__init__(timeout=None)```
wicked atlas
#

!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. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

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

from discord import Intents
from discord.ext import commands

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

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

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

scarlet aurora
#

who want's to play russian roulette?

lucid galleon
#

I need help๐Ÿค” How to make bot dm me when someone sends a help message in discord?

scarlet aurora
#

ctx.send

lucid galleon
scarlet aurora
#
await user.send("whatever u want")```
#

user must be there discord.Member object

#
user: discord.Member```
scarlet aurora
lucid galleon
#

let me check

scarlet aurora
#

so u wanna do await user.send("text")

#

and user is defined as a discord.Member object

lucid galleon
#

like mine user_id or mine username?

scarlet aurora
#

in this case if u want it to be u it dms

#

do urs

lucid galleon
#

@scarlet aurora I am not getting docs

#

It's showing team member not a single member

scarlet aurora
#

wdym

lucid galleon
slate swan
slate swan
#

Most easy way to do it

slate swan
#

wdym by "sends a help"

lucid galleon
slate swan
lucid galleon
slate swan
#

you need to use an on_message event, check if message.content is equal to "help", if it is
then you will get/fetch your user object

user =bot.get_user(yourid) or await bot.fetch_user(yourid)
``` and use `user.send("text u want")` to send a message
rose nest
#

is there a way to automatically send a message on discord on a channel text at a given delay? if yes, can you give me a link ?

like I want a extension, that runs 24/7 and, at 2 hours delay, from my account types something on some discord server, in some channel text

slate swan
#

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

use this

rose nest
#

thank you โค๏ธ

fiery basin
#

how to make tickets?

rose nest
lucid galleon
#

@slate swan it's showing None user = bot.get_user(myid) print(user)

tough lance
#

how to get remaining cooldown of a command for a user, by the user object itself?

pastel basin
#

how to send images with webhook?

#

i only know to send images in embeds

hushed galleon
chilly dove
hushed galleon
#

though you can create some kind of MockMessage with the attributes related to the BucketType the cooldown uses

hushed galleon
#

?

tough lance
hushed galleon
#

yea

unkempt canyonBOT
#

discord/ext/commands/cooldowns.py lines 64 to 69

def get_key(self, msg: Union[Message, Context[Any]]) -> Any:
    if self is BucketType.user:
        return msg.author.id
    elif self is BucketType.guild:
        return (msg.guild or msg.author).id
    elif self is BucketType.channel:```
tough lance
#

i'll have to go through source code now YuiDepressed

lucid galleon
#

bot command isn't working ```
Traceback (most recent call last):
File "F:\pyenv\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "F:\discord bot\bot.py", line 34, in on_message
await message.channel.send(res)
File "F:\pyenv\lib\site-packages\discord\abc.py", line 1536, in send
data = await state.http.send_message(channel.id, params=params)
File "F:\pyenv\lib\site-packages\discord\http.py", line 744, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message ``

chilly dove
#

the variable res is empty

dull terrace
#

are you remembering to commit to the database

ocean dragon
#

@commands.has_role() doesnt work for slash commands?

#

is there an equivalent ?

glad cradle
#

Well, what is None? show the full error ๐Ÿ˜”

dull terrace
#

what do you mean? put a record with that guild id in your database

#

is this someone elses code?

slate swan
#

guys how can i upload a photo into a embed

#

i tried using the set_image(url="") but i dont have the url because its a file

alpine cove
#

or pass discord.File("path") instead of the url

#

at least im pretty sure that works

hushed galleon
alpine cove
#

thx