#Basic Pycord Help (Quick Questions Only)

1 messages · Page 56 of 1

young bone
grizzled sentinel
#

I dont think they wrote there own code. :/

green hinge
#

Okay it seems to be a problem with the DB somehow. I exported the DB from the server and hosted it locally on my computer and then I get the same error. If I use the old local DB then it works on the computer, will load this times on the server and test.

proud mason
#

or just use epoch

green hinge
lethal valve
#

how do i add an image to a buttonb

eternal wing
#

Is there a way to detect when a user joins a voice channel?

proud mason
proud mason
#

the voice_state_update event

#

.rtfm voice_state_update event

eternal wing
#

Ok thanks! Will try!

proud mason
#

oh and you need the intent for it

eternal wing
#

👍

lethal valve
#

how do i delete an embed when a buytton is clicked tho

proud mason
lethal valve
#

yes

#

and ok

gleaming falcon
#

As a sanity check, is it expected that I cannot include the whole server in a Thread by using @everyone? Roles seem to work, so was sorta hoping default_role would work even better.

(This is for legitimate server-wide notifications)

gleaming falcon
#

Unrelated, how can I get whether a higher role has access to a channel?

Say I have a couple of roles:

  • Core
  • Verified

I have a specific channel that Verified has explicit access to, which would give implicit access to Core (who is presumably also Verified)

When I ask

target_channel.permissions_for(<Role Core>).view_channel

I get false, even though someone with the Role definitely has access to the channel.

Is there some other way I can calculate this?

royal spindle
#

Is there a way to check if a message had a slash command attached to it?

silver moat
#

.rtfm message.interaction

olive marsh
#

?tag replit

obtuse juncoBOT
royal spindle
#

Is there a way to get all active cooldowns?

proud mason
gleaming falcon
# proud mason You would pass a member object. That factors in multiple roles

Hm. But then that would require comparing all users individually, which sounds inefficient.

The idea is to infer whether members in the current channel can see messages in a target channel based on each channel’s allowed Roles.

For instance, a channel that only allows the “Core” Role should be able to see messages sourced in a channel that has a base allow of “Verified”, but not vice-versa.

For now, I just made an explicit override in the target channel so that permissions_for works, but I wish there was a better way of rolling up permissions.

soft girder
#

Hello everyone. I wanted to know. Who can throw off the code for the discord cogs. And approximately how it should look in the files.
PS. I already tried to make cogs on PYCord ,but every time I run the program code, only one file with commands out of 3 is launched.

#

I will be glad if you write in a personal chat. Thank you in advance.

proud mason
#

.guide

winter condorBOT
ripe sage
#
embed.set_footer(icon_url=guild.icon.url)
await ctx.respond(embed=embed)```
#

embed.set_footer(icon_url=guild.icon.url)
AttributeError: 'NoneType' object has no attribute 'url'

ripe sage
#

anyway to get the bot to not use footer if guild has no icon

ripe sage
young bone
#

Its not hard to find..

ripe sage
#

Ok so stop acting smart bc that shows nothing of what I want so i think you should read again

limber urchin
#

The docs tell you everything you need to know

#

And if you can't use simple if statements, you shouldn't be making a bot yet

grizzled sentinel
still helm
#

How many buttons can i have in pycord?

grizzled sentinel
#

25 per message

limber urchin
#

The same as any other library. Max 5 action rows, and max 5 buttons per row

grizzled sentinel
#

But that is a discord limitation not a pycord limitation

If you mean just in general, trillions, idk. How ever many you can keep in your ram

still helm
limber urchin
still helm
#

2 days for this 😄

young bone
#

oof

mossy holly
#

Hey guys just a quick question:
Is there any preferred way to store data when developping discord bots ?
I was thinking to use either sqlite (I never used it before) or PostgreSQL (which I already used) but I think sqlite is more adapted as I don't need crazy functionnalities

still helm
#

sometimes the simplest is the hardest

#

f***** copy failure 😄

limber urchin
#

There isn't a preferred way as it all depends on what data you're storing and what you're comfortable using. If you're good at sqlite, there's no reason to use postgres unless you actually need to.

#

You don't really need to worry about what database to use as long as you know how to use it. Unless you have an ungodly amount of data that needs to be handled in a specific way, then it might be worth looking at which engine works best for you.

#

If you're comfortable with psql, use psql.

mossy holly
#

Ok thanks to both of you (I'll probably go for sqlite then 😄)

young bone
limber urchin
#

You should probably use aiosqlite over the one that comes with python though.

young bone
#

^

limber urchin
#

I mean 99% of your queries probably finish in a matter of milliseconds, but it's still good practice to use async wherever you can in an async environment.

mossy holly
#

Thanks I'll look into it (+ I'm not really comfortable with async yet so it'll probably help me learn a little more ^^)

limber urchin
#

Knowing how to work with async/await is mandatory for making a Discord bot, so learning more sounds like a good idea.

green hinge
#

Can I use instead of

await interaction.response.send_modal```
```py
await interaction.channel.send_modal```?
wicked helm
#

With slash commands, can everyone see the response or are they private?

silver moat
#

?tag ephemeral

obtuse juncoBOT
#

An 'ephemeral' message is one that's only visible to the person who invoked a command. If you ever got a command error with a blue background, this is an example of one.

To do this, set ephemeral=True when you first use an ApplicationContext. (This includes .defer()ing it; the choice of whether a message is ephemeral or not must be made up front. If you .respond() to a deferred message, setting the ephemeral flag at that time will have no effect.)

This is the equivalent of hidden=True if you're coming from interactions.py

wicked helm
#

Ahh, that is why "The Application didn't response" and the correct response are different colours

#

Thank you!

silver moat
#

yw

wicked helm
#

Woop, I got it 😄 That makes this much easier

midnight torrent
#

How can you reply to a interaction response message? When i try and use ctx.message.reply or ctx.interaction.message.reply, the message object is always None

young bone
#

interaction.response.send_message

midnight torrent
#

yeah thats not what im trying to do

midnight torrent
#

^^

proud mason
midnight torrent
#

i can just reply from that

young bone
#

ye

midnight torrent
hollow heath
#

Any ideas why this:

def get_oauth_tokens(code):
    url = 'https://discord.com/api/v10/oauth2/token'
    params = {
        "client_id": BOT_ID,
        "client_secret": BOT_KEY,
        "grant_type": 'authorization_code',
        "code": code,
        "redirect_uri": REDIRECT_URL,
        "scope", "identify",
    }
    response = requests.post(url, data=json.dumps(params), headers={'Content-Type': 'application/x-www-form-urlencoded'})
    return response.json()

Is returning this:
{'error': 'unsupported_grant_type'}
I also tried doing json=params, as well as using path queries

soft girder
young bone
soft girder
#

+-

#

1 sec

young bone
#

just delete the list and maybe use os.listdir

#

so you dont hard code it

soft girder
#

@young bone

#

i think . This can help

#

I right?

young bone
#

try it

soft girder
#

uhhhh....

#

@young boneI don't know

young bone
#

do you have something like this active?

soft girder
#

Hmmm ... I don't know.

cyan quail
#

it errors for the first condition it's checking for (grant_type) since it can't read the data at all

#

...ironic that your variable is called params lol

high jay
#

n=int(input("Enter number:"))

temp=n

rev=0

while(n>0):

dig=n%10

rev=rev*10+dig

n=n//10

if(temp==rev):

print("The number is a palindrome!")

else:

print("The number isn't a palindrome!")

#

could someone explain me this code?

#

it's a program to check whether a number entered by the user is a palindrome or not

#

