#Basic Pycord Help (Quick Questions Only)

1 messages · Page 72 of 1

cyan quail
#

it'll let you throw whatever string in there and if it fails it fails

torpid wraith
#

Thanks ❤️ I ended up using a regular expression for validation 🙂

#

Follow up question: Is there an event or a way to print to console once all cogs are loaded?

#

For example, this is what I currently have ("Characters" is a cog):

04/20/2023 14:59:09: [Startup] Bot attempting to login to Discord...
04/20/2023 14:59:12: [Startup] TestBot9000#1577 is ready and online!
04/20/2023 14:59:12: [Characters] Successfully loaded!

But I'd rather it be like this:

04/20/2023 14:59:09: [Startup] Bot attempting to login to Discord...
04/20/2023 14:59:12: [Characters] Successfully loaded!
04/20/2023 14:59:12: [Startup] TestBot9000#1577 is ready and online!

"Ready and online" comes from bot event on_ready

cyan quail
#

just load cogs before connecting?

#

this is considered standard anyway since slash commands have to be loaded before on_ready fires

torpid wraith
#

I thought I was...

# Create the bot object
bot = discord.Bot(intents=intents, activity=activity)
# Add cogs to bot
bot.add_cog(CogCharacters.CogCharacters(bot, db))

@bot.event
async def on_ready():
  print("Online!")

bot.run(TOKEN)```
#

But the Characters cog is printing its on_ready after the main bot file's on_ready? Is that normal?

#

Is add_cog async?

cyan quail
#

nope

#

you could add in a await self.bot.wait_until_ready() in your other cog events

torpid wraith
cyan quail
#

no, i mean inside your other on_ready events where you're printing stuff

torpid wraith
#

That would be in the other cog files

#

I have a bot on_ready and then a cog on_ready for each cog. I just found it odd that the cog on_ready's were loading after the bot's on_ready

cyan quail
#

well the on_ready isn't for when the cog loads

#

it's just when discord cache is ready

#

the default bot.event is fired first, then the additional listeners are fired after

torpid wraith
cyan quail
#

yeah probably

torpid wraith
#

Btw, what exactly is the Discord Cache (I'm still learning everything, sry)

#

Or, what does it being ready indicate?

cyan quail
#

well by default, if you have the members intent the bot will go through all your guilds and save all the members locally

#

so you can receive member related events and quickly interact with them

#

there's also the message cache and a few other small ones

torpid wraith
#

oh cool, so it fires when it's queried the Discord API successfully and has cached all that data locally

cyan quail
#

mhm

torpid wraith
#

is there a cache per cog? or is it global to the bot? Doesn't make sense to have a duplicate cache per cog

cyan quail
#

bot

torpid wraith
#

kk, tyvm ❤️

cyan quail
#

e.g. you can access bot.guilds

torpid wraith
#

gotcha

cyan quail
#

and for every guild you have guild.members

torpid wraith
#

And just to learn, is there any particular reason to load it as an extension over how I'm doing it?

cyan quail
#

as an extension it's easier to update code on the fly without having to restart

torpid wraith
#

wait whaaa... If I load it as an extension I can develop the code, save, and it will live update functionality without rebooting?

cyan quail
#

there's some caveats like not being able to update slash metadata (name etc.) but yeah

#

you load it with load_extension and you can reload / update with reload_extension; the best integration for this is to make these commands

torpid wraith
cyan quail
#

all good

torpid wraith
#

oh, it requires a function call to reload? I'll look into that

cyan quail
#

mhm

torpid wraith
#

Sorry for the ping @cyan quail, but is it possible to send extra data as arguments in bot.load_extension()? I need to send a database object that's defined in the main bot file to all the cogs, but I don't think I can with load_extension, which is why I think I'm using bot.add_cog 😅

cyan quail
#

you can access it directly through self.bot no?

torpid wraith
cyan quail
#

have you made a proper cog structure?

torpid wraith
#

How do you mean?

#

I think so

cyan quail
#

e.g. from the guide https://guide.pycord.dev/popular-topics/cogs/ ```py
import discord
from discord.ext import commands

class Greetings(commands.Cog): # create a class for our cog that inherits from commands.Cog
# this class is used to create a cog, which is a module that can be added to the bot

def __init__(self, bot): # this is a special method that is called when the cog is loaded
    self.bot = bot

#  commands etc.

def setup(bot): # this is called by Pycord to setup the cog
bot.add_cog(Greetings(bot)) # add the cog to the bot

#

in your init we have self.bot = bot which is expected in all cogs

#

so here you can add any other variables you might need

torpid wraith
#

Oh, yes, I have all this, but I currently have it like this:

class CogCharacters(discord.Cog, guild_ids=[GUILD_ID]):
    def __init__(self, bot, db):
        self.bot = bot
        self.db = db```
But you said to not pass it as an argument and instead call it via `self.bot.db`? Which means it would be an instance variable of `bot`, no?
cyan quail
#

right

#

is it the same db across all cogs?

torpid wraith
cyan quail
#

did you already subclass bot

#

ah it doesn't look like you did, but it doesn't matter

#

you can just do bot.db = ...

silver moat
cyan quail
#

eh... not particularly?

#

i do like subclassing bot but it's not a must

torpid wraith
cyan quail
#

though if you plan on doing it more extensively, adding several variables or overwriting several methods then yeah subclassing would make it easier in the long run

torpid wraith
#

How do I subclass bot?

silver moat
#

I think it's definitely not the best way, but again, that doesn't mean that's bad.

cyan quail
#

the same as how you'd subclass cogs, just make a class that inherits discord.Bot

#

though unlike cogs you need to include a super init

silver moat
#

subclass, also known as inheritance or extending.

torpid wraith
cyan quail
#

...that being said the guide code samples... kinda suck

#

oh well

silver moat
cyan quail
#

yeah...

silver moat
#

I mean if you understand OOP you should know why+how you should subclass, right?

torpid wraith
#

Just need to sit down and learn it...

silver moat
#

usually I see people trying to speedrun making a super complex discord bot before they know the basics of computer science and/or python.

torpid wraith
#

I believe it... I almost have my degree in CS and am super familiar with Java and C++, but Python syntax is still new to me. Trying to keep all my Python growing pains out of this channel though and only ask questions regarding the API. Thx for all the info peeps

proud mason
#

Btw there is a way for it. Make a GET or HEAD http request to the url and check the content type

errant craneBOT
#

Here's the slash autocomplete example.

soft girder
#

How fix this problem?

proud mason
#

Make less api calls

#

And don't use a host with shared ip

waxen whale
#

Some days I rly wanna slap you..

young bone
#

Es war nur unwissenheit?

waxen whale
#

inform yourself before you speak or don't speak at all.

young bone
#

k

proud mason
#

Can can pass names of Users if you want. And set value to the id

#

Oh damn that's a really old msg 💀

young bone
full basin
#

That's what I did hah

fallen cove
#

Can you use utils.get_or_fetch() the same way as utils.get()?

median nacelle
#

how do i use

#

cogs ?

young bone
median nacelle
#

can u direct me

#

ok nvm i found it

frank yew
#

I'm a little bit stuck, I don't have much clarity. Can someone help me or provide a code to connect to a channel and play an audio file?

dapper pasture
# frank yew I'm a little bit stuck, I don't have much clarity. Can someone help me or provid...
from discord.ext import commands
from discord_slash import cog_ext, SlashCommandOptionType
import asyncio

class MyBot(commands.Bot):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        
        self.voice = None # Initialize the voice client variable

    # Define a command to join a voice channel and play audio
    @commands.command()
    async def play(self, ctx, *, file_path: str):
        if ctx.voice_client is not None:
            return await ctx.voice_client.move_to(ctx.author.voice.channel)

        voice_channel = ctx.author.voice.channel
        self.voice = await voice_channel.connect()

        # Load the audio file using discord.py's FFmpegOpusAudio class
        audio_source = discord.FFmpegOpusAudio(file_path)

        # Play the audio file
        self.voice.play(audio_source)

    async def on_ready(self):
        print(f"Logged in as {self.user}")
        
bot = MyBot(command_prefix="!")
bot.run("your_bot_token")```
#

chatgpt4 made this

#

Also someone help me, i have problem using slashes in class

#
@discord.ext.commands.is_owner()
@option('collection', description='Choose database', choices=['Games', 'Site exceptions', 'exceptions'])
    async def add_to(self, ctx, collection: str, string: str):
        listing = self.retreive_list(collection)
        print(listing)```
frank yew
#

What loses me a little bit is the FFmpegOpusAudio. Do you know if I have to have the audio in some format?

dapper pasture
#

how do i hide it?

frank yew
dapper pasture
dapper pasture
frank yew
#

What if you remove it?

dapper pasture
#

then it puts ctx into self variable

frank yew
#

I am going to check my commands

silver moat
#

why do you have self 🙃

dapper pasture
woeful skiff
#

hey, i want to change every appropriate user. but my code doesn't work, please help me out somehow

@bot.event
async def on_member_join(ctx):
    if "swearword" in ctx.username:
        await ctx.edit("Moderierter Name")
    else:
        pass
dapper pasture
frank yew
#

For example:

async def get_type_times(ctx: discord.AutocompleteContext):
    return [
        time for time in TIMES if time.capitalize().startswith(ctx.value.capitalize())
    ]
@option("type_time", description="Duration type", autocomplete=get_type_times)
async def vote(self, ctx, type_time: str):
...
woeful skiff
#

but why doesn't that work, again i want to moderate every username made in the "or ..." thing

@bot.event
async def on_member_join(ctx):
    if "swear" or "swear2" or "discord.invite" or ".gg" in ctx.username:
        await ctx.author.edit(nick="Moderiert")
    else:
        pass
dapper pasture
#

i see, u have wrong syntax: u need to make this if ".gg" in ctx.username and "swear" in ctx.username and .......for every one of your strings

woeful skiff
#

ohh ok

dapper pasture
woeful skiff
#

it still doesn't work

#
@bot.event
async def on_member_join(ctx):
    if "swear" in ctx.username and if ".gg" in ctx.username:
        await ctx.author.edit(nick="Moderiert")
    else:
        pass
frank yew
dapper pasture
#

i think ctx.username doesn't exist

woeful skiff
#

yeh it does

dapper pasture
#

oh ok

woeful skiff
#

i think

#

i dont know too actually 💀

dapper pasture
woeful skiff
#

nothing

#

it just doesnt work lmao

dapper pasture
#

if u don't have any console output that means u haven't turned on your bot

frank yew
woeful skiff
#

it is turned on

dapper pasture
#

but u have console, right?

woeful skiff
#
@bot.event
async def on_member_join(ctx):
    if "swear" in ctx.author.name or ".gg" in ctx.author.name:
        await ctx.author.edit(nick="Moderiert")
    else:
        pass
dapper pasture
#

what

woeful skiff
#

that my code

#

it doesnt work

dapper pasture
#

console

#

not code

woeful skiff
#
container@server~ if [[ -f /home/container/${REQUIREMENTS_FILE} ]]; then pip install -U --prefix .local -r ${REQUIREMENTS_FILE}; fi; /usr/local/bin/python /home/container/${BOT_PY_FILE}
Requirement already satisfied: py-cord in ./.local/lib/python3.10/site-packages (from -r requirements.txt (line 1)) (2.4.1)
Requirement already satisfied: aiohttp<3.9.0,>=3.6.0 in ./.local/lib/python3.10/site-packages (from py-cord->-r requirements.txt (line 1)) (3.8.4)
Requirement already satisfied: typing-extensions<5,>=4 in ./.local/lib/python3.10/site-packages (from py-cord->-r requirements.txt (line 1)) (4.5.0)
Requirement already satisfied: aiosignal>=1.1.2 in ./.local/lib/python3.10/site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord->-r requirements.txt (line 1)) (1.3.1)
Requirement already satisfied: charset-normalizer<4.0,>=2.0 in ./.local/lib/python3.10/site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord->-r requirements.txt (line 1)) (3.1.0)
Requirement already satisfied: yarl<2.0,>=1.0 in ./.local/lib/python3.10/site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord->-r requirements.txt (line 1)) (1.8.2)
Requirement already satisfied: frozenlist>=1.1.1 in ./.local/lib/python3.10/site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord->-r requirements.txt (line 1)) (1.3.3)
Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in ./.local/lib/python3.10/site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord->-r requirements.txt (line 1)) (4.0.2)
Requirement already satisfied: attrs>=17.3.0 in ./.local/lib/python3.10/site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord->-r requirements.txt (line 1)) (22.2.0)
Requirement already satisfied: multidict<7.0,>=4.5 in ./.local/lib/python3.10/site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord->-r requirements.txt (line 1)) (6.0.4)
Requirement already satisfied: idna>=2.0 in ./.local/lib/python3.10/site-packages (from yarl<2.0,>=1.0->aiohttp<3.9.0,>=3.6.0->py-cord->-r requirements.txt (line 1)) (3.4)

[notice] A new release of pip available: 22.2.2 -> 23.1
[notice] To update, run: pip install --upgrade pip
dapper pasture
#

well thats terminal

#

do u have pycharm

woeful skiff
#

no

dapper pasture
#

or vs code?

woeful skiff
#

i use a hoster

#

where it is hosting

dapper pasture
#

what's that

woeful skiff
#

💀

#

that the bot is online 24/7

dapper pasture
#

so u edit your code on hosting service??

woeful skiff
#

yes

dapper pasture
#

thats not correct way of doing it

#

you can't check your code, if it has any errors

#

use pycharm or vs to edit your code locally, then upload it onto host

#

both of these programs help you by showing ctx parameters such as author, send, respond....

#

and mainly it shows console output where are errors shown

woeful skiff
#

I thought this is "help"

#

so u guys can tell me what's the code

proud mason
#

we wont write and give you code

#

we just help you with errors in your code

#

and other stuff like ode structure etc

#

or how to do x, y, z

#

you need to do the coding part

#

||we are unpaid volunteers pogbruh||

sinful pivot
#

Hi, anyone wanna guide me on how I'd go about making a verification system that uses Discord Authorization. Basically, they authorize their discord account on my website, and I give them the verified role, how would I do this?

full basin
woeful skiff
#

i just figured it out myself

#

cause u guys don't know how to explain

full basin
#

Or unless you want to ping some api the bot listens to (no idea how to do that but it's an option)

sinful pivot
#

i really forgot wtf oauth2 was

#

and why it existed, i remember its basically the discord dashboard login

#

just the callback code is changed

full basin
full basin
#

You just do different stuff lol

sinful pivot
#

yeah

#

i dunno why i didnt think of that, thanks for reminding me lol

full basin
#

Np

full basin
# woeful skiff i am a boy

It's used as a plural world. Not specific. Just like "bro". Don't get your masculinity offended darling.

dapper pasture
cyan quail
fallen cove
cyan quail
#

all utils.get does is return an item from any list

#

depending on some criteria

#

utils.get_or_fetch will parse your args to either return an item or fetch it. Let's take this docs example:py channel = await utils.get_or_fetch(guild, 'channel', channel_id, default=None)
this will do the following:

  1. try guild.get_channel(channel_id)
  2. if that returns none, it'll try await guild.fetch_channel(channel_id)
  3. If that also doesn't work, it will error. However by passing default it won't error and instead just return None
fallen cove
cyan quail
#

ah no it can't really do that

fallen cove
young bone
#

Isn`t get or fetch already trying to fetch it?

cyan quail
#

you could use guild.fetch_channels to fetch all and then use get

#

yeah but you can't fetch by name

young bone
#

I use get() the most of the time

#

only get ;3

fallen cove
cyan quail
#

what do you actually do with the category?

fallen cove
cyan quail
#

hmmm isee

#

is it a particularly large bot? there shouldn't be many issues with cache

fallen cove
cyan quail
#

that's very strange then yeah

#

can you see if it's there when you print guild.categories

fallen cove
fallen cove
#

The last time I checked at least

cyan quail
#

are you 100% sure the name is exact