101 when reversed gives us 101, since 101 = 101 hence it is a palindrome whereas 102 when reversed gives us 201 which isnt equal to 102 hence it isnt

#

basically this is what a palindrome is

#

just need help w the code

#

im new to python so please explain it in simple terms

cyan quail
#

this sounds suspiciously like homework... so i won't explain it fully
% (mod) gets the remainder from a division
// (div) is the opposite; it gets the result without the remainder
e.g. 10%3 = 1, 10//3 = 3
n or temp is whatever number you input
then it's doing some fun loops with rev; i recommend printing the results of each variable to see how the program progresses.

full basin
#

Isn't there an easier way of doing this

cyan quail
#

if i had to guess, someone gave them that code to analyze

#

it's a decent demonstration at a low level at least

#

if you wanted a better method idk convert to string and iterate through to see if i matches length - i

full basin
high jay
#

so i googled the question and found this code

#

this is what i have done

#

ill be sendin the whole code, im just stuck at the palindrome part

#Record Q-6
#Write a Python program to perform the following task according to user’s choice using menu:
#Accept a number and check whether the number is odd or even.
#Accept a number and check whether the number is a palindrome or not.
#Accept a number and check whether the number is an Armstrong numberor not

#Showing the user the options
print("|No.| |-----------------------Choices----------------------------------------|")
print("|-1--| |-Check whether the number entered is odd or even-------|")
print("|-2--| |-Check the number entered is a palindrome of not---------|")
print("|-3--| | Check the number is an armstrong number or not---------|")
print("0 or any other number beside the choices to exit")

#Obtaining the user's choice
user_ch=int(input("enter your choice"))

#code to check if it's odd or even
if user_ch==1:
            n=int(input("enter a number")) #obtaining the number
            if n%2==0:                                    #code to check it's even
                print("it is an even number") 
            else:
                print("it is an odd number")

#code to check the number is entered is a palindrome or not
if user_ch==2:
    n=int(input("enter a number"))
    n_str = str(n)[ : :-1]
    if n_str == n:
        print("it is a pal")
    else:
        print("its not")```
full basin
#

Great code, "```py"

fervent cradle
#

hey guys, do you know why await interaction.response.defer() isnt working?

full basin
#

I'm sure it works

high jay
#

it's still incomplete bc im stuck at the second part

winter condorBOT
high jay
cyan quail
high jay
#

hm

#

i see

#

i can't really think of any other way other than the code i sent earlier

#

do you have one in mind?

cyan quail
#

well.. you could just not convert the type on a certain line

#

but again as per #help-rules we aren't gonna provide extensive help for hw/exams; the solution here should be straightforward enough to figure out on your own or with a bit of research

high jay
#

but okay lol

full basin
#

I'd just convert it to a str and reverse it lol

high jay
full basin
#

You were comparing a str to an int

high jay
#

hm

full basin
#

They'll never be the same

#

You just gotta type 5 characters to make it work

high jay
#

wdym?

soft girder
#

How does localization work in teams?

fervent cradle
# fervent cradle hey guys, do you know why `await interaction.response.defer()` isnt working?

i am trying to defer response because my view is have so many buttons (19)
my code is

@discord.ui.button(label='users', style=discord.ButtonStyle.primary, emoji='🪪')
async def users_callback(self, button, interaction):
    await interaction.response.defer()
        
    users = [await self.bot.fetch_user(i[1]) for i in self.get_users()]

    embed = discord.Embed(
        title='users',
        description='select user',
        color=discord.Colour.blue()
    )

        ...

but... discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
please help

full basin
#

Providing 1/4 of your code isn't helpful

high jay
full basin
#

No

fervent cradle
#

my code have 1421 lines...

full basin
#

You should be able to figure out what's wrong with the reverse string function

#

If not, learn python basics

full basin
winter condorBOT
high jay
#

That's what i am doing right now, we just recently started learning python

fervent cradle
#

it have russian language

high jay
#

and we didnt even learn reversed() function

fervent cradle
#

ok?

high jay
#

i decided to learn it early because i found the topic interesting

#

and this was one of the questions from the topic

high jay
soft girder
#

How does localization work in commands?

cyan quail
fervent cradle
#

this button is just showing all users in database

high jay
cyan quail
fervent cradle
#

and giving me permissions to do something with selected user

fervent cradle
#

but it have russian language

cyan quail
#

well it doesn't have to be the entire file, for now just do the button

#

and the language is fine regardless

fervent cradle
#

oh, good

soft girder
fervent cradle
errant craneBOT
soft girder
fervent cradle
#

password: somepassword

soft girder
#

Why doesn't the second cog work?

cyan quail
#

also... did you really need to use exec

soft girder
#

@cyan quail help me after ?🫠

fervent cradle
#

yes

#

to send data

cyan quail
#

that looks incredibly painful

fervent cradle
#

and access it in view

cyan quail
#

that code should just be a separate file which you import, or make it a real class above the view

fervent cradle
#

ok

#

thx for tip

#

and help

cyan quail
#

and do you load the cogs before using bot.run

soft girder
cyan quail
#

like can you show it in pip list

#

also unrelated... but visual studio is an interesting choice for python

soft girder
cyan quail
#

hmm ok

#

and you're 100% sure the cog is loaded during runtime? i.e. it's present when you print bot.cogs

soft girder
#

ouuu

#

I tried

fervent cradle
soft girder
#
bot.load_extension(`1`)
bot.load_extension(`2`)
#

And now It work

#

🤔🤔

cyan quail
#

well as long as it works ig?

soft girder
#

@cyan quail This is weird.

young bone
#

?

fervent cradle
#

ok

soft girder
#

It turns out the method from the guide does not work 🤔🤔🤔

cyan quail
#

im pretty sure looping to load extensions has always worked

#

idk what the issue is in your scenario

soft girder
young bone
fervent cradle
#

not worked:

Ignoring exception in view <SecretView timeout=None children=8> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Пользователи' emoji=<PartialEmoji animated=False name='\U0001faaa' id=None> row=None>:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/ui/view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "/home/container/cogs/secret.py", line 1054, in users_callback
    self.MyView = MyView''')
  File "/home/container/.local/lib/python3.10/site-packages/discord/interactions.py", line 961, in edit_message
    await self._locked_response(
  File "/home/container/.local/lib/python3.10/site-packages/discord/interactions.py", line 1090, in _locked_response
    await coro
  File "/home/container/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 215, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
soft girder
#

I don't know

#

Everything works now

#

🫠

#

Thanks for your help 🫡😉@cyan quail

cyan quail
fervent cradle
#

but this exec works fine before i add so much buttons

cyan quail
#

and coincidentally, it broke after you added stuff

fervent cradle
#

yes

#

then

#

i will just delete this

#

i have 9 more commands based on this

#

and all of them is works good

#

thx

soft girder
#

@cyan quail

#

WTF

cyan quail
#

Show how you defined block

grizzled sentinel
#

You need to use a group

#

.rtfm applicationcommandgroup

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

full basin
#

.rtfm SlashCommandGroup

soft girder
#
class BLOCK(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    block = SlashCommandGroup("block", "Various greeting from cogs!")

    @block.command(name='user', description="Close a participant's voice channel.")
    @commands.cooldown(1,30, commands.BucketType.user)
    @commands.guild_only()  
    @commands.has_permissions(manage_channels=True)
    async def block(self, ctx: discord.ApplicationContext, member:discord.Member):
        voice = ctx.author.voice
        if voice is not None:
            channel = ctx.author.voice.channel
            overwrite = channel.overwrites_for(member)
            overwrite.connect = False
            await channel.set_permissions(member, overwrite=overwrite)
            await ctx.respond(f"
ame}.",ephemeral=True)
        else:
            await ctx.respond("Sign in to a channel to change its rights.",ephemeral=True)

    @block.command(name='role', description='Close the voice channel for a role.')
    @commands.cooldown(1,30, commands.BucketType.user)
    @commands.guild_only()
    @commands.has_permissions(manage_channels=True)
    async def lock(self, ctx: discord.ApplicationContext,role:discord.Role=None):
        if role == None:
           role = ctx.guild.default_role
        voice = ctx.author.voice
        if voice is not None:
            channel = ctx.author.voice.channel
            overwrite = channel.overwrites_for(role)
            overwrite.connect = False
            await channel.set_permissions(role, overwrite=overwrite)
            await ctx.respond(f"Channel {ctx.author.voice.channel.mention} has been closed for role {role.name}.",ephemeral=True)
        else:
            await ctx.respond("ights.",ephemeral=True)

def setup(bot):  
    bot.add_cog(BLOCK(bot))
cyan quail
#

You have a function called block

#

Which overwrites your block group

#

Just name it anything else

soft girder
#

Ok

proud mason
young bone
#

lol

long zealot
#

Hey! I feel like I should be able to find this in the documentation, but I just can't find it anywhere: how do I add descriptions to various slash command arguments? If the slash command is /hello [playername], how would I add a description to playername? Thank you!

errant craneBOT
#

Here's the slash options example.

proud mason
soft girder
young bone
proud mason
soft girder
#

Hmmmm

spring hull
#

How would i go about finding the uptime of my bot?? Is that a possibility?

#

(Of the bot, not the machine)

limber urchin
#

Just create a variable that stores the current timestamp when your bot starts. The uptime will be current time - start time.

spring hull
#

ok

royal spindle
#

How do I check if a message had a command invoked on it?

#

I previously used to check this using ctx.valid but currently it doesn't seem to work.

limber urchin
#

.rtfm discord.Message.interaction

winter condorBOT
delicate jolt
#
Traceback (most recent call last):
  File "C:\Users\tearx\PycharmProjects\Rosalina\bot.py", line 6, in <module>
    bot = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'```
delicate jolt
limber urchin
#

What IDE are you using?

delicate jolt
#

pycharm

#

should i just reset the project?

#

and go again

limber urchin
#

Did you install pycord with the pycharm package manager?

delicate jolt
#

yes

flat kite
#

And the correct environment is selected?

delicate jolt
#

yep

#

wait hang on

flat kite
#

Are you using conda?

delicate jolt
#

nope

#

anyone know how to change the venv location

#

on pycharm

flat kite
#

Are you usng virtualenv?

delicate jolt
#

yes

flat kite
delicate jolt
#

alright 2 secs

flat kite
#

Try opening a command prompt and activating the environment with source %venv%/bin/activate (linux) or ./venv/Scripts/activate.exe (windows)

#

Then, find the python file and run it with python3 %file%

delicate jolt
#

ive just managed to delete venv

#

some how

flat kite
#

What OS?

limber urchin
#

interesting

delicate jolt
#

windows

flat kite
delicate jolt
#

ill just redo the project

#

This is next level

flat kite
#

xD

#

Fair

delicate jolt
#

is it still discord.Bot()

flat kite
#

Yeah

#

Pretty sure both commands.Bot, discord.Bot and discord.ext.commands.Bot supports slashcommands

delicate jolt
#

Alright epic

#

got it working now

#

ty

limber urchin
delicate jolt
#

im using commands.bot

#

as thats always what i've used

flat kite
#

Sure that works

delicate jolt
#

Epic

flat kite
#

If you want BOTH slash and prefix commands, however, you should look into the bridge bot

loud holly
#

Is there a way to detect if a user is a self bot?

flat kite
#

Nope, sadly

limber urchin
#

If there was, do you not think Discord would have implemented that already?

delicate jolt
#

in a cog

flat kite
limber urchin
#

well I say "reliable", it's a way at least

limber urchin
flat kite
#

That would be to send a link to something, which Discord then embeds

loud holly
#

I guess with links, you can check with https check thing

flat kite
limber urchin
#

I'm pretty sure an embedded link is different from a bot embed

loud holly
flat kite
royal spindle
flat kite
#

Just read up on it

#

However its dumb discord hasnt fixed it...

limber urchin
#

And then check the message for replies

delicate jolt
#

i have bridge commands setup how to check for a specific error in an error

#
    @bridge.Cog.listener()
    async def on_application_command_error(self, ctx, error):
        if isinstance(error, commands.UserNotFound):
            embed = discord.Embed(description=f"Invalid User Silly", colour=col)
            await ctx.respond(embed=embed, mention_author=False)
#

Currently I have this but it's not working

limber urchin
#

That listener should be in your main file.

#

And on_application_command_error only triggers for slash commands

delicate jolt
#

yeah its in the same file

#

oh i read that wrong

#

whats the one that triggers for bridge

limber urchin
#

I do not believe there is a collective listener for that

delicate jolt
#

is there one for a command in particular?

limber urchin
#

So if you have a command called my_command you can do @my_command.error as a decorator

delicate jolt
#

and for the function?

#

i got it to work

#

Thanks for the help 🙏 you were correct as always

proud mason
limber urchin
#

If it doesn't already exist, I haven't used bridge commands personally so not too educated on them

proud mason
#

hmm ill check docs

#

cant find anything

fervent cradle
#

hello everyone, why is my /help command is not showing in slash commands menu?

@commands.slash_command(name='help', description='Команда помощи')
@commands.guild_only()
async def help(self, ctx):
    if self.check_commands(ctx.author) == True:
        embed = discord.Embed(
            title='Ошибка',
            description=':red_negative_cross_mark:  Владелец данного бота ограничил вам использование слэш-команд',
            color=discord.Colour.red()
        )

        await ctx.respond(embed=embed, ephemeral=True)
    else:
        embed = discord.Embed(
            title='Помощь',
            description='Выберите категорию',
            color=discord.Colour.blue()
        )

        await ctx.respond(embed=embed, view=HelpView())
fervent cradle
#

yes

#

using bot.remove_command('help')

young bone
#

for what is the self check?

fervent cradle
#

its a system

#

for blocking

#

commands for users

young bone
#

can you remove it and try it without it?

fervent cradle
#

ok, i will try

young bone
#

also sometimes it takes some time to see slash commands

fervent cradle
#

i will wait ~10 mins

young bone
#

or use ;

#

stuff like this also works

print("Hello"); print("World")
long zealot
grizzled sentinel
#

It would not go in the decorater but it works if you type hint the arguments of the command
async def hi(ctx, user: Option(discord.User, description="The user to say hi to"))

winter condorBOT
# fervent cradle hello everyone, why is my `/help` command is not showing in slash commands menu?...

Checklist for Application Commands Not Showing Up:
• Does your bot have the application.commands scope?
• Are you loading cogs before on_ready and on_connect?
• Is on_connect not overridden?
• Did you update to the newest version of py-cord (tag: install)?
• Is User Settings > Accessibility > Chat Input > Use legacy chat input turned off?
• Did you share your code and errors?
• Do you still have libraries that conflict with the discord namespace (e.g. discord.py)?

proud mason
#

Uh

#

Bot has become slow ngl

fervent cradle
#

How can I send a message to a particular channel?

young bone
fervent cradle
#

yes but how do I get the channel?

#

ok wait wtf

#

nvm got it didnt think it'd be so simple

long zealot
#

Love pycord 😂

flat merlin
#

How would I get emoji to use them on buttons? The normal Discord emoji, not custom ones.

limber urchin
#

Type an emoji with a \ in front of it and you'll get the unicode version of it.

grizzled sentinel
grizzled sentinel
#

.rtfm options

flat merlin
#

Thanks.

soft girder
#

IN Api Ref. subtracted about the localization of the commands.

#

Please give a guide to it, as very little is written in the API.

silver moat
soft girder
#

@silver moat thx

astral mist
#
@bot.event
async def on_ready():
    await webhook.send(status_text, username='Foo')

async def foo():
    async with aiohttp.ClientSession() as session:
        webhook = Webhook.from_url(status, session=session)
        await webhook.send(status_text, username='Foo')

#

why is it not defined

tired goblet
#

How can i add multiple buttons to a single message?

young bone
tired goblet
#

Gotcha

#

The guide helped too

real frost
#

Hi everybody, i have a question, how to create a command that works through a profile?

#

like this

#

Thanks in advance for your reply.

real frost
#

Appreciate it!11

tired goblet
#

if i have a user's id, how do i turn that into a mention?

#

im trying f'@{ctx.author.id}' but not working

astral mist
#

After the @ is where u add the ctx author thing

tired goblet
#

okay

tired goblet
astral mist
tired goblet
#

oh

astral mist
#

f'<@{ctx.author.id}>'

astral mist
tired goblet
#

worked thanks!

astral mist
tired goblet
astral mist
tired goblet
#

not defined means it can't see where webhook was first initialized, but ofc you already know that

tired goblet
#

where?

#

is this a scope problem?

still helm
#

is there a way to post in chat who´s pressing a discord button?

storm oyster
astral mist
#

And when I add await webhook send

#

It just says not defined

astral mist
proud mason
#

.botvar

winter condorBOT
#

Need to keep track of a variable between functions? No problem!

⚠️ Careful what you name it though, else you might overwrite something ⚠️

Just add it to your commands.Bot or discord.Client instance like so:

bot = commands.Bot(...)
bot.my_variable = 0

async def foo():
    bot.my_variable += 1

# In a cog
@commands.command()
async def counter(self,ctx):
    await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))

This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance

astral mist
proud mason
#

depends on where foo is

#

if foo is run before bot is ready, it will work. else it wont

#

you might want to look into asyncio.Event if you want to synchronise stuff

spare juniper
#

isnt it non pythonic (and usually problematic) if you are using global variables

#

Could you pass the variables as parameters to make it more modular

proud mason
spare juniper
grizzled sentinel
proud mason
spare juniper
#

true

grizzled sentinel
#

Oop, did not see they were getting help

proud mason
still helm
loud holly
astral mist
limber urchin
#

If you don't know how variable scoping works, you should not be making a bot. You need to learn basic Python

still helm
#

is there a way to check for permissions for a button like in commands? @has_permissions or is_owner?

#

i am using @discord.ui.button()

meager mica
#

so im trying to edit an embed on button click but im not sure how to pass my message id or class or whatever to my class to be able to edit it is this possible?

#
            view = RockPaperScissors(ctx.user, user)
            await ctx.respond(embed=no_turn_embed, view=view)
        ```
proud mason
#

also, view.message should have the message object if you want the embed

meager mica
proud mason
meager mica
#

ohhhh

#

ok thanks

proud mason
#

if you have sent a message, then use interaction.message.edit

#

np

green hinge
#

Can you change the color of a dropdown menu when you have selected something?

meager mica
#

so i was trying to make so it just dont respond when you cloick button according to docs from what i could tell you do self.stop() but i did that and it still responds... do i do self.disableallitems

limber urchin
#

You need to edit the message with your view after you disable the items to update the buttons

meager mica
#

can i just make it not listen to them

limber urchin
#

?

#

just disable the buttons and edit your message

meager mica
#

ok

tired goblet
#

Is it possible to disable buttons after a specific time? Like its working for the first 5 minutes the message was sent and then greys out automatically?

silver moat
#

.rtfm view.disable_on_timeout

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

silver moat
#

.rtfm view.dis

winter condorBOT
silver moat
#

Just override the on_timeout function and edit the message with the updated view

tired goblet
#

Thanks!

grizzled sentinel
#

What is the best way to make message templates when sending a response. With slash commands I subclassed get_application_context so I could do ctx.prespond.success(message) and it would return an embed that was created to look like a success message. However there is no such thing as get_interaction_context so how would I add these functions to interaction s well?

proud mason
#

you will need to use function programming

#

is this in a view?

#

if so, you can have a method that accepts an interaction (or even the button/select menu), and does the stuff you want

#

or you can even have this function outside the view in the global scope that does the same

solemn idol
#

What does this mean?
What is "internal message cache", if I may ask?

proud mason
# solemn idol What does this mean? What is "internal message cache", if I may ask?

pycord has a message cache that stores messages the bot receives. it has a size limit of 2000 messages by default. pycord has various such caches, like member cache, role cache etc.
often it happens that an older message was edited and it wasnt present in the cache. events with raw are called regardless of whether the object is in cache or not

solemn idol
#

Ohhhh- I did not know that, tysm :)

obtuse canyon
#

Is there a way to separate a command group into multiple cogs? I'm looking to try and organize files a little better.

silver moat
gleaming falcon
#

Can confirm. Works wonderfully

high jay
#
How many times will Python execute the code inside the following while loop?

i = 1
 while i < 10000 and i > 0 and 1:
 print “ Hello ...”
 i = 2 * i
Answer:
14.```
#

why is it 14? i don't understand

#

i've tried the code and yes it did print it 14 times

#
code:
i = 1
while i < 10000 and i > 0 and 1:
    print ("Hello ...")
    i = 2 * i
Output:
Hello ...
Hello ...
Hello ...
Hello ...
Hello ...
Hello ...
Hello ...
Hello ...
Hello ...
Hello ...
Hello ...
Hello ...
Hello ...
Hello ... ```
full basin
#

Print i and you'll see

high jay
#

alright

#
code:
i = 1
while i < 10000 and i > 0 and 1:
    print ("Hello ...")
    i = 2 * i
    print (i)
Output:
Hello ...
2
Hello ...
4
Hello ...
8
Hello ...
16
Hello ...
32
Hello ...
64
Hello ...
128
Hello ...
256
Hello ...
512
Hello ...
1024
Hello ...
2048
Hello ...
4096
Hello ...
8192
Hello ...
16384

i do understand it doubles itself everytime, but im confused why is it restricted to 14times?

full basin
#

Because 16384 is > than 10000

high jay
#

but the code here is "while i < 10000", so shouldn't it not print 16384?

full basin
#

You're printing i after the change

#

When the loop starts again and checks, it stops

#

Because i is not smaller than 10000

high jay
#

hm alright i see thanks

limber urchin
gilded niche
#

Hi, is it possible to make a search option for a Select menu on mobile? Because it is not possible to search through members in a select menu on mobile

limber urchin
#

You can't just make a mobile feature work on your bot. That's through the Discord client, if it doesn't work, it doesn't work.

high jay
#

mistakes are part of the process

#

im a beginner so yeah

silver moat
#

While we do appreciate your enthusiasm, I think the Python Discord server would explain these topics much better

#

.gg/Python

high jay
fervent cradle
#

How to check if a snowflake ID is a user id, role id, or channel id?

tired goblet
#

How can i access the context received in a slash command in a button callback method?

#

The button is part of a view shown with the slash command response

proud mason
tired goblet
#

Oh

proud mason
tired goblet
#

I was actually struggling with the init of view

#

Not sure if i gotta do something to super()

proud mason
#

First line in your init should be a call to super init
Like this super().__init__(...)

tired goblet
#

Okay

proud mason
#

And then you would set the ctx to a variable

tired goblet
fervent cradle
proud mason
fringe socket
#

Anybody know how I can make a help command using Slash Commands? There isn't anythign on the guide, sadly.

tired goblet
#

How can i use disable_all_items() in a button callback command?

proud mason
tired goblet
proud mason
tired goblet
#

lol nah wait pls

#

so i have a class that inheits from discord.ui.View

#

and i've got two button callbacks in this class

tired goblet
#

is it possible to do something like self.disable_all_items()?

tired goblet
#

doesn't seem to be working

#

i also have disable_on_timeout set to True

proud mason
tired goblet
#

could that be causing a conflict?

tired goblet
#

didn't know that

proud mason
proud mason
tight sentinel
#

I've been using slash commands for quite a while now and have been registering them one by one, which is I believe normal, however, I've been wondering if I could "bulk register" all slash commands at once. (I haven't been able to do so, so far which is why I'm asking)

grizzled sentinel
#

Pycord is able to handle registration for you. Can you show how you are registering them?

tight sentinel
#

the way I'm registering them is different than what I want ( which is bulk register ), but sure:

@client.slash_command(
    name="ping",
    description="Bot latency"
)```
(*it works! but that's not how I want it to be*)
#

I was thinking of something maybe as following:

commands = {
"ping": "bot latency",
...
}```
grizzled sentinel
#

I think you would have to use docstrings for the description though.

tight sentinel
#

oh, didn't notice that my bad, yeah that's fine, tho what I'm worried is the choices since I usually use

@discord.commands.option(name="name", description="description", required=True)```
young bone
#

discord.option()

#

@tight sentinel

soft girder
#

Please tell me. What will the best team look like to clear the chat.

grizzled sentinel
tight sentinel
#

alright, thanks

soft girder
#

I already have one, but it can sometimes freeze.

#

Please tell me. What will the best command look like to clear the chat.

grizzled sentinel
#

.rtfm purge

chrome skiff
#

How can i fix this error?

grizzled sentinel
grizzled sentinel
young bone
#

Im not sure if you really can use discord.User

grizzled sentinel
#

fetch_user takes the user ID you are giving it the member object.

young bone
#

@errant crane is down... oof

grizzled sentinel
chrome skiff
#

Wait… i can remove the fetch_user because i already have a user object

#

Right?

grizzled sentinel
#

👍

chrome skiff
#

so this should work fine

loud holly
#

So I have a situation where if I announce updates, the message would be sent in every server that has configured the Bot in a logging channel, is it needed await asyncio.sleep(0.05) when sending the message to those channels to prevent my bot from being put in the spam list?

cyan quail
#

though regardless, the library already handles ratelimits for you so there isn't much risk

#

also you should probably encourage users to follow an announcement channel instead

hushed ledge
#

One message removed from a suspended account.

cyan quail
#

it's not built in no

loud holly
cyan quail
#

just have them enter their destination channel, then on your end use channel.follow(destination)

#

bot will need decent permissions though

hushed ledge
cyan quail
#

again, it's not built in; you'd need to create your own system

hushed ledge
cyan quail
#

if your button's custom ID is unique enough, you could easily set up a dict that maps the custom ID to the last timestamp it was pressed at

loud holly
cyan quail
#

yes

#

(typically) webhooks can't mention

#

(and tbh, using an @everyone mention in every guild your bot's in may be seen as abuse)

fervent cradle
#

hi, how can i get the modal title in the callback from the modal?

cyan quail
#

is it subclassed?

#

if so, probably self.title

fervent cradle
#

it is! let me test it :)

#

worked. thanks! :)

dry gazelle
#

If I have lets say 1000 people clicking a button at one time, I am needing to defer these interaction responses, and hititng the rate limit quickly. Is there any way for me to throttle these calls to make them not hit the rate limit?

#

I would think asyncio might have something to help?

cyan quail
#

interactions have their own ratelimit which you typically don't have to worry about

#

but hm

#

the library already handles ratelimits for you by queuing stuff when necessary

dry gazelle
#

Weird because it gets rate limited quickly

cyan quail
#

is it specifically defer that gets ratelimited?

silver moat
#

what is in your callback

cyan quail
#

or somewhere else in your code

silver moat
#

replit?

cyan quail
#

run

dry gazelle
#

The interaction.followup.send() call is returning a 429 error saying its being rate limited

#

But even before being rate limited, it was getting a 404 unknown interaction on the interaction.response.defer() call

#

(Not using replit)

#

Using a Vultr VPS to host

#

That's the callback for the button

cyan quail
#

should probably defer before the DB call, beyond that the best you could do is create your own queue system with task loops which handles followup.send

#

though odd that ratelimit handling isn't applied here...

dry gazelle
#

Yeah that was what is weird, that it is not automatically handling the ratelimit

#

I know the issue that started this more was the fact that the generate_watermark_image() function is a compute heavy function, so with more than 100 calls at a time, it can take a few seconds to complete, but this should be solved by the defer() calls, no?

cyan quail
#

strictly speaking yes, the main issue is that defer is being ratelimited then you're doomed

dry gazelle
#

ugh

cyan quail
#

but i don't think it should

dry gazelle
#

the first error started coming when it was giving me this error when trying to call defer

cyan quail
#

perhaps paste/screenshot the error?

dry gazelle
cyan quail
#

that's a completely different button

dry gazelle
#

wrong error hold on

#

that's the correct buttoin

#

Should i get rid of the button being part of this view?

cyan quail
#

i mean the button itself is fine

#

but yeah you can't really counter that

young bone
#

I cannot see any message you send

cyan quail
#

because it's impossible to do anything else if you can't defer

young bone
#

at the interaction

dry gazelle
#

The line await interaction.followup.send(file=discord.File(img_path), ephemeral=True) is the response to the interaction

#

it is just sending an image in an ephemeral message

young bone
#

you need something like interaction.response.send_message or edit_message

dry gazelle
#

well I had the interaction.response.send_message, but then i saw i needed to defer the calls because the computation was longer than the 3 second timeout

ornate current
#
import discord
from discord.ext import commands
import os

intents = discord.Intents.all()
bot = commands.Bot(command_prefix=">", intents=intents, case_insensitive=True)
bot.remove_command("help")



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


        
        
bot.run("...")```
This says command not found. I have a command in the cog
#

what am i doing wrong here

dry gazelle
ornate current
#
import discord
from discord.ext import commands
class InfoCommands(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    #----------------------OWNER------------------------
    @commands.command()
    async def hi(self, ctx):
      await ctx.send("hello")
       
def setup(bot):
    bot.add_cog(InfoCommands(bot))```
#

@young bone ^

cyan quail
#

thus you'd actually have to go to discord for an increased ratelimit

#

(i think that's how it works?)

#

but indeed, we could do with a github issue on ratelimits not being handled on every function

dry gazelle
cyan quail
#

you cannot delay a defer

#

or rather, you can't extend that 3 seconds without a response

proud mason
dry gazelle
cyan quail
#

if discord themselves is preventing the response you need to continue then it's out of our hands

dry gazelle
#

would that get around the rate limit?

cyan quail
dry gazelle
#

I was just doing the response.send_message before and it was just running out of time and not finding the interaction, but not getting rate limited per se, so I will try something like that

ornate current
#

nvm i figured it out

cyan quail
#

if you respond immediately before doing anything else then maybe it'll be viable

proud mason
cyan quail
#

yeah but observing the error here #998272089343668364 message, it couldn't make it to defer

Discord

Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.

dry gazelle
cyan quail
#

do they actually have 0 rate limits or reduced rate limits

proud mason
proud mason
# dry gazelle so is there any way around doing the followup?

not really. i made a bot wide producer consumer based coroutine queue for the followups that sleeps around 0.3 seconds before sending the next followup. if a followup still failed due to a ratelimit, then sleep for the time specified in retry_after and retry the followup again. I havent faced issues after that

proud mason
cyan quail
#

interesting

dry gazelle
#

and isnt the rate limit like a 15 minute cooldown, or is it just until you aren't makeing more than 50 calls per second

proud mason
dry gazelle
grizzled sentinel
proud mason
dry gazelle
#

im confused on how it can't find the interaction even though its the first thing in the callback...

proud mason
#

also share pip list and python version

dry gazelle
proud mason
#

could be a network issue on the vps

dry gazelle
#

I just did it on my local PC and the same issue

proud mason
#

oh

dry gazelle
proud mason
#

do you have any cpu intensive or event loop blocking work going on somewhere else in the code?

dry gazelle
#

not anywhere else, just the generate_watermark_image function in the callback

#

Its generating images

#

should I be like threading this work out?

proud mason
dry gazelle
dry gazelle
#

so it looks like the defer call isnt getting screwed up now

proud mason
dry gazelle
fair ledge
#

.rtfm Interaction

proud mason
proud mason
dry gazelle
proud mason
# dry gazelle That would be extremely helpful... I understand the concept of producer/consumer...

ok so this is just some rough stuff i will type out right in the chat input


bot.followup_queue = asyncio.Queue() # This is a queue of coros that we will run sequentially rather than asynchronously

@bot.event
async def on_ready(): 
    # Don't use on_ready as this can fire multiple times. Just using for an example
    while True:
        coro = await bot.followup_queue.get()
        try:
            await asyncio.sleep(0.5) # sleep for a while. this blocks the loop from going to the next coro in the queue
            await coro
        except discord.HTTPException as e:
            await asyncio.sleep(e.response.headers.get("Retry-After", 20)) # Get retry after seconds and sleep for it
            await coro # Retry

# Somewhere else
coro = interaction.followup.send(...) # Notice how we dont await
interaction.client.followup_queue.put_nowait(coro)

dry gazelle
#

I really appreciate the help!

proud mason
proud mason
dry gazelle
proud mason
proud mason
#

😀

green hinge
#

I have included the 'WetterView' above.
I call the view 'WetterView' via the button. After I click a button in WetterView I want the 'OptionalView' to be called again and the button to be displayed disabled.
How can I get this to work?
Because to include the views on the other side does not work as far as I know or?

from tageszeiten import WetterView


class OptionalView(discord.ui.View):
    def __init__(self, bot: discord.Bot, spotdaten):
        self.bot = bot
        self.spotdaten = spotdaten
        super().__init__(timeout=None)

    @discord.ui.button(label='Wetter', custom_id="Wetter_Button", style=discord.ButtonStyle.primary, disabled=True)
    async def wetter_button(self, button: discord.ui.Button, interaction: discord.Interaction):
        attach_message = self.spotdaten[1]['messageid9']
        await attach_message.delete()
        await interaction.channel.send(view=await WetterView(self.bot, self.spotdaten))
        await interaction.response.defer()
gleaming falcon
#

General python question... any OOP gurus about? I want to set up and reference configurations for a single common service (API) but with different configs/base urls. There will be a dozen of them or so. Much (if not all) of the same class logic itself would apply, it's just various addresses that might change.

Can't determine whether I should have a Singleton that contains all of the configs, or use individual instances with some sort of collection class

alpine helm
#

How do you prevent the bot from running any command until the bot is ready

#

I have database commands but people tend to use them more often. When the bot is restarting, it takes some time to load the database. Up until then, any database command used will cause error

#

There is await self.bot.wait_until_ready(). I can put this in every command function but that would be redundant?

#

I am sure there must be another way to stop commands from running until the bot is fully loaded

full basin
#

You can use the on_command and on_application_command listeners

boreal abyss
#

prefetched_commands = await self._bot.http.get_guild_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\يولين\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 360, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access

alpine helm
boreal abyss
young bone
boreal abyss
#

all ofit?

full basin
young bone
alpine helm
boreal abyss
young bone
#

can you do a better screenshot pls

boreal abyss
#

thats better?

young bone
#

yes

#

Im not sure if this one is breaking it

boreal abyss
#

should i completly uninstall it?

#

i aint using it

young bone
#

also do you have intents?

boreal abyss
#

Deleted.

boreal abyss
young bone
#

website and code?

boreal abyss
hardy crescent
#

My slash commands won't register

alpine helm
hardy crescent
#

Waiting for 12 hours

young bone
young bone
alpine helm
#

You can add your server in guild_ids

#

and then try

hardy crescent
#
from discord.ext import commands
import discord, asyncio, os

TOKEN = ""

intents = discord.Intents.default()
bot = commands.Bot(intents=intents)

@bot.event
async def on_connect():
    print(f"Logged in as: {bot.user}")
    print(f"Loaded {len(bot.guilds)} guilds")
    await bot.register_commands()

    cogs = [
        "cogs.generate",
        "cogs.invite",
        "cogs.vote",
        "cogs.help",
        "cogs.status",
    ]

    for cog in cogs:
        try:
            x = bot.load_extension(cog)
            print(f"Loaded extension {x[0]}")
        except:
            print(f"Failed to load extension {cog}.")

    while True:
        await bot.change_presence(
            status=discord.Status.dnd,
            activity=discord.Activity(
                type=discord.ActivityType.watching,
                name=f"{len(bot.guilds)} servers"
            )
        )
        await asyncio.sleep(25)

bot.run(TOKEN)

This is my code

boreal abyss
young bone
hardy crescent
#

also tried at the beginning of the file

#

and on_ready

young bone
#

dont load the cogs at on_ready or on_connect

boreal abyss
#
Ignoring exception in on_connect
Traceback (most recent call last):
  File "C:\Users\يولين\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\يولين\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 1164, in on_connect
    await self.sync_commands()
  File "C:\Users\يولين\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 738, in sync_commands
    app_cmds = await self.register_commands(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\يولين\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 531, in register_commands
    prefetched_commands = await self._bot.http.get_guild_commands(
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\يولين\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 360, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
Logged in as Hound#5599 (ID: 1070369109704982538)

full error

young bone
#

do you use anything like debug_guilds?

hardy crescent
#

It's working now Thanks

boreal abyss
young bone
#

and what is with both message intents?

boreal abyss
hardy crescent
#

Now i am getting broken pipe errors

#
  File "/opt/homebrew/lib/python3.10/site-packages/discord/ui/view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "/Users/jeffrey/Desktop/pepperai_dev/cogs/generate.py", line 79, in select
    await msg.edit_original_response(embed=embed, view=View(self.prompt, images), file=discord.File(f"images/{image_uuid}.png"))
  File "/opt/homebrew/lib/python3.10/site-packages/discord/interactions.py", line 428, in edit_original_response
    data = await adapter.edit_original_interaction_response(
  File "/opt/homebrew/lib/python3.10/site-packages/discord/webhook/async_.py", line 157, in request
    async with session.request(
  File "/opt/homebrew/lib/python3.10/site-packages/aiohttp/client.py", line 1141, in __aenter__
    self._resp = await self._coro
  File "/opt/homebrew/lib/python3.10/site-packages/aiohttp/client.py", line 560, in _request
    await resp.start(conn)
  File "/opt/homebrew/lib/python3.10/site-packages/aiohttp/client_reqrep.py", line 899, in start
    message, payload = await protocol.read()  # type: ignore[union-attr]
  File "/opt/homebrew/lib/python3.10/site-packages/aiohttp/streams.py", line 616, in read
    await self._waiter
aiohttp.client_exceptions.ClientOSError: [Errno 32] Broken pipe
#

how can i fix this

loud holly
#

is there a way to check if this is set? I typed in Rule Screen in the docs hoping to get keywords, but all I got was the welcome screen

EDIT: Found the Solution, had to find screening itself and dig around the docs

hardy crescent
hardy crescent
#

yes

zinc cloak
#

After running a new slash command a few times, it gets... unregistered

#

And I have to restart the bot for the command to work again

#

I got guildIDS set to the right server too

proud mason
#

Do you have multiple instances of the bot running?

zinc cloak
#

OH SHOOT

#

I just realized that... lol.. thanks!

proud mason
#

Lol 👍

long zealot
limber urchin
#

You can see exactly how it works in the docs and examples

silver moat
#

This is more of a design question: when should I name a file in its plural state (e.g. enums.py as opposed to location.py)?

limber urchin
# silver moat This is more of a design question: when should I name a file in its plural state...

This is a comment from the Java reddit, but I think it makes sense in any environment:

As always, it's up to your discretion and what makes sense in your environment, but I tend to name them singular when the classes in the package are classification and plural when they are implementations. For example, I would put Sheep, Goat, and Pig inside of com.example.animals and I would define it as com.example.animal in the case that it contained infrastructure, utility, or other similar classes such as Pet, WildAnimal, Feeder, AbstractAnimal, CommunicationInterface, etc.

#

It doesn't look like there are any conventions for it, so yeah, pretty much up to you whatever you think makes the most sense.

fervent cradle
#

How to get a list (data type) of banned users in a guild?

silver moat
#

.rtfm guild.bans

winter condorBOT
limber urchin
#

The docs quite literally gives you the code you need for that

soft girder
#

Hmmm ChatGPT I already did. But I need help with the code. How will he respond?

limber urchin
#

what?

green hinge
#

I have included the 'WetterView' above.
I call the view 'WetterView' via the button. After I click a button in WetterView I want the 'OptionalView' to be called again and the button to be displayed disabled.
How can I get this to work?
Because to include the views on the other side does not work as far as I know or?

from tageszeiten import WetterView


class OptionalView(discord.ui.View):
    def __init__(self, bot: discord.Bot, spotdaten):
        self.bot = bot
        self.spotdaten = spotdaten
        super().__init__(timeout=None)

    @discord.ui.button(label='Wetter', custom_id="Wetter_Button", style=discord.ButtonStyle.primary, disabled=True)
    async def wetter_button(self, button: discord.ui.Button, interaction: discord.Interaction):
        attach_message = self.spotdaten[1]['messageid9']
        await attach_message.delete()
        await interaction.channel.send(view=await WetterView(self.bot, self.spotdaten))
        await interaction.response.defer()
limber urchin
#

What? What isn't working? You're just sending code

green hinge
#

If I put this in my tageszeiten .py to then call the OptionalView again. My bot always crashes. I think because I import the two files each other and thus have an infinite cycle or?

from submit_spot import OptionalView

await interaction.channel.send(view=await OptionalView(self.bot, self.spotdaten))```
limber urchin
#

I don't understand what you're trying to do. Why are you importing OptionalView?

#

And why are you awaiting OptionalView?

green hinge
#

I have a file submit_spot.py where the OptionalView is inside.
Here I call the WetterView from the file tageszeiten.py via a button.

In the WetterView is also a button. If I click this I would like to call again the OptionalView with the button which should be however deactivated.

limber urchin
#

So why don't you just edit OptionalView and disable the button in your button callback?

green hinge
#

Because when I press the button in OptionalView, the button should be deleted and then be under the WetterView again.
So that OptionalView is always the last message.

#

I want to jump to another file via the button click, execute something there and then jump back to the insert_spot.py file to display the view again.

limber urchin
#

Why can't you just import both views into one file and use both of them? Your file structure makes no sense

green hinge
#

Okay my problem is more complex after all, I have to think again, thanks anyway 🙂

green hinge
#

How can I access the contents of the dict "spotdata" here outside of init and without a function?

class OptionalView(discord.ui.View):
    def __init__(self, bot: discord.Bot, spotdaten):
        self.bot = bot
        self.spotdaten = spotdaten
        super().__init__(timeout=None)

    data = self.spotdaten[1]
limber urchin
#

you can't

#

and why would you ever want to?

green hinge
#

I want to check with an If query if the variable 'check' is set to True. If it is set to True the button disabled should be displayed, if it is set to False the button enabled should be displayed.

#

Had thought so

    if self.spotdaten[1]['check'] == True:
        @discord.ui.button(label='Wetter', custom_id="Wetter_Button", style=discord.ButtonStyle.primary, disabled=True)
        async def wetter_button(self, button: discord.ui.Button, interaction: discord.Interaction):
            await interaction.response.defer()
    else:
        @discord.ui.button(label='Wetter', custom_id="Wetter_Button", style=discord.ButtonStyle.primary)
        async def wetter_button(self, button: discord.ui.Button, interaction: discord.Interaction):
 await interaction.response.defer()
limber urchin
#

I have no idea what you are talking about. Why do you need to make a variable called data outside of your functions??

pallid magnet
#

how to let buttons access value?

limber urchin
#

?tag codeblock

obtuse juncoBOT
#

Please put your code in a code block:
```py
Here is your Code
```

That makes reading code in Discord a lot easier:

print("This is an example.")
pallid magnet
#
class Event(View):
    @button(label="1:Apex", style=discord.ButtonStyle.blurple)
    async def callback1(self, button, interaction):
        data=data+str(interaction.user)
        await interaction.response.edit_message(content=f"List:\n{data}\nPlease select ", view=self)
limber urchin
#

Where is data defined?

pallid magnet
#

user id

limber urchin
#

what?

pallid magnet
#

save user id

limber urchin
#

where is data defined???

pallid magnet
#

gobal variable

limber urchin
#

?

#

why?

proud mason
#

.botvar

winter condorBOT
#

Need to keep track of a variable between functions? No problem!

⚠️ Careful what you name it though, else you might overwrite something ⚠️

Just add it to your commands.Bot or discord.Client instance like so:

bot = commands.Bot(...)
bot.my_variable = 0

async def foo():
    bot.my_variable += 1

# In a cog
@commands.command()
async def counter(self,ctx):
    await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))

This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance

proud mason
#

use that instead of global vars

pallid magnet
#
global data
data=""
class Event(View):
    @button(label="1:Apex", style=discord.ButtonStyle.blurple)
    async def callback1(self, button, interaction):
        data=data+str(interaction.user)
        await interaction.response.edit_message(content=f"List:\n{data}\nPlease select ", view=self)
#

not work

proud mason
#

what doesnt work?

#

.idw

#

any errors?

winter condorBOT
#

Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.

pallid magnet
#

File "c:\Users\user\Desktop\emotion_eng_chatbot\Youth_Discord_Chatbot\try.py", line 13, in callback1
data=data+str(interaction.user)
UnboundLocalError: local variable 'data' referenced before assignment

limber urchin
#

Don't use global variables when you don't need them

pallid magnet
#

I see thanks

limber urchin
#

And in the future, provide code and errors. It's a waste of time having to ask multiple questions just to see what's wrong

pallid magnet
#

got it

serene spindle
#

Is it possible to use hyperlinks([]() method) in embed titles?

limber urchin
#

no

limber urchin
#

it's probably faster to just try it instead of asking here tbh

serene spindle
#

Just wanted to make sure it's not my code

#

I'll try experimenting with the description ig

cyan quail
#

that's what makes the title a link

#

if you meant field titles then no

serene spindle
#

I meant embed titles, and the url attribute works, thanks! Sorry if this was a xy problem

cunning furnace
#

Any ideas on how i'd go about making a ticket transcript that is html instead of just txt files

glacial falcon
#

can i remove an option from a select menu

limber urchin
fervent cradle
glacial falcon
fervent cradle
#

what did you want to do? remove option in code or remove after callback?

glacial falcon
#

like after i click a button

limber urchin
#

.rtfm View.remove_item

winter condorBOT
fervent cradle
#

^

glacial falcon
#

i want to remove an option from the select menu

limber urchin
glacial falcon
silver moat
#

you can just edit the current select menu with different options

glacial falcon
silver moat
#
original_options = select.options
# remove your option here
new_options = ...

select.options = new_options
glacial falcon
silver moat
glacial falcon
#

hmm...

glacial falcon
# silver moat iff `select` is a child of `view`.

so i want to edit the select menu after clicking the button
and theres a button callback function taking a View, a Button and an Interaction object
do i do this?
View.children[0].options = new_options
and await Interaction.response.edit_message(view=View)?

silver moat
#

What does your button callback look like?

glacial falcon
silver moat
#

Is this in a view subclass?

glacial falcon
#

yes

#

i renamed self

silver moat
#

other than the casing, everything looks fine.

glacial falcon
#

thanks for helping

proud mason
limber urchin
#

local variables shouldn't have any uppercase letters anyways if you want to follow the normal conventions (which you should)

#

and renaming self seems useless to me

cunning furnace
cunning furnace
#

🤷‍♂️ I wasn't the one saying it isn't good

limber urchin
#

And what's stopping you from using your own brain? Instead of a stranger that tells you it's bad and doesn't give a reason.

#

Either way you'll have to deal with things like proper authentication to view transcript etc.

real frost
#

Sup everybody, can anybody help me?

AttributeError: 'Guild' object has no attribute '_member_count'

I'm getting this error while this code

@tasks.loop(seconds=8)
async def change_banner():
    guild = await bot.fetch_guild(guild_id)
    print(guild)
    members = guild.member_count
limber urchin
#

Where is guild_id defined? And why are you fetching the guild on every loop?

real frost
#

oh, i've replaced it with members = len(guild.members) and it works

proud mason
limber urchin
#

It wouldn't be that hard to just run django on it's own and use a shared database though

proud mason
#

If you only need a web framework then you might be better off using fastapi or quart

limber urchin
#

Yeah, if you only want to display HTML pages with no auth stuff or anything django is going to be overkill.

#

But Django does come with a pretty good built-in ORM and Authentication system

young bone
#

what is with Flask?

limber urchin
#

But tbh if you want to build an actual web application, I'd look at a fully fledged JS/TS frameworks instead. Like Angular or SvelteKit

sick quest
#

is there a way to make a forced set of options in a slash command? like if I want the user to input a weekday, it can only be Monday, Tuesday, etc.
I've tried autocomplete but the user can still input something else, it's more of a suggestion

silver moat
errant craneBOT
#

Here's the slash options example.

sick quest
#

cool thanks!

limber urchin
#

It's a Discord limitation, if you need more than 25 options you have to use autocomplete and make your command respond with something like "Invalid value for option 'weekday' " if they input something else.

young bone
#

Can I remove a button from an edited message?

silver moat
young bone
#

How? I dont really have an idea

silver moat
#

.rtfm view.remove

winter condorBOT
silver moat
young bone
#

it works, thx!

loud sail
#

Which program do you think is the best for coding Discord bots in Python?

limber urchin
#

There isn't a "best". It's whatever you prefer.

loud sail
#

I'm always hesitating between vs Code and PyCharm peepoShrugIDK

limber urchin
#

Why?

limber urchin
#

Every editor has pros and cons. We can't pick for you because we don't know what you want in an editor.

loud sail
limber urchin
loud sail
silver moat
#

because iirc only windows has an issue with ram for intellij based IDEs

limber urchin
#

Probably, Windows has RAM issues with a lot of things

#

Just dual boot and use Linux whenever you're developing, ez

silver moat
#

mac

loud sail
silver moat
loud sail
limber urchin
#

Chrome uses a lot of RAM no matter what OS you're on

grizzled sentinel
silver moat
#

I use IntelliJ for everything 💀

loud sail
hollow mauve
#

Quick question how to use emoji with name from particular server and can we use animated emojis from a server with the bot?

limber urchin
#

Type a \ before the emoji and you will see what to use in your bot
E.g pycord = !pycord

#

And yes, you can use animated emojis

#

As long as the bot has permission to use external emojis in the server

boreal abyss
#

Traceback (most recent call last):
File "E:\Ganger\Raid-Protect-Discord-Bot\main.py", line 23, in <module>
bot.load_extension(f"Cogs.{filename[:-3]}")
File "C:\Users\يولين\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\cog.py", line 910, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\يولين\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\cog.py", line 791, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'Cogs.changePrefix' raised an error: ClientException: Cog named 'ChangePrefixCog' already loaded

help.

if name == 'main':
for filename in os.listdir("Cogs"):
if filename.endswith(".py"):
bot.load_extension(f"Cogs.{filename[:-3]}")

young bone
limber urchin
boreal abyss
limber urchin
#

And if you're making a bot you should be at the level of Python competence where you know how to catch errors

boreal abyss
limber urchin
#

And if you do know Python, you should also know how to catch an error and prevent crashes

boreal abyss
#

ok ill just do for i in range the number of cogs?

limber urchin
#

what?

boreal abyss
limber urchin
limber urchin
boreal abyss
fervent cradle
#

ik dumb question but docs always confuse me. how do i add a dropdown menu to a message?

limber urchin
boreal abyss
limber urchin
#

Where is that code?

boreal abyss
#

next to the file.

#

folder*

limber urchin
#

What?

#

where in your file is the code that loads the cogs?

boreal abyss
limber urchin
#

how do you have code "next to" a file?

#

what does that even mean

boreal abyss
fervent cradle
#

i see theres a busy argument so i will ask later

limber urchin
# boreal abyss bot\ main.py cogs

I don't care where in the folder the code is, I'm asking where you're loading the cogs. Is it in on_ready, is it in on_connect, is it before you run .start????

#

where in the file

boreal abyss
limber urchin
#

?tag codeblock

obtuse juncoBOT
#

Please put your code in a code block:
```py
Here is your Code
```

That makes reading code in Discord a lot easier:

print("This is an example.")
fervent cradle
#

maybe you should put that in a codeblock

#

yea

limber urchin
#

I've already told them that before as well

boreal abyss
#


if __name__ == '__main__':
    for filename in os.listdir("Cogs"):
        if filename.endswith(".py"):
            for i in range(21):
             bot.load_extension(f"Cogs.{filename[:-3]}")
```
limber urchin
#

and that is at the top level of your code scope?

#

why is that there?

fervent cradle
#

oh that

fervent cradle
#

i didnt see the arrow

#

my bad

proud mason
#

.rtfm load_extentions

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

proud mason
#

Bruh

#

.rtfm bot.load

limber urchin
#

extensions* doggokek

errant craneBOT
#

Here's the dropdown example.