fallen cove
#

Case and spelling are identical across servers

cyan quail
#

hm tbf doing it by ID is far more reliable anyway but strange case

fallen cove
#

And interms of scaling the way I have it set up is a pain as I’ve got to add the ids manually

#

(Few role ids aswell as they differ by spelling across servers)

full basin
#

Those look like normal options

errant craneBOT
#

Here's the slash options example.

silver moat
#

autocomplete is dynamic while choices are static.

rare ice
#

How do I get a user's public flags as an integer?

silver moat
paper kindle
#

class lfgView(discord.ui.View): # Create a class called MyView that subclasses discord.ui.View @discord.ui.button(label="Join", style=discord.ButtonStyle.green) async def join_button(self, button, interaction): message = await interaction.original_response() print(message.id) await interaction.response.send_message('hey', ephemeral=True)

Produces an error on message = await interaction.original_response() when I press the button:
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook

This button is attached to an embed that is a response to a slash command. I'm trying to access the message id of this embed.

silver moat
#

you can use view.message for the message.

paper kindle
cyan quail
dull onyx
#

How i can send a message via webhook in thread?

#

i'm trying to initiate snowflake and insert id of thread in it, but i getting TypeError: Protocols cannot be instantiated

#

python ver 3.11.2 and py-cord version 2.4.1

dull onyx
cerulean halo
#

Can I make buttons work even after bot restart if yes how?

proud mason
cold hamlet
#

Does the library force Guild.filesize_limit to be 8MB when the boost level is 0 or whatnot, or is the API still returning the old 8MB cap?

#

I just uploaded a 25MB file despise the FS limit attribute being 8MB, so

cyan quail
#

it was updated to 25 on master

cold hamlet
#

Ah

cyan quail
#

but it's never forced it internally

#

we just have it for guild.filesize_limit

waxen whale
#

👀 are we all behaving here

versed fern
#

I'm interested in how larger, professional bots setup their bot and organize their code. Are there any public, open source bots running on pycord?

proud mason
versed fern
#

awesome, thank you

lime moss
#

Is there a way to make the bot stop showing “sending command” even if I still have some of the command stuff running?

rare ice
#

no

full basin
#

Sending command is when discord is sending the command (ironic) not when the command is being processed by your bot

rare ice
#

^

#

its discord's way of making you think the bot is already processing it but its to cover up their slow ass slash commands

lime moss
#

I have it using delete_after, is there a way to make it still delete but not show sending command

full basin
static matrix
#

i want to execute some operations for all options of a command by using for, but i don't figured out how.

#

inside of Quantity function gotta be the str value of the option that will entered who using the bot

proud mason
#

this is wrong on so many levels

static matrix
#

yea i'm a sleepy adhd rn forget about the goofy i = i.real in for 💀 just wondered how can i manage my all options with for

proud mason
# static matrix i want to execute some operations for all options of a command by using for, but...
  1. options are typehinted, not assigned. so opt1: str, opt2: discord.Option(...), ...

  2. your last 4 options are string type but default value is an int or a float? pogbruh
    if you want them to be inputed as integers, why not give the input type as integers, and then convert to str

  3. you should typehint ctx with discord.ApplicationContext

and now for your actual issue
4. have you tried "reading the docs"
https://docs.pycord.dev/en/stable/api/application_commands.html#discord.ApplicationContext.selected_options

sorry if this sounded rude blobpain

proud mason
static matrix
#

omg i gotta go bed so bad 💀

proud mason
#

yes lol

static matrix
proud mason
#

ah alr

static matrix
#

thank you so much btw rooBless

solemn idol
#

The good ending wowcry

full basin
#
  1. my god what's the variable assignment, its hurting my eyes
  2. why do you even set variables in the command callback when they don't depend of it and then you use them as a button callback
  3. you should subclass views and not do that
still tulip
#

mb g

leaden sedge
#

get_user isnt returning anything:
code:

for player in players:
            print(player)
            user = bot.get_user(int(player))
            print(user)
            await user.send(f'Your role is: {roles_assigned[player]}')

Output:
384449598305075200
None

cyan quail
leaden sedge
#

thanks

woeful skiff
#
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 378, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 1164, in on_connect
    await self.sync_commands()
  File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 719, in sync_commands
    registered_commands = await self.register_commands(
  File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 599, in register_commands
    registered = await register("bulk", data, _log=False)
  File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 371, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 39: Application command names must be unique
#

i want to know what command name is not unique

#

how to fix that?

proud mason
woeful skiff
#

can't i see the line where it is not unique

still helm
#

How do i add a description for link?

@bridge.bridge_command(description="To download videos from tiktok")
async def tikload(self, ctx, link):
young bone
errant craneBOT
#

Here's the slash options example.

proud mason
#

@still helm ^

proud mason
still helm
cyan quail
#

it still works for bridge

still helm
#

yeah i got it with async def tikload(self, ctx, link: discord.Option(description="xxx")

solemn idol
#

from discord.commands import Option

#

wait does that even matter?

proud mason
#

just use plain old discord.Option pogbruh

#

Especially when dealing with bridge stuff

magic pendant
#

Does slash command have check decorators?

solemn idol
#

I think they do

woeful skiff
#

hello, i want to make a "your message has been sent" bot

@bot.event
async def on_message(message : discord.Message):
    if message.author.id != "1099713203413463162": ##<= ID of the bot
        await message.reply("Your Message has been sent successfully")
    else:
        pass
#

@proud mason do you know smth?

proud mason
woeful skiff
#

oh lmao

fervent cradle
#

How to create a private thread?

worn void
#
import discord
from discord.ext import commands

class Greetings(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @discord.slash_command()
    async def goodbye(self, ctx):
        await ctx.respond('Goodbye!')

    @discord.user_command()
    async def greet(self, ctx, member: discord.Member):
        await ctx.respond(f'{ctx.author.mention} says hello to {member.mention}!')

    @commands.Cog.listener()
    async def on_member_join(self, member):
        await member.send('Welcome to the server!')

def setup(bot): # this is called by Pycord to setup the cog
    bot.add_cog(Greetings(bot)) # add the cog to the bot

Can bot be changed to client without issue? I'm just used to using client instead of bot

novel jay
#

If i make 2 cogs have the @commands.Cog.listener() for example on_message will they override each other or will they run independently?

silver moat
silver moat
silver moat
novel jay
#

alright

warm spire
#

any way to schedule one-off tasks? like i want X to happen at Y time?

#

or create a new loop while the code is running? like i want X to happen every Y hours?

proud mason
#

.rtfm ext.tasks

#

uh

#

@errant crane help

#

ig just look it up on the docs page

#

should be there under the ext heading

cyan quail
fervent cradle
warm spire
proud mason
patent knoll
#

Do I have to make an entire MyView() etc class to properly wait for a button press or can i do it in a simpler way?

patent knoll
#

shrug no idea what that means

#

all i wanna do is have a button, and when that button is pressed, do 1 thing

silver moat
patent knoll
#

i do

#

but i dont see why i need an entire class, and why you cant just attach a function call to a button press

#

Plus I am doing this entire thing in a cog which is all one big class so i have no idea how i'd properly put another class definition in there so it works

silver moat
#

well, you asked for the simplest.

patent knoll
#

yea, well, how do i do it then

silver moat
#

create a button, create a callback, set the callback attribute to your callback then add the button to the view.

patent knoll
#

i tried this, but it just instantly executes the callback
I'm very new to interactions anyway lol, last i made bots in discordpy was 3 years ago

full basin
patent knoll
#

and that tells me what

errant craneBOT
#

Here's the confirm example.

full basin
patent knoll
#

trying to copy that rn, but apparently its not possible to do this as it says label isnt defined

patent knoll
#

i do but i am tired, and i did never work with classes much

young bone
#

self.label

patent knoll
#

nope

#

"self is not defined"

young bone
#

Im also tired x3

#

Its 1:47 am for me xd

patent knoll
#

same here

#

i have been trying to figure this out all night

#

All i need is a singular button with a dynamically created label, that does 1 thing when pressed

#

and the thing its doing also needs to be dynamic
and i cannot figure it out

steel wharf
#

you cant pass class atts to decorators

#

you have to subclass the button

patent knoll
patent knoll
#

oh, wait

steel wharf
#

i said the button

full basin
#
class MyButton(discord.ui.Button):
  def __init__(self, customlabel):
      super().__init__(label=customlabel)```
patent knoll
#

just read what you said, but, would this work too or should i just do it your way

full basin
#

ig that works

#

but subclassing is always the best practice

patent knoll
#

and I'm sorry, I'm just tired and going right into interactions lol
im not stupid

#

Okay, i'm trying to do it the way you are doing, but now i'm unsure how to do the callback right since i'm subclassing button

cyan quail
patent knoll
cyan quail
#

eh they're accomplishing the same thing, if you want to add more custom stuff to button then i'd recommend subclassing but if it's just this one label then you could keep it down to view

patent knoll
#

i really just need a single button (dynamic label, i can do that) that also has a dynamic callback (this is what i have been stuck on for ~2h)

cyan quail
#

in what way is it dynamic

patent knoll
#

sends a message that depends on what was said in the very original command
e.g. i do /command user1

the callback needs to basically reference the user1 argument in that command as well as the original command user

cyan quail
#

right, so you've already been adding arguments to your subclassed view and assigned them as self variables

#

you can just keep doing that

#

then inside your callback, just reference self.uid or whatever you've set

patent knoll
#

currently i have 3 different implementations all at once lol

full basin
#

subclassing looks cleaner SCgrin

patent knoll
#

am i stu🅱️id

#

says self isnt defined

cyan quail
#

no not in the decorator

patent knoll
#

well, says it in the send_message too lol

cyan quail
#

oh the args should be self, interaction because it's in a class

patent knoll
#

well, then how do i make the label dynamic :>

cyan quail
#

if you want to do the label without subclassing button, leave a placeholder string inside the decorator and inside init do self.button_callback.label = label

patent knoll
#

ah right

#

i assume thats because of the added self

cyan quail
#

oh right LOL

#

no uh

patent knoll
#

i am going mentally insane

cyan quail
#

because it's a decorator, it's self, button, interaction

patent knoll
#

just to make sure, like this? Thonk

cyan quail
#

mhm

patent knoll
#

but why the button there

cyan quail
#

so you can access the button object

patent knoll
#

💀 that made it work but i never even used "button"

cyan quail
#

yeah but it's there GuraShrug

patent knoll
#

magic

#

just because i wrote button there it works

#

well, thanks a lot, finishing my planned feature should be like 10 more minutes lmfao

cyan quail
#

well it is a required argument, even if you don't use it

#

allgood

patent knoll
#

One more issue
Despite me doing it correctly and everything working, it says "interaction failed"

cyan quail
patent knoll
#

wdym final callback

cyan quail
#

your current code

#

you probably forgot to respond

patent knoll
#

well
i added about 60 lines of code to my callback lmfao
but, no, the very last line is ctx.respond

cyan quail
#

does it take more than 3 seconds

#

if so, you need to defer at the start

patent knoll
#

no

#

its 1s max

cyan quail
#

could you show the callback then

unique cargo
#

Is pycord support voice recording

patent knoll
#

The code is messy, it allows you to basically keep up an infinite loop of embeds that have buttons, which create embeds with a button, etc.
But this is the only thing that actually does something "back" basically

cyan quail
#

you have to respond to the button's interaction

#

that callback is the only issue here

patent knoll
#

perfect
now i just need self.disable_all_items to work wheeze

cyan quail
#

if you use disable you need to edit the message with the new view

unique cargo
cyan quail
#

though note the examples there may not be 100% accurate

patent knoll
#

suboptimal

cyan quail
#

what were you trying to set LOL

patent knoll
#

forgot a positional

#

i love whenever an object gets printed
i find it so funny

#

this is just python at this point but what in the fuck does it want me to do

cyan quail
#

but either works

round rivet
#

python conditionals are half english

cyan quail
#

kind of weak that it doesn't even offer to replace it for you though

patent knoll
exotic compass
#

umm hey so, for some reason this cog isn't working.

import discord
from discord.ext.commands import Context, Cog, command


class Ping(Cog):  # create a class for our cog that inherits from commands.Cog
    # this class is used to create a cog, which is a module that can be added to the bot

    def __init__(self, bot):  # this is a special method that is called when the cog is loaded
        self.bot = bot

    @command()  # creates a prefixed command
    async def ping(self, ctx: Context):  # all methods now must have both self and ctx parameters
        await ctx.reply('Hello!')

    @discord.slash_command()  # we can also add application commands
    async def ping(self, ctx: discord.ApplicationContext):
        await ctx.respond('Pong!', ephmeral=True)


def setup(bot):  # this is called by Pycord to setup the cog
    bot.add_cog(Ping(bot))

It's being registered like this,


class Handler:
    def __init__(self, bot: BotClient):
        self.bot = bot
        for cog in generate_cogs_list():
            print(f"Loaded {cog.replace('.', '/')}.py")
            self.bot.client.load_extension(cog)
class BotClient:

    def __init__(self):
        self.client = Bot(intents=Intents.all(), command_prefix="!")

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

    def run(self):
        self.client.run(getenv("DISCORD_BOT_TOKEN"))
cyan quail
exotic compass
cyan quail
#

...also that event definition is very off

exotic compass
#

I know

cyan quail
#

remove the @self.client.event and unindent it one level

exotic compass
#

would it work tho?

cyan quail
#

wait....

#
class BotClient:

    def __init__(self):
        self.client = Bot(intents=Intents.all(), command_prefix="!")
```???
exotic compass
#

I'm a java guy and this is not how annotations work there

#

so i am a bit confused but thanks

cyan quail
#

allgood

exotic compass
#

I got my slash command working

#

but not the prefixed command

#

Does discord.Bot also include the commands thingis?

cyan quail
#

oh yeah you need ext.commands.Bot for prefix

exotic compass
#

Would it also suppose application command?

cyan quail
#

mhm

#

the ext bot includes all features

#

discord.Bot is just application commands

exotic compass
#

❤️

cyan quail
#

and discord.Client is no commands

exotic compass
#

@cyan quail What is this due to?

cyan quail
#

is ping in the cog or

exotic compass
exotic compass
cyan quail
#

can you show the full cog

exotic compass
cyan quail
#

oh right

#

your function names have to be unique

exotic compass
#

Do I change it to a bridge command?

cyan quail
#

you can set a different command name by including name=... in the decorator

#

you can also use bridge commands if you want yes

#

need to make sure you're using bridge.Bot too

cloud sand
silver moat
#

the same

cloud sand
#

doesnt seem to work its underlined yellow

silver moat
#

.idw

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.

cloud sand
#

can I show you my code?

silver moat
#

yes

silver moat
#

I don't see where you defined message

cloud sand
exotic compass
#

Is there a way to create a default setup() method for cogs?

silver moat
#

btw

@client.slash_command(description = "Discord Ebay Viewer Command")
- async def ebay_view(interaction: discord.Interaction, url: str, views: int):
+ async def ebay_view(ctx: discord.ApplicationContext, url: str, views: int):
exotic compass
#

It's annoying to register a simple class for every cogs

silver moat
#

why?

exotic compass
#

So that, I can read every class that extends cogs

#

and do a automatic bot#add_cogs

silver moat
#

what are you doing that requires like 15000 cogs.

#

it's just boilerplate

exotic compass
#

Nothing but just to ease

silver moat
#

well, this is just the conventional way

cloud sand
exotic compass
#

How can I set default value to a slashcommand option through context

#

like setting a default value of option "channel" to "ctx.channel"

silver moat
#

set it to None and handle it in callback

exotic compass
#

channel = channel or ctx.channel?

wanton palm
#

How do I make a slash command help

#

I dont want ilke a regular help command

#

I want it to be a slash command

#

I havent used cgs

#

pls tell me there is something

silver moat
exotic compass
silver moat
silver moat
wanton palm
#

I mean I need to do the redundant method

#

oof ok

exotic compass
#

I think discord.ui.View is memory based only right?

paper kindle
#

im having trouble getting all members in a role

#

im using role.members but it only returns one person or two people in the list

#

its also saying ctx.guild.members is just me and the bot

proud mason
errant craneBOT
#

Here's the persistent example.

proud mason
silk spindle
#

hello, if there are some advanced python user here could you please have a look to #1099926878451679244 ?

paper kindle
#

oh yeahhh that makes sense

ionic hull
#

hey guys, is it possible to detect who has update emoji?

cyan quail
#

oh i guess that doesn't exist on stable yet

ionic hull
#

thanks

cyan quail
#

well if you really want you can use them on master

white scarab
#

Some of my shards reset from time to time, is there any way to find out why this is happening?
The traceback or something like that.

cyan quail
#

It's normal for a client to disconnect from the gateway after some time, discord will then reconnect it

white scarab
cyan quail
#

Then yeah that's normal

#

This'll print whenever it disconnects from the gateway etc

white scarab
#

I will try activating it to see if there is a problem that I am causing.
But I'm reassured to see that it's normal.

Thank you very much.

edgy coral
#

is there a way to detect what was typed as an argument?
for example i have /command object:str type:str, if object:option1, i would like to have a specific autocomplete for type:str

sorry if this doesnt make sense as much 😔 (i might add an image to get my point across)

errant craneBOT
#

Here's the slash autocomplete example.

young bone
#

@edgy coral

edgy coral
fervent cradle
#

Hey, does py-cord support setting default_member_permissions at all? Because some of my commands do show up by default to everyone despite being directed towards administrators only (I still put internal checks in, so unauthorized users get a denied message)

restive scarab
#

(Paginator, py-cord)

does it work if you press a button, for example, that you are then forwarded to a specific page

proud mason
silk spindle
#

anyknow already encountered "Can't keep up, shard ID None websocket is 13.9s behind." ?

fervent cradle
proud mason
silk spindle
green hinge
#

With this loop I update the pages from my Paginator. But after the loop has run through, my buttons disappear from my custom_view.
Does anyone know how I have to design it correctly so that the buttons are still displayed after the refresh?

    async def __init__(self, bot: discord.Bot):
        self.bot = bot
        self.pages = await self.update_pages()
        view = await self.generate_view()
        self.custom_buttons = [
            discord.ext.pages.PaginatorButton("first", label="<<", style=discord.ButtonStyle.primary, custom_id="first_button"),
            discord.ext.pages.PaginatorButton("prev", label="<", style=discord.ButtonStyle.red, custom_id="prev_button"),
            discord.ext.pages.PaginatorButton("page_indicator", style=discord.ButtonStyle.gray, disabled=True, custom_id="page_indicator_button"),
            discord.ext.pages.PaginatorButton("next", label=">", style=discord.ButtonStyle.green, custom_id="next_button"),
            discord.ext.pages.PaginatorButton("last", label=">>", style=discord.ButtonStyle.primary, custom_id="last_button")]
        super().__init__(pages=self.pages, use_default_buttons=False, custom_buttons=self.custom_buttons, custom_view=view, timeout=None, author_check=False)

    async def update_loop(self):
        while True:
            self.pages.clear()
            self.pages = await self.update_pages()
            await self.update()
            await self.message.edit(view=self)
            await asyncio.sleep(60) 

    async def generate_view(self):
        view = SpotDetails(self.bot)
        return view```
patent knoll
#

why are you using a while true loop?

solemn idol
green hinge
# solemn idol do yourself a favor and use tasks ;)

Like this? 🙂

asyncio.create_task(self.update_loop())    

@tasks.loop(seconds=60)
    async def update_loop(self):
        self.pages.clear()
        self.pages = await self.update_pages()
        await self.update(use_default_buttons=False, custom_buttons = self.custom_buttons, custom_view = await self.generate_view())
green hinge
young bone
#

it is already a loop

#

it will run every 60 seconds

#

you just have to do ```py
update_loop.start()

green hinge
#

Yes I just had a thinking error 😄

silk spindle
fervent cradle
#

Just wondering if its possible to reset the users choice on a select menu?

#

e.g. the user selects something and it runs the code for it, then unselects it so they can select it again

wicked helm
#

Howdy! I am running a background task that updates all users in the discords roles..

I have noticed that the first time the for loop runs. It takes 1.5 seconds to update all the roles. Then it takes ~ 8 seconds for each member.. ANy ideas as to why?

fervent cradle
wicked helm
#

Or responses sorry

#

That I'm aware of.. D:

full basin
fervent cradle
#

and doesnt error afaik

wicked helm
#

Ah

fervent cradle
#

from what i remember too

wicked helm
#

That could be it then.. thinkCat

#
try:
                        guild = self.bot.get_guild()
                        member = guild.get_member(int(member_id))
                        await member.add_roles(
                            *[
                                discord.utils.get(
                                    guild.roles, name=membership_list[membership_index]
                                ),
                                discord.utils.get(guild.roles, name=rank_list[rank_index]),
                            ]
                        )
                        await member.remove_roles(
                            discord.utils.get(
                                guild.roles, name=membership_list[membership_index - 1]
                            )
                        )
                        for i in [1, 2, 3, 4, 5]:
                            await member.remove_roles(
                                discord.utils.get(guild.roles, name=rank_list[rank_index - i])
                            )
                    except AttributeError as error:
                        logger.error(error)

Probably something to do with the last part where I remove the roles that I don't want to remain on the users

fervent cradle
#

you might want to add a slight delay when iterating through users

errant craneBOT
#

ccc_assistant/cog.py lines 55 to 56

while do:
    artist_message: AristMessage = await self._image_to_process_queue.get()```
full basin
#

Use a task

#

Which does the exact same thing you're trying to do

fervent cradle
#

hey dark do you know if it is possible to reset the choice on a dropdown menu

wicked helm
fervent cradle
#

you can possibly lower it to see where the sweet spot is

wicked helm
#

Well I asked it to wait 2 seconds and it too 2 seconds off the " delay"

#

But over all it still takes the same amount of time

silk spindle
full basin
#

Yes.

fervent cradle
# full basin What

for example the user clicks on a choice in the selectg menu and then it runs the code and resets the choice

#

as if the user never clicked anything

#

i cant find anything in docs or google about it

full basin
#

It has .start() and .stop() methods

errant craneBOT
#

Here's the background task example.

full basin
#

@silk spindle ^

cyan quail
#

it's scuffed but it's a client thing so you can't actually reset it without overriding the view

silk spindle
silk spindle
fervent cradle
#

can i just set a loop to automatically edit it with the same view every ~60seconds or would that not work

#

as i dont know how id refer4ence the mesage from the interaction response

cyan quail
cyan quail
fervent cradle
#

ah alright i didnt realise you could do that

#

so i'd just do insteraction.message.edit(view=dropdown())

cyan quail
#

or even just view=self

#

assuming this is inside a subclassed view

fervent cradle
#

ah yeah

#

thanks i didnt realise i could do that

wary rover
#

Hi there!
I have a little problem,

I connect the bot in the channel but when I play a sound the bot tells me that it is not connected.

This problem occurred after it tried to talk in an AFK channel, I don't know if it can come from there.

Any clue?

#
discord.errors.ClientException: Not connected to voice.```
young bone
wary rover
young bone
#

update to 2.4.1

wary rover
wary rover
#

Thanks man

young bone
#

wait

#

they changed the message links

cyan quail
#

yeah a bit neater now

young bone
#

I like it

cyan quail
#

(technically this change actually existed for ~a year prior but most libs didn't implement it)

wary rover
#

My bot worked 1h and then impossible to play a sound, in visible reason it stopped working.
I would never have thought of this update.

green hinge
#

Is it possible to make a paginator persistent so that the buttons etc. still work after a restart?
Because a paginator has no attribute custom_id which I would need or?

#

I have tried this but I always get the message that "NoneType" is not editable.
Do I have to cache the message await paginator.send(ctx) with the Guild_ID, the Channel_ID and the Message_ID here and then read it again at the bot.ready event so that I can find the message?

class Test(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.persistent_views_added = False
    
    @commands.Cog.listener()
    async def on_ready(self):
        if not self.persistent_views_added:
            for guild in self.bot.guilds:
                self.bot.add_view(await PaginatorInfoView(self.bot, guild.id))
                paginator = await PaginatorInfoView(self.bot, guild.id)
                if paginator.task is None:
                    await paginator.start_loop()           
            self.persistent_views_added = True

    @commands.command(name="show")
    async def page(self, ctx):
        guild_id = ctx.guild.id
        paginator = await PaginatorInfoView(self.bot, guild_id)
        await paginator.send(ctx)
fervent cradle
green hinge
fervent cradle
#

Issues so far:

  • dm_permission flag ignored on @slash_command decorator
  • default_member_permissions ignored when set after command definition
  • persistent views are not persistent
#

You should also call bot.add_view(MyView()) when on_ready is called

#

In your case you have to instantiate the whole object with parameters

green hinge
#

I have not yet figured out how to get a Paginator persistent.
It is said everywhere that the paginator class behaves like a view but you can't assign a custom_id to the paginator class and with bot.add_view(MyView()) it doesn't work either.

#

When I try it this way I always get this error because it doesn't know what message it is because I can't assign a custom_id like with buttons etc..

await self.update(use_default_buttons=False, custom_buttons = self.custom_buttons, custom_view = await self.generate_view())```

AttributeError: 'NoneType' object has no attribute 'edit'```

green hinge
fervent cradle
#

I don’t know either
I am now trying to figure out how paginators work and how to set custom ids on them

green hinge
fervent cradle
#

You are awaiting a constructor, is that supposed to be?

green hinge
#

per outputs with True but I still get this error because it probably doesn't know which message to update which is supposed to happen via the custom_id 🤔

    @commands.Cog.listener()
    async def on_ready(self):
        if not self.persistent_views_added:
            for guild in self.bot.guilds:
                self.bot.add_view(await PaginatorInfoView(self.bot, guild.id))
                paginator = await PaginatorInfoView(self.bot, guild.id)
                await paginator.update()
                per = paginator.is_persistent()
                print(per)```

AttributeError: 'NoneType' object has no attribute 'edit'```

fervent cradle
#

Also you are instantiating the same object twice

silk spindle
# cyan quail you theoretically could if you tried to subclass or something, but you'd be bett...

https://github.com/Pycord-Development/pycord/blob/master/examples/background_task_asyncio.py I really struggle. Trigger a background task using arguments from a command.

GitHub

Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/background_task_asyncio.py at master · Pycord-Development/pycord

grizzled sentinel
#

I'm not exactly sure how you set it up. But you could have a dict mapping the argument to the task and than just do something like this
tasks[argument].start()

green hinge
wicked helm
#

Can I get the name of a members rank? I want to check if the member has a rank to skip updating it..

torpid wraith
wicked helm
#

AH, nice thanks!

torpid wraith
#

If I’m subclassing my bot, is it possible to define slash commands within the class? If so, what would that look like and how would I specify kwargs without the decorator being present?

royal acorn
#

If I understand correctly, ctx.defer() is cnsidered a reply to the interaction

#

because i am not able to do send_modal afterwards

proud mason
torpid wraith
proud mason
proud mason
silent meadow
#

hey, this is a very simple and dumb question...

but I have been seeing places where the bot mentions the number of lines of code it has been written in.... any idea how can I do that too?
I can make the embed and stuff... I just wanna know how can i count the number if lines of code in a repo
i know the readlines() and len() methor
but like is there any round the way i could do it for all files all together? like cog files, json files and others?

full basin
grizzled sentinel
#

Make sure you do that at startup and not everytime the command is called though.

coarse cargo
#

There is no way of getting the guild of the interaction?

versed fern
#

interaction.guild or ctx.guild

#

If you would type hint it should show up automatically

proud mason
coarse cargo
tired goblet
#

if i have the direct link url to an image, how can i send it to discord?

tired goblet
#

await ctx.respond('https://zapquaker.netlify.app/img/card.jpg') if i use this, it sends the image, but also the url

#

anyway to send just the image and the url text doesn't appear?

young bone
#

you could download it and send it

tired goblet
#

oh

#

okay thanks

green hinge
#

Can I send the ephemeral message to a specific user instead of me?

await ctx.response.send_message(embed=embed, view=RateButtons(self.bot, user), ephemeral=True)    ```
grizzled sentinel
finite flame
#

what the heck is this error?
code:

def write_json(path: str, data: dict | list):
    with open(path, "w") as f:
        json.dump(data, f, indent=2)```
exception:

Traceback (most recent call last):
File "main.py", line 3, in <module>
from classes.settings import Settings
File "/home/bot/bots/service_droid/classes/init.py", line 1, in <module>
from .settings import Settings
File "/home/bot/bots/service_droid/classes/settings.py", line 3, in <module>
from ios import read_json, write_json
File "/home/bot/bots/service_droid/ios/init.py", line 1, in <module>
from .json import read_json, write_json
File "/home/bot/bots/service_droid/ios/json.py", line 10, in <module>
def write_json(path: str, data: dict | list):
TypeError: unsupported operand type(s) for |: 'type' and 'type'```

young bone
#

what is data?

finite flame
#

but it already failed at the import

finite flame
#

found the problem: wasn't using my venv and with that also not 3.10, which adds the feature with the pipes

red geyser
#

How can I send a DM message to the message author?

young bone
red geyser
#

huh?

young bone
#

at a command

#

or someone joins the server?

red geyser
#

Yeah I have a command, i just want it to send the response via dm, and not as a normal message in the channel the command is ran

red geyser
#

thanks

torpid wraith
#

If I subclass my bot, are there any security concerns with storing the bot's token as an instance variable of the bot? (And by concerns, I mean glaring concerns; this bot won't be very public)

cyan quail
#

If you for some reason have an eval command, just make sure perms are setup correctly

torpid wraith
#

Gotcha, thx 👍 And by eval you mean a Python eval and not a Bash eval, right?

cyan quail
#

Mhm

torpid wraith
#

Is there any clean way to check if a user defined guild ID is valid without the API throwing an error?
I currently have this, which prints my custom error, but the API still prints its error:

# Check that guild_id is valid
guild = self.get_guild(self.guild_id)
if guild == None:
    print(f"ERROR: Could not find valid guild with ID: {self.guild_id}")
    await self.close()```
#

I also attempted to do Try/Except, but the API error was not caught.

cyan quail
#

Not really

torpid wraith
#

Fair enough, thx ❤️

cyan quail
#

You're looking for client.fetch_guild

#

But it'll only work for guilds the bot is in

torpid wraith
# cyan quail You're looking for client.fetch_guild

Am I?... (honest question) I'm ultimately just trying to input guild_ids for the @bot.slash_command decorator. I currently have the end-user define an environment variable with the ID of the guild the bot will join, but am struggling with input sanitization.

#

Maybe there's a better way to do this?

cyan quail
#

oh i see

#

hm

torpid wraith
#

I feel like it's chicken-in-the-egg, because I need the guild id from the bot, but the commands get defined before the bot instance exists

cyan quail
#

yeah you can't really validate it without making a request

#

is this for a custom command system

torpid wraith
#

And there's no way to obtain the guilds the bot is in before defining its slash commands?

cyan quail
#

not the way pycord is structured, no

#

it's technically possible to resync commands even after the bot is connected, however... it's kind of been broken here because of a rather annoying design flaw

torpid wraith
#

So my premonition of it being a chicken-in-the-egg issue is actually correct. Damn, that's too bad, but I can ultimately deal with it for my application. Thanks! 🙂

torpid wraith
#

I have the following two files:
main.py

import os
from dotenv import load_dotenv
import discord
from src import MySubclassedBot

GUILD_ID = None

def main():
    COGS_LIST = [
        "CogCharacters"
    ]

    # Load environment variables
    load_dotenv()
    TOKEN = os.getenv('DISCORD_TOKEN')
    global GUILD_ID
    GUILD_ID = os.getenv('GUILD_ID')

    bot = MySubclassedBot(TOKEN)
    # Add cogs to bot
    for cog in COGS_LIST:
        bot.load_extension(f'cogs.{cog}')
    bot.run(bot.token)

if __name__ == '__main__':
    main()

cogs/CogCharacters.py

import discord
import main
print(main.GUILD_ID)

class CogCharacters(discord.Cog, guild_ids=[main.GUILD_ID]):
    # Stuff...

def setup(bot): # this is called by Pycord to setup the cog
    bot.add_cog(CogCharacters(bot)) # add the cog to the bot

I'm just trying to get GUILD_ID from the main function to the cog py file so it can be used in the class definition. I feel like this should work because main should be called and executed before Python even knows the cog file exists, but print(main.GUILD_ID) still prints None. Does Python get pre-compiled to byte-code? Maybe that's why the class is created before main() is run?

cyan quail
#

ultimately you've overcomplicated it, you can just use bot.get_cog to get the class and set cog.guild_ids

torpid wraith
#

Omg you're a life saver... This makes so much sense, is way easier, and I learned something new about importing (well, I already kinda knew, I was just being dumb 😅 )

cyan quail
#

yeah gotta understand importing first

#

what you were trying to do would have normally lead to a circular import

#

never let files import each other

torpid wraith
#

I didn't think main.py was importing the cog, but I guess the API function load_extension kinda does that, doesn't it?

cyan quail
#

well that's what i meant by normally, load_extension is designed to work around imports but if, for example, you weren't using this lib it could be something like ```py

main.py

import os
from dotenv import load_dotenv
import discord
from src import MySubclassedBot
from cogs import CogCharacters

bot = MySubclassedBot(TOKEN)
cog = CogCharacters(bot)

...

CogCharacters.py

import discord
import main # instantly error on this line```

#

since import main would then do all the imports in main, which would lead to doing all the imports in CogCharacters... and so on, an infinite loop so python just says no

torpid wraith
#

Gotcha. Makes sense. I think I just went down a rabbit hole and started spaghetti coding, lol. Thank you very much for helping me on my journey to get gud at Python 😅

proud mason
#

yk like

def setup(bot):
  cog = MyCog(...)
  cog.guild_ids = bot.some_attr
  bot.add_cog(cog)
torpid wraith
#

So, I'll try your way, which should work 🙂

jaunty jewel
#

how the commands cannot be used by the specified user to be like this, as my knowledge i can hide the command (which is the thing that i searching for) if the channel that command begin used for is NSFW or guild_only for e.g, however, how it can be selected for a user or role :\

idk if it's one of the (default_member_permissions) or (checks) Attributes :\

jaunty jewel
#

huh, someone forgot a todo task :)

plush meadow
#

I'm having an issue which seems to be pretty common but I can't quite grasp the solution, or why it works. I am trying to delete an ephemeral message upon the user interacting with my view, but regardless of the method I use, the message is not found

#

obviously we know the delete() method doesn't work on ephemerals, so I went for delete_original_response(), which seems to timeout after a few moments of not finding the message

cyan quail
plush meadow
#

yeah that's the one I tried first

#
class ConfirmView(discord.ui.View):
    @discord.ui.button(label='Submit', style=discord.ButtonStyle.green, emoji='✅')
    async def submit_request(self, button, interaction):
        await interaction.message.delete()
cyan quail
#

that's working fine on my end

plush meadow
cyan quail
#

it works with ephemerals because discord added support for it months ago

plush meadow
#

I didn't know that, that's a good update, but nonetheless I can't seem to delete it

#

hmm

cyan quail
#

delete_original_response is for deleting responses you do with response.send_message, not the original message

#

if it's not working then there's a chance the user already dismissed the message

plush meadow
#

if any additional context will matter, here's where the view appears:

await ctx.reply(embed=embed, view=ConfirmView(), ephemeral=True)
#

upon calling a command of course ^

#

I'm absolutely baffled

distant roost
#

does anyone know how i can get a member object through an id because my view class is outside the setup function in the cog and i need so send an message to a user with a button

proud mason
#

@plush meadow can you try that?

#

Defer first and then use delete original response

plush meadow
#

let me give it a go

plush meadow
#

that seems like a bandaid fix, but perhaps it's not and i just don't get the inner workings

cyan quail
#

oh it's not actually a bandaid, discord considers it intentional

plush meadow
#

i mean visually it works flawlessly, but this is itching my head since Nelo mentioned interaction.message.delete() is supposed to work as intended

cyan quail
#

i forgot it's because the standard endpoint doesn't work with it nicely

plush meadow
#

oh, i see

#

i mean if that's the proper way to write it, i'm more than satisfied. thank you both for your help!

distant roost
#

user = interaction.guild.get_member(id) doesn't work

wicked helm
# torpid wraith `role.name() for role in User.roles`

Can I use this to add and remove roles at the same time?

Currently I am adding a role from a list, and the. Removing all others in the list from the user.

This seems to result in discord timing me out for a couple seconds… so updating a list of 8 users takes 50 seconds

cyan quail
#

this is also doable with add_roles and remove_roles if you set atomic=False, it'll be a single request

proud mason
#

the most important one, is that you dont need to send a followup, unlike app cmds

#

secondly, the edit_original_response and delete_original_response endpoints now point to the message the item was attached to

#

so that allows for your use case

proud mason
modest mica
#

Hey guys,
Is it possible to send a modal to a specific channel which was given by a slash command?

So /command <channel> -> Getting the id -> Opening Modal, then filling it -> Sending the content to the channel what I give in the slash command

cyan quail
#

do you mean an embed?

#

you can't "open" a modal in another channel

#

it'll just popup wherever the user currently is

young bone
#

you have to open a modal with an interaction

modest mica
#

So yes, basically I want to send an embed to the channel I typed in the slash command, but I want to write the content with a Modal, then send the embed to that specific channel

cyan quail
#

yeah that's straightforward enough

#

have you subclassed your Modal?

modest mica
#

Yes, I've made the Modal class

cyan quail
#

then you're more or less done

#

assuming you've overridden __init__, add another argument for your channel

#

then assign it as a self variable and use it in your callback

modest mica
#

Alright

plush meadow
#

Would someone be kind enough to demonstrate how I'd make a view persistent on restart? Views are a bit confusing to me in the first place so the docs are a little unclear for me.

#

I've made my timeout None already, but I'm having a hard time figuring out where to stick the persistent boolean

grizzled sentinel
plush meadow
#

really? I could have sworn I remember something like that

#

let me give it a go and see

errant craneBOT
#

Here's the persistent example.

grizzled sentinel
#

This can help if you have not seen it yet

plush meadow
#

ah okay wait, I am not adding anything in my on_ready() listener

#

so I just have to add the view itself, and all the messages which utilize the view will automatically work again?

#

and no I had not seen this, thank you very much

modest mica
#

Okay, managed to do what I wanted, but when I submit the modal, it doesn't close itself. I didn't get any error message in the log, only Discord tells me something went wrong.

cyan quail
#

you have to somehow respond as well as do your other logic; either by send_message, edit_message or defer

modest mica
#

Ohh, I didn't. I responded for the command within the command, and not inside the modal class. I fixed it, now it works perfectly 👌

Thanks for the help, really appreciate it 👍

plush meadow
#

So I feel like I'm very close to getting persistent views to work, save for one issue. My buttons are dynamically loaded, they are not hardcoded into the view. So when "caching" them, I can't just send a blank view with no buttons. That being said, in the example, it mentions that # In a more complicated program you might fetch the message_id from a database for use later. I am actually already saving these messages in a database, so what's the recommended way of caching them via message ID? the example doesn't explain that part

#

I am referring to the prepare() coroutine in the example at line 68

silver moat
#

Is the tag botvar encouraging bad practices? Shouldn't sub-classing be encouraged instead?

pallid token
#

Just wondering... When did client.load_extension become async?

cyan quail
#

in another universe

#

(you installed dpy)

pallid token
#

I'm running py-cord...

#

2.4.1

cyan quail
#

well you aren't if it's async

regal agate
#

hey is there anyway to get a members activity status?

cyan quail
#

probably member.status

pallid token
regal agate
#

im looking it up but im only getting member.activities[0].name

cyan quail
#

we never made load_extension async

regal agate
#

which gives me a empty tuple

pallid token
regal agate
cyan quail
regal agate
#

like the names you can put with a status

cyan quail
#

custom status?

regal agate
#

yeah

cyan quail
#

i think that isn't available on api

regal agate
#

theres a listener for it

#

really?

cyan quail
#

hold on

regal agate
#

theres threads on it so im guessing it has it

cyan quail
#

ok yeah it's under activities, didn't realise discord threw away my status again

#

but you probably need the presences intent

regal agate
#

so i dont need the list?

cyan quail
#

?

regal agate
#

it says it sends a python formatted list

#

idk if its outdated info

cyan quail
#

activities will always be a tuple/list

#

since it's possible to have multiple

regal agate
#

so why when i use activities[0] its out of range?

cyan quail
#

though i think activity just returns the first one

#

does your bot have the presences intent

regal agate
#

it has all

#

i actually only need the main activity

#

so maybe the first solution would work

deft mirage
#

is there any clean/kosher way to remove a bot from a server from the backend?
my use case is: I provide a paid product and one customer has ghosted me. the bot is still on their server. Can i remove it somehow?

#

i have blocked them from doing anything with it but it's still there in the list and consumes 'some' resources

winter condorBOT
proud mason
#

get the guild object using bot.get_guild

deft mirage
#

appreciate it

proud mason
#

np

loud holly
#

is there a way to disable the debug, I haven't installed or enabled anything and this started spamming the console

loud holly
#

Fixed it

solemn idol
neon bramble
solemn idol
#

I know but still

#

"Fixed it" is just blobpain

young bone
#

Why do you even use logging?

neon bramble
#

it can be useful sometimes

#

for like debugging

solemn idol
#

young bone
#

uh yea but if you gonna host more than one bot it can be annoying

#

I use pm2 and it would spam the pm2 logs

neon bramble
#

just log to a file then

solemn idol
#

#

I just make it overwrite everytime my bot restarts

#

and I'm not saving Debug in just doing Info

#

Debug will probably need a lot of space very very soon

#

For a small application

neon bramble
#

yes?

proud mason
#

||this is pycord.... but that thing is the same. so you are lucky||

distant roost
#

Does anyone know if you can just have 1 slash command group because the commands from my second group won’t register

proud mason
distant roost
#

ok

#

thank you

proud mason
#

yea. share your code if your cmds arent registering

#

also

#

.tag slashnoshow

winter condorBOT
#

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)?

solemn idol
#

A thing I never understood; why use bot.commands in main file but discord.commands in a cog.
Why not just use self.bot.commands or discord.commands in both. 🤔

solemn idol
#

cogs use discord.commands

silver moat
#

wdym

solemn idol
#

When defining a command

#

Decorator

#

You use discord.command in cogs

silver moat
#

isn't it just @discord.slash_command

solemn idol
#

yeah or that.

#

Nonetheless the discord part

#

Why is it bot in main file and discord in a cog

#

Why not just make them both the same

#

And use discord

silver moat
#

because in the main file, how do you know what the bot object is otherwise

#

in the cog, you are provided with the bot object

solemn idol
#

Hmmm okay...

#

@violet magnet.bot pogbruh

#

Oh fk

#

I don't know who I just pinged

silver moat
#

that doesn't work because self is not defined

solemn idol
#

in a cog it should be in the init... No?

silver moat
#

decorators aren't inside a function/method.

solemn idol
#

ah okay 💀

#

makes sense, lol thanks

silver moat
#

making it static would cause... more problems

solemn idol
#

kk tyvm

silver moat
#

yw

distant roost
coarse spire
#

How can I get the context from an on_message event?

proud mason
#

what are you trying to do?

coarse spire
#

Ah, ok. I'm trying to do async with typing in an on_message event

proud mason
#

.rtfm channel.typing

proud mason
#

yep

coarse spire
#

Oh, ok. Thanks 😄

proud mason
#

Context just provides shortcuts to these methods. You can do almost everything without it

coarse spire
#

Oh, ok. Well, thanks, it works now 🙂

proud mason
#

nice

patent knoll
#

Is there any quick way to prefill slash command options made with bridges?
e.g. i wanna have a field with 2 options, how can i make it suggest these 2 options automatically?

celest gulch
#

I launched my bot today and it started to print out an bunch of debug info after updating pycord what da hell?

grizzled sentinel
grizzled sentinel
grizzled sentinel
celest gulch
patent knoll
grizzled sentinel
#

Do you have logging enabled? Or a debug value set somewhwre?

celest gulch
#

This is what it prints, an bunch of info about the discord servers its in etc. This is my main startup code

young bone
grizzled sentinel
celest gulch
patent knoll
#

well thats kind of the problem lol, i tried around a lot and didnt manage

young bone
celest gulch
grizzled sentinel
patent knoll
#

type hinting how
currently i just made it as boolean but i might wanna add a third option later, that's why i asked

this correctly shows True and False, obviously, but i'm stuck at how to make it properly

#

oh wait, i think i know what you mean, 1s

heavy bough
#

Is there a way to fetch the users that are interested in an event using pycord? With discord.py it works, with pycord it’s returning „none“. And it’s not returning the creator of an event either

celest gulch
#

Can anyone help??

patent knoll
#

Okay, i am trying to switch to using the decorator to set up my slash command arguments, however I cannot get it to show a list of users like it used to

#

This, in the function arguments, showed it perfectly fine

patent knoll
#

Okay i advanced lol

#

how tf do i make the input_type of an option "user", i already tried discord.Member

grizzled sentinel
patent knoll
dense tide
#

how do I get an normal Interaction if I only have the Message

proud mason
#

interactions are created for each button press, app cmd run etc

full basin
#

What's even a "normal" interaction supposed to mean

dense tide
proud mason
#

that is for messages sent by interactions (of other bots too)

#

for eg

errant craneBOT
#

Here's the basic voice example.

proud mason
dense tide
#

oh okay thx

patent knoll
# patent knoll nothing

anyone have an idea
it works when i just use user: discord.Member in the function arguments without any decorator stuff

dense tide
patent knoll
#

it doesnt work.

#

Here, no autocomplete suggestions

dense tide
#

try this :

patent knoll
#

Okay, wtf, that works, but only if i pass it without a keyword - why?

#

Shouldn't
discord.Option(input_type=discord.Member)
and
discord.Option(discord.Member)
be the same?

dense tide
#

no bc input_type requires
input_type=<class 'str'>

patent knoll
#

so when can you actually use input_type=

dense tide
#

I actually dont know

#

If I only have the Message can I give a respond which only the user who sent the message can see?

patent knoll
#

yes

#

add ephemeral=True

#

Next question, what tf does "autocomplete" take?
I tried ANYTHING i could think of

dry echo
#

hello, i forgot how i can do dynamic button titles with add_item() is there any guide out there?

dense tide
# patent knoll yes

that would work if I have the ApplicationContext but I don't I just have the Message -> discord.Message

exotic compass
#

how do i create a permission ovewrrite

agile dust
#

I need some help with pycord (I'm new to it).
How do I create options for slash commands? I have looked at the docs but they are very spartan and do not provide much detail in this topic. A code snippet would be nice.

dense tide
agile dust
dense tide
agile dust
dense tide
#

what do you mean with permission-only commands

agile dust
proud mason
# patent knoll Next question, what tf does ["autocomplete"](https://docs.pycord.dev/en/master/a...

it accepts a function
that function should have only 1 argument of AutocompleteContext

also see this

GitHub

Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/slash_autocomplete.py at master · Pycord-Development/pycord

green hinge
#

Can I somehow find out when a user joind via an invitation link to the server from whom this user was invited?

dense tide
proud mason
green hinge
cyan quail
#

not available directly

#

the best you can do is constantly track invite usages, then in the join event see which one changed

proud mason
cyan quail
#

the example kinda shows you already

errant craneBOT
#

Here's the slash autocomplete example.

patent knoll
#

oh, i called the function