#Basic Pycord Help

1 messages · Page 11 of 1

opal hamlet
#

a discord Cog is a .py file, that gets loaded into the main bot

autumn gust
#

oh

#

and have the entire bot be classless?

opal hamlet
#
async def on_ready():
    global botversion
    with open(Path(sys.path[0],os.path.basename(__file__)), 'r') as f:
        l1 = f.readlines(1)
        botversion = l1[0].strip('#Version: \n')
    print(f'Version: {botversion}, Logged on as {bot.user}')
    logger.info(f'Version: {botversion}, Logged on as {bot.user}')  
    version_control.start()  
    await bot.change_presence(activity=discord.Game('Star Citizen 🚀'))
    await status_msg()```
#

no need to subclass the bot

autumn gust
#

there is no subclass, though?

#

there's just one class

opal hamlet
#

how did you even initialize the bot at the beginning of your code

opal hamlet
#

hmhm

autumn gust
#

all of those are outside the class

opal hamlet
#
@bot.event
async def on_ready(self):
    print(f"I'm alive, at {self.user}!")

@bot.event
async def on_message(self, message):
    print(f"{str(message.author).rstrip('#0')}: {message.content}")

@bot.event
async def on_member_join(self, member):
    userID = member.id
    channel = bot.get_channel(1155232310468280320)
    welcomeChannel = bot.get_channel(1130586203855540266) 
    getCurrentDate()
    userMention = member.id
    userAvatar = member.avatar.url
    userDisplayName = member.global_name
    userName = member.name
    userIDstring = str(userID)
    if userIDstring in whitelistIDs:
        await channel.send(f"{date_time} | `Traffic Syndicated for {userID}, recognised as {whitelistIDs[userIDstring]}`")
        await welcomeChannel.send(f"Greetings, {member.mention}")
    elif userIDstring in blockedUserIDs:
        await channel.send(f"## **{date_time}** | @autumn gust `Potentially Dangerous Traffic Blocked: {userID}, recognised as {blockedUserIDs[userIDstring]}`")
        await channel.send(f"Mention: **<@{userMention}>**\n Avatar: **<{userAvatar}>**\n Name: **{userName}**\n Display Name: **{userDisplayName}**")
        await member.send("You were kicked, reason: Banned on the Whitelist.")
        await member.kick(self, reason="Banned on Whitelist.")
    else:
        await channel.send(f"## **{date_time}** | `Remote Traffic Blocked: {userID}`")
        await channel.send(f" - Mention: **<@{userMention}>**\n - Avatar: **<{userAvatar}>**\n - Name: **{userName}**\n - Display Name: **{userDisplayName}**")
        await member.send("You were kicked, reason: Remote Traffic Blocked; Disconnected.")
        await member.kick(reason="Connection Denied.")```
#

decorators @autumn gust

autumn gust
#

huh

opal hamlet
#

gotta use @bot.event

autumn gust
#

neat

opal hamlet
#

god i wish i could remember what part of my bot i was working on exactly

autumn gust
#

ADHD in a nutshell

#

"oh I should do this prob"
3 minutes in
"yo wat's that"
...
"what was I doing again?"

opal hamlet
#

i know what it is and what it does, how it does it, but i forgot what else was needed lol

autumn gust
#

ever heard of... checklists?

opal hamlet
#

do i look like i organize my shit?

autumn gust
#

sadly, my adhd wins over my autism in the organisation department

#

my urge to be as organized as can be is non existant

opal hamlet
#

ugh dont you hate it when for some reason your pc decides to forget shortcuts exist and you gotta restart your pc

#

I mean atleast i decided to draw a previous version of my database

#

It was… chaotic

#

Now my db is probably less efficient but i know what the fuck it does this time

autumn gust
#

hmmm

opal hamlet
#

ur shit workin?

autumn gust
#

trying to figure out the complicated tidbits

#

but somewhat

#

now to figure out how to check if user has default permissions or not

autumn gust
#

if the user has the permissions required to run the command, and respond differently if they don't

little cobalt
#

They cannot see the command

#

With default_permissions

autumn gust
#

AAAAAAAAAAAAAAAAAA

autumn gust
autumn gust
#

for reference

opal hamlet
autumn gust
#

oh...

#

now it works, thnks

#

oi @opal hamlet how do you make the slash command ask for a thingy

#

like input

#

/terminal input: for example

opal hamlet
#

async def funcname(ctx, input, otherinputvalue):

#

@autumn gust

autumn gust
#

btw do you mind if I ping you for those kinds of things or na

#

I should've asked before

#

I assume input returns a string?

opal hamlet
#

Don't care, one more notification doesn't hurt if i have my phone on mute lol

opal hamlet
autumn gust
#

so for a simple command system,

if input == "test1":
elif input == "test2":
else:

will work

opal hamlet
#

you can also do async def funcname(ctx, input:discord.Option(variabletype f.e. str, int)

#

You can also specify a description for the input argument inside this discord.Option(..., description='good desc!')

autumn gust
#

use code blocks maybe

#

code's barely readable without them

opal hamlet
#

Ah yeah

#

Im eating and on mobile, couldn't be bothered lol

#

Ill send you an example later

#

Did you know you can localize command names and description?

autumn gust
#

huh

#

wdym by localize

#

like swap into other languages?

#

I wonder, how to make a bot refresh

#

oh, how do I make a message ephemeral

#

ctx.send("test").ephemeral?

opal hamlet
#

Close

#

ctx.send('msg',ephemeral=True, delete_after=seconds) if you want it to auto delete after x seconds

opal hamlet
#

@autumn gust localization

autumn gust
#

let's goo

#

wait

#

not the ()

opal hamlet
#

you know you could make that thing 2 lines shorter right

autumn gust
#

of course

#

like this

#

I assume

opal hamlet
#
await ctx.send(f'pinging... {bot.latency*1000}ms')```
autumn gust
#

o

opal hamlet
#

some shit can just be ridiculously short

little cobalt
opal hamlet
#

cant you still ctx.send

little cobalt
#

yes but not with ephemeral=True and you get every time a error

opal hamlet
#

nope

#

i am defering it beforehand tho

little cobalt
#
@client.slash_command()
async def test(ctx: discord.ApplicationContext):
    await ctx.defer()
    await ctx.send("test", ephemeral=True)
opal hamlet
#

it literally works for me

#

may cuz im not on dev version?

little cobalt
#

I use the dev version

#

because it also works with sync commands

opal hamlet
#

i know that "it works on my device" is something no dev wants to hear, but it does

little cobalt
opal hamlet
#

prevents it from erroring that app isnt responding

little cobalt
#

So, with slash commands you have to respond after 3 seconds

#

if you dont do it you get an error

opal hamlet
#

bascially just tells discord, yup i saw that interaction

little cobalt
#

with ctx.defer you have more time

autumn gust
opal hamlet
#

show code

little cobalt
autumn gust
#

ctx.send

little cobalt
#

use ctx.respond for slash commands

autumn gust
#

oh.

shell radish
#

what the heck is command

autumn gust
shell radish
#

bruh

autumn gust
#

it works

opal hamlet
#

round that shit ASAP

#

my eyes

#
round((bot.latency*1000),2)```
autumn gust
#

just because you kindly asked me to round it

#

I won't

opal hamlet
#

anger

autumn gust
#

but nah I didn't know that was a thing

#

I was lowkey about to go nag Pillow about it

edgy nest
#

why would you nag pillow to round numbers

autumn gust
#

they're a python and xml nerd

edgy nest
autumn gust
ember crane
autumn gust
opal hamlet
#

lmao

autumn gust
#

yeah meet Pillow, he was carrying my ahh here until he redirected me here with stupid questions

opal hamlet
#

lol

#

do be like that sometimes

autumn gust
#

fr

autumn gust
#

what's the on bot join guild event called

#

or is it discord.on_guild_join

#

and I'm just shit at reading

lofty parcel
#

Yes

autumn gust
#

wow

red mist
#

Literally need help to structurize my cogs.

Im unsure wether to make a cog with multiple commands or 1 cog per command.

Recommendations?

little cobalt
#

and with pycord-multicog I can use the slash groups at other files

red mist
#

idfk ab multicogs

edgy nest
#

otherwise i would have 80 extensions

#

& fuck that

tidal estuary
#

How would I go about approving user_id to speak on a stage? I took a gander at the manual for about half an hour and am stumped.

#

If there's some method on a Member that's cool too

#

Oh.. I think it's Member.edit(suppress=False)

#

If that's wrong poke me, but it's there for posterity and ctrl + F

tidal estuary
#

Now I can't figure out how to get the TextChannel that gets stapled to every stage so I can send messages ._.

opal hamlet
#

Well maybe you can actually send messages to the stages channel id?

#

Just get or fetch it

tidal estuary
#

Nice. Haven't got to the line where I can even see if that part works yet, lol. I can't figure out why bot.fetch_stage_instance(id) is 404ing. I know the ID is right.

autumn gust
#

hm, so in general

#

what are cogs

red mist
# autumn gust hm, so in general

Basically, you know how you can put all of your commands in your main.py file or bot.py file? You can put them in cogs which are basically an extra set of files which contain your commands.
Cogs themselves are actually the classes tho, for which you'd need to ReadTheDocs. :)

lapis dock
#

With prefix commands the nice thing with cogs is you could load/unload them without restarting yout bot. This does not work for slash commands though.

little cobalt
#

sync commands is working

lapis dock
#

Overall I dont think loading/unloading slash commands is good even if it technically works.

stoic patio
#

how do you find when ppl change their display names

#

bc it doesn't fire with on_user_update

#

it does for on_member_update, but it says "member object has no attribute global_name"

#

and i believe i'm using the latest version of pycord

little cobalt
stoic patio
#

i installed with -U option, and it shows "0.1.1" when i do pip list

lapis dock
#

Can you show your full pip list please

stoic patio
#

(don't question the libraries with funny names)

lapis dock
# stoic patio

You will need to uninstall

discord-components
discord-py-slash-command
DiscordUtils <- I think Unless it is literally just helper functions
pycord

Then uninstall and reinstall py-cord. Notice the dash, there is a different library (you also have installed) called pycord this is for something completely different.

autumn gust
#

neat

opal hamlet
#

Cogs ✨

autumn gust
#

hi D!

opal hamlet
#

Sup

autumn gust
opal hamlet
#

Thats great

lapis dock
# stoic patio

Also as a side note you should learn how to use venvs. You have a bunch of different librarys that your discord bot does not need. Venvs help keep the dependencys from different projects seperate.

opal hamlet
#

I can send you some crappy example code for cogs later

autumn gust
#

interesting

autumn gust
opal hamlet
#

Aka some shit i'll strip of functionality

autumn gust
#

also lockdown still doesn't work after global

opal hamlet
#

Btw do you still hard code tokens? Probably yes?

autumn gust
#

yes

opal hamlet
#

Cring

autumn gust
#

do I just use a variable instead

opal hamlet
#

I'd recommend actual configs

autumn gust
#

or store it in another file and pull from that

opal hamlet
#

Externally

#

Yes

lapis dock
opal hamlet
#

Some use txt, some json, many env i just use my sqlite3 db and initially enter the token via terminal input

little cobalt
#

you can use a env file or a json file for something like a token

autumn gust
#

I need to read up on what env files are

#

but json? yeah that's fine

opal hamlet
#

Environment

autumn gust
#

yes I know that much

#

but that's where my knowledge ends

lapis dock
#

the problem with txt/json is you can accidentally upload to git.

opal hamlet
#

isn't it py import python-dotenv

autumn gust
opal hamlet
autumn gust
#

I use nothing, I live on the edge

little cobalt
opal hamlet
#

Backups are futile, prepare to lose all progress!

opal hamlet
autumn gust
#

that's just a warning

autumn gust
#

also did anyone else already say your avatar is lowkey terrifying

lapis dock
#

At one point they invalidated tokens whne on git, I know it was broken for a while

stoic patio
#

the latest fully released version is 2.4.1 right

opal hamlet
#

the latest non dev version yes afaik

#

But i think the current dev is stable

little cobalt
stoic patio
#

oh

lapis dock
#

Main difference is username change

opal hamlet
#

Would it require me to change a buncha syntax?

#

If yes, nah thanks ill rather wait until i full developed my shit and then cry about having to change it

stoic patio
#

so i tried with 2.4.1

#

and when i change my display name, the member_update event fires twice

lapis dock
#

its not another fork it is literally just the person who has permissions to upload to pypi is unavailable so someone created a separate name for it.

lapis dock
opal hamlet
#

Yea ik, but did syntax change

opal hamlet
#

Like did naming convention of stuff change

lapis dock
#

Nope, except things that would have actually been updated. Like username stuff

#

It should be a drop in replacement

opal hamlet
#

Hmhm

#

Don't really remember the changelog

red mist
stoic patio
#

and the other discordutils library cuz i need it

#

it still happens

#

where member_update fires twice

lapis dock
red mist
#

@little cobalt you know ab this?

lapis dock
stoic patio
#

i did print([before.global_name, after.global_name])

tidal estuary
#

I've been up for hours ._. how does one get the attached regular text channel if you have x = someStageChannel

lapis dock
# stoic patio

Im not sure why that would be it is possible it is a bug. I have to go for now though sorry 🙁

stoic patio
#

ok bye

#

we'll just wait ig

lapis dock
red mist
#

Also one more question, when tf will @commands.isowner be available when only importing discord
and not also from discord.ext import commands

tidal estuary
#

I just get AttributeError: 'StageChannel' object has no attribute 'send_message', or 'send' or whatever I try

tidal estuary
#

nothing under discord, py-cord version 2.4.1

autumn gust
#

for an active developer badge, does your bot have to be public?

lofty parcel
#

No

clear aurora
#

Is there any problem with slash commands in a DM? On my server it´s working for everyone, if they dm the bot, it will not be shown for everyone.

opal hamlet
#

Well some commands are guild only

clear aurora
#

No they worked before

opal hamlet
#

Hmm

clear aurora
#

i did not change anything

autumn gust
#

I had ran slash commands etc. yet it doesn't seem to pop up a prompt

#

like man

autumn gust
#

can you remove a reply from a slash command?

red mist
#

is there a guide about autocomplete, I literally don't understand it with options

#

like the @option decorator

red mist
autumn gust
#

lol

#

that's essentially what my questions look like

#

I like to double check from now on since my reading skills are non existant

#

anyhow, is there any way to make the bot respond without used /speak?

opal hamlet
#

Uhhh since send apparently doesn't work(is it just the newer version? Works for me.) Probably ctx.defer() and then there's probably a ctx.followup.send or stuff

rugged lodgeBOT
atomic fern
#

how to create select menu options without decorator? i want to pass variable in it

opal hamlet
#

Do you want the select options to be passed into it?

atomic fern
#

yes

opal hamlet
#

I've struggled with that too, i can send you example code

#

Basically just py super().__init__() selectfunctionname.select_option = var_with_options

#

Maybe it was option instead of select_options, but basically that inside the classes init def

atomic fern
#
class Test(discord.ui.View):
    def __init__(self, input):
        super().__init__()
        self.select_options = [SelectOption(label=input)]

like that or I'm misunderstood? wowcry

opal hamlet
#

Nah instead of the self use the function you decorated(?) As a select func

#

Gotta get to my pc to scramble for code lol

atomic fern
opal hamlet
#

I totally know what i am talking about yes

#

You know how code is you made at 3am

#

You just know that it works, not how

atomic fern
#

yep

#

i don't even know how super works

#

so, can you ping me if you are on pc

opal hamlet
#
class ConfigAboutme(discord.ui.View):  
    def __init__(self, user_id:int, locale:str):
        try:
            self.locale = locale
            localization = Localization(lang=locale).data
            self.user_id = user_id
            super().__init__(timeout=30)
                self.aoptions.extend(discord.SelectOption(label=info, value=info) for info in self.addops)
                self.addselect.options = self.aoptions
            else:
                self.addselect.disabled = True
            if len(self.remops) > 0:
                self.roptions.extend(discord.SelectOption(label=info, value=info) for info in self.remops)
                self.removeselect.options = self.roptions   
            else:
                self.removeselect.disabled = True
        except:
            logger.error(traceback.format_exc())
    
    @discord.ui.select(placeholder='Add a field to your Aboutme', options=[discord.SelectOption(label='Select an option', value='Placeholder')], row=0)
    async def addselect(self, select, interaction):
        try:
            select.disabled=False
            selval = select.values[0]```
#

@atomic fern ignore the undeclared vars and shit

#

the important part is py super.__init__() before py self.addselect.options = self.roptions

#

also use placeholders inside the decorator

atomic fern
#

ok thanks

opal hamlet
#

hope it works lol

red mist
#

Uhhh I had a massive struggle with autocomplete because I forgot to make my debug guilds enabled.
Im officially a dumbass

opal hamlet
#

lmao

frail basin
#

Any1 know why im getting this error:

discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In options.1: Required options must be placed before non-required options
In options.3: Required options must be placed before non-required options
In options.5: Required options must be placed before non-required options
#

with this code:

gw_channel = bot.get_channel(991672736957087786)
@bot.slash_command(name="giveaway", guild=guild, description="test")
@commands.has_role(551826763794087966)
async def giveaway(
    ctx: discord.ApplicationContext,
    channel: discord.Option(discord.TextChannel, "The channel where the giveaway should be hosted in.", default=gw_channel, required=True),
    winners: discord.Option(int, "The number of winners", default=1, required=True, min_value=1),
    title: discord.Option(str, "The title of the embed", default="Giveaway", required=True),
    prize: discord.Option(str, "What the prize should be.", max_lenght=256, required=True),
    days: discord.Option(int, "How long the giveaway should be.", required=False),
    hours: discord.Option(int, "How long the giveaway should be.", reqired=False),
    minutes: discord.Option(int, "How long the giveaway should be.", required=False),
    seconds: discord.Option(int, "How long the giveaway should be.", required=False)):
    
    await ctx.interaction.response.send_message("Thinking...", ephemeral=True)
    
    duration = days * 86400 + hours * 3600 + minutes * 60 + seconds
    if duration <= 0:
        await ctx.interaction.edit_original_response("Invalid duration, please enter a duration that is greater than 0!")
        return
    
    staff_embed = discord.Embed(title= f"Start the giveaway {title}?", timestamp= datetime.datetime.timestamp())
    staff_embed.add_field("Prize", prize, False)
    staff_embed.add_field("Duration", duration, True)
    staff_embed.add_field("# of winners", winners, True)
    staff_embed.add_field("Channel", channel, True)
    
    await ctx.interaction.edit_original_response(content="", embed=staff_embed)
#

for phone users

#

Also please ping me because i wont see it otherwise

shell radish
frail basin
shell radish
#
    channel: discord.Option(discord.TextChannel, "The channel where the giveaway should be hosted in.", default=gw_channel, required=True),
#

whatever this line is

frail basin
shell radish
#

the issue is default=gw_channel

#

if there is a default, it will not be required

frail basin
#

i guess ill just remove the default part then

little cobalt
#

@red mist @lapis dock wants the ratelimit 100 commands for slash?

#

I mean how many you can load

little cobalt
#

Es ging um das ratelimit für slash commands

red mist
#

if when reloading a cog

#

and it has more commands

#

wouldnt you hit the ratelimit quickly

#

because each command gets reloaded

little cobalt
#

so at the end you cannot really use reload

#

or you have to create for every bot a new dc account

red mist
#

lmao I actually built reload into smth cool

#

auto updating my bot

#

made a /update command which allows me to select either version or branch from github where to update to

#

now the cool thing is, it keeps track of active branches and versions that exist

#

within a minute, when releasing new code on the github repo, it changes the values in the autocomplete so that you can always select the latest

#

and it updates this by basically just reloading the cog, as that entire cog is just for that one command.

little cobalt
#

so reload and unload is working fine

red mist
#

well I sure hope so

#

@little cobalt do you know how to limit someone from using both options in a slash command, when having 2 but only 1 of the 2 should be used?

little cobalt
#

you cannot remove a option from a slash command sadly

red mist
#

yeah that was pretty much my question

#

disabling an option

fickle salmon
red mist
#

Yeah by just responding with "You can only choose one.". That was in first instance not what I was trying to achieve, I wanted to know if it was possible to entirely disable other options.

fickle salmon
#

unless you want two slash commands, it's not possible

jolly ledge
#

builtin_function_or_method What does this mean?

#

I'm trying to iterate over a text file and search for bad words inside a user's message

sudden agate
#

is there any way to move mocks (MagicMock) to garbage collection? currently having issues with mem leaks, found out it's because of the mocks

shell radish
#

what

atomic fern
#
discord.ext.commands.errors.CommandInvokeError: Command raised an
exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0.options.5: The specified option value is already used
In components.0.components.0.options.7: The specified option value is already used

what is this? can't send view

sudden agate
# shell radish what

right so basically we use mocks to manipulate my bot in certain ways, but the mocks never go to gc

shell radish
sudden agate
#

mk

atomic fern
#

nvm simple mistake

opal hamlet
#

Sounds like duplicate options in your list?

sonic sorrel
#

what could be the causes for this error? it's caused by a random person so its hard to understand why it happened or how to handle it, but maybe they deleted the bot message?

Ignoring exception in on_application_command_error
Traceback (most recent call last):
  File "/mnt/Main/no_sync/home/xor/Bot/LoadoutLotteryBot/venv/lib/python3.11/site-packages/discord/commands/core.py", line 124, in wrapped
    ret = await coro(arg)
          ^^^^^^^^^^^^^^^
  File "/mnt/Main/no_sync/home/xor/Bot/LoadoutLotteryBot/venv/lib/python3.11/site-packages/discord/commands/core.py", line 982, in _invoke
    await self.callback(ctx, **kwargs)
  File "/mnt/Main/no_sync/home/xor/Bot/LoadoutLotteryBot/main.py", line 516, in roll
    await ctx.edit(embed=embed_msg, view=None)
  File "/mnt/Main/no_sync/home/xor/Bot/LoadoutLotteryBot/venv/lib/python3.11/site-packages/discord/interactions.py", line 428, in edit_original_response
    data = await adapter.edit_original_interaction_response(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/mnt/Main/no_sync/home/xor/Bot/LoadoutLotteryBot/venv/lib/python3.11/site-packages/discord/webhook/async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message

line 516 in roll is the last line of my command which happens after 5 seconds of it actually finishing doing stuff.

shell radish
#

yeah that sounds plausible

sonic sorrel
#

i accidently ctrl C'd but there was some other errors too

#

like missing webhook

#

it just didnt seem like a one-off someone manually deleting the message

red mist
#

what was the default time for a button to expire?

little cobalt
#

Im not sure

red mist
red mist
#

ah

little cobalt
#

Im not sure if there is a limit for it and if there is one I dont know how long

red mist
#

ty

strong rain
red mist
#

wait this is a thing?

#

lmfao that makes it easy.

#

ig I should've re read the doc >~<

#

whoever made that, I thank you

little cobalt
strong rain
#

If it's in the library that is

lofty parcel
#

I don't think pycord supports that

strong rain
#

Would love to have App Premium implemented to the library hopefully in the future

fickle salmon
#

Put it in #suggestions 🙂

obsidian stratus
#

Does a guild ban object/entry have a timestamp attribute

shell radish
obsidian stratus
#

BanEntry

shell radish
#

no

obsidian stratus
#

I seem to have found the answer

shell radish
#

you can try finding it in the auditlog tho

#

¯_(ツ)_/¯

obsidian stratus
#

yup I’ll have to store that manually thanks

obsidian stratus
#

Anyway thanks!

shell radish
#

yw

strong rain
shell radish
strong rain
#

Not sure if I did it right, but I tried my best

rancid arrow
#

I have two discord.OptionChoice's with true and false for names for a slash command option but im getting

discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 27.options.0.options.3.options.2.choices.0.value: Could not interpret "1" as string.
In 27.options.0.options.3.options.2.choices.1.value: Could not interpret "0" as string.
#

the command is under a subgroup if that changes anything

#

and the option is

discord.Option(name = "no_dm", choices = [discord.OptionChoice("True", 1), discord.OptionChoice("False", 0)], default = False, required = False)
deft kestrel
rancid arrow
#

oh wow i forgot Option had an input type

#

congrats me

#

ty

#

but why is OptionChoice broken like that, docs says value can be an int

shell radish
#

iirc

hazy turret
#

Why is my message not displayed ephemerally?
I use ctx.defer() at the beginning because it can be that the function takes a little longer so that I don't get an interaction failed and then I want to send the confirmation message at the end with followup but it should be ephemeral?

await ctx.followup.send(embed=embed, ephemeral=True)```
hazy turret
little cobalt
#

Yes

hazy turret
rain flax
#

how to send a msg in voice channel chat?

lapis dock
#

Just treat the voice channel as a normal text channel
It has a send function too.

rain flax
#

Thanks

barren adder
#

Anyone aware of changes to the guild.members property?
I have a bot with member intents and some of the commands require the total list of members.
For months, len(guild.members) has produced an accurate result but now it seems to give a number somewhere between 1 and all members
I'm using get_guild() not fetch_guild() so it's not that. I do still get some or all members depending on the server

proud lynx
#

Anyways, I need help. When I view the server as anyone besides an admin, my slash commands are hidden, even though Integrations has it set to allow everyone, explicitly.

deft kestrel
#

Does the channel have application commands permission enabled?

proud lynx
#

They all do.

proud lynx
#

Still hidden. Verified with all the roles, all the channels, no dice, but immediately shows back up when I got back to my Admin role.

#

Any admin role will have them show, to be clear.

deft kestrel
#

hmm, and this is enabled right?

barren adder
#

I swear guild.members used to do that

proud lynx
barren adder
#

Gotcha

proud lynx
barren adder
#

Is it possibly a proximity bot permission? I don't know anything about that bot

proud lynx
#

Let me look back over it.

proud lynx
#

Proximity is the bot I'm developing, for context.

barren adder
#

Oh, gotcha

proud lynx
#

What on earth could possibly prevent non-admins from it? Certainly nothing in the code?

barren adder
#

Well, something in the code could do it

deft kestrel
#

Did you also try enabling that permissions specifically for the channel? Also how are you setting the permissions for the command in your code?

autumn gust
#

any way to make a slash command NOT respond to the user?

little cobalt
autumn gust
#

I'd like it to just say text, that's it

little cobalt
#

You could send a hidden message first and after that a normal text message

#

An you cannot remove the "name used x command"

autumn gust
#

while the reply is an ephemeral

little cobalt
#

That is not anymore an Interaction and ephermeral only works with Interactions

autumn gust
#

have an ephemeral "Done!", and then get the channel ID of where the command was used

#

and then send {text} to there

little cobalt
#

If you would do ctx.send it just send a normal message in the same channel

autumn gust
#

or ctx.reply ephemeral and ctx.send normal

little cobalt
#

ephermeral works with ctx.respond and not with ctx.reply/send

autumn gust
#

there's a difference?

#

oh

little cobalt
#

ctx.respond is for slash commands

#

the other are for prefix commands

#

But if you do a hidden ctx.respond and after that a ctx.send/reply that would work

autumn gust
#

this worked perfectly

autumn gust
little cobalt
#

Yes

edgy nest
proud lynx
#

I'm having a session with a bug tester in about 4 hours and they can confirm/deny.

edgy nest
#

just make an alt account

proud lynx
#

Booo.

shell wharf
#

hey guys. I've just started and.. I already have got problems.. 😄 hello world worked out well. But now I wanted to access it from an saved aditor writing by using this: cd c:/python/hello.py
But it says the directory name is invalid and I really dont get it

edgy nest
proud lynx
#

Yeah, you just go to C:/python/.

#

That's the directory you need and you can access hello.py from there.

#

If you use the os library, you can do print(os.getcwd()) to see what your current working directory is.

#

And then just work out the relative path.

shell wharf
#

well that was fast 😄 thank you very much! You will see me asking some more stupid / simple questions

red mist
opal hamlet
white stump
#

i want to participate in a hackathon, can you tell what all should i learn

hallow copper
#

haiiiii ppls

thorn sapphire
#

Given an instance of discord.sinks (say, a my_sink = discord.sinks.MP4Sink()) how do I save the contents of my_sink.audio_data.items() to disk?

Normally, I send the files to chat, like

audio_files = [discord.File(audio.file, f'{user_id}.{sink.encoding}')
                   for user_id, audio in my_sink.audio_data.items()]

But what about saving it to disk?

edgy nest
#

audio.file appears to be raw bytes

#

just write that to a file

jolly ledge
#

How can I count the amount of time a user has spent inside a voice channel efficiently ?

proper dew
#

Hey, quick question. Can one await discord.utils.get(guild.roles,...) command?

proper dew
#

and is there any other way to wait for the role to be successfully stored in a variable? This gives me errors from time to time when I want to change the role of a user afterwards, because the program then does not have the role yet.

lofty parcel
#

How would awaiting it solve your issue

proper dew
#

because then I can pass the variable into the remove_roles(role) command and it won't generate the error that role is of NoneType.

lofty parcel
limber terrace
proper dew
#

by id, yes

lofty parcel
#

That's not name

#

.rtfm guild.get_role

sly karmaBOT
proper dew
#

wait, sorry, my mistake, I searched by name

white sparrow
#

Hey, I recently came back to creating discord bots after a while and struggle with creating permission predicates for slash commands. For text commands I always created a decorator which returned a predicate wrapped by ext.commands.check(). This doesn't seem to work anymore (using the old decorator on a slash command). Can anyone help me out there? Thanks :)

shell radish
#

show code?

white sparrow
#
def is_owner():
    async def check(ctx: discord.ApplicationContext):
        if ctx.bot.is_owner(ctx.author):  # type: ignore
            return True
        else:
            raise NotOwner

    return commands.check(check)
little cobalt
#

and what is the error?

white sparrow
#

No error, just anyone can use the command

shell radish
little cobalt
#

is that for the bot owner only?

shell radish
#

how did you decorate the slash command

white sparrow
shell radish
#

I remember there being some stupid edge case where it has to be a specific order

white sparrow
# shell radish how did you decorate the slash command
@discord.slash_command(
        name="reload",
        description="Hot-reload all or selected cogs.",
    )
@discord.option(
    name="module",
    description="The module to be reloaded.",
    type=str,
    choices=BOT.cogs_to_load,
    required=False,
)
@is_owner()
    async def reload(self, ctx: discord.ApplicationContext, module: str):
        ...
#

last one

shell radish
#

I'm assuming the indentation is correct

white sparrow
#

yes

#

maybe the is_owner without parentheses? Nope

shell radish
#

maybe the predicate should be above the option(s)?

white sparrow
#

I will try

#

Still not

#

I does indeed work with commands.is_owner(), but this was more like an example

shell radish
dense dirge
tawny ether
#

is it possible to change bot's profile picture using code?

unkempt cipher
#

not per server but the global avatar yes, should be

tawny ether
#

so for custom server profile for bot i will need to take their token and use their bot?

#

i will need to look how can i do that then

opal hamlet
#

Depending on use case some stuff could probably be done using Webhooks, tho i never used them and can only say that much

tawny ether
#

so it can match with their server

opal hamlet
#

I see, yeah no idea sry

tawny ether
#

its fine, thanks for trying 🙂

little cobalt
#

at which line?

frail basin
#
guild.get_role(984842845208866916).members

outputs []
but the role has 10 members

#

any ideas?

stoic patio
#

are you sure you have member intent enabled?

frail basin
#

yes

#
@bot.slash_command(name="test", guild=guild, description="A test command!")
async def test(ctx: discord.ApplicationContext, role: discord.Role):
    await ctx.interaction.response.send_message(content="Thinking...", ephemeral=True)
    
    if ctx.interaction.user.id == 603880226631450624:
        role2 = guild.get_role(984842845208866916)
        print(role.members)
        print(role2.members)
        await ctx.interaction.edit_original_response(content="Success!")
    else: 
        await ctx.interaction.edit_original_response("Only @frail basin can use this command!")

role.members returns a long list of roles, but
role2.members returns []

role is the same as role2

stoic patio
#

can you pls show more code

#

oh

#

nvm

#

try using discord.Intents.all()

frail basin
stoic patio
#

then idk

#

also i have a question: why does on_member_join literally only fire once (the first time after the bot restarts), then it doesn't fire anymore

little cobalt
limber wagonBOT
#

Any function that starts with get_ in Py-cord is retrieving the related object from your bots cache. If the object is not in the bots cache the get_ method will return None. Because of this behavior you should check if the get_x method is None and if it is use the fetch_x method.

Why Is Using fetch_ Without Using get_ First Bad?
The fetch_ method makes a call to the discord API. This API call is unneeded if you already have the information. It will also make your command take longer because it will have to send and than wait for a response from the discord API. It will also contribute to the discord APIs global rate limit of 50 requests per second.

What Is Cache?
The cache is a temporary storage inside your bot. It holds many objects from members to messages. When you restart your bot the cache will be empty. When the cache is full it will delete older objects to make space for the new objects.

frail basin
#

thanks

stoic patio
frail basin
#

role.id outputs the correct ID btw, its just that role.members is empty

deft kestrel
#

Try

role2 = ctx.guild.get_role(int)
if role2:
   print("Role Found")
else:
  try:
    role2 = ctx.guild.fetch_role(int)
    print("Role Found")
  except:
    print("Role not found.")
deft kestrel
red mist
#

What were the limits as in command limits of a discord bot again?

How many commands can it have;
globally privately subcommands and root's of subcommands?

shell radish
# red mist What were the limits as in command limits of a discord bot again? How many comm...

You can have 100 commands, and each command can have up to 25 sub-command groups. Each sub-command group can have up to 25 sub-commands.

100 x 25 x 25 = 62.5k

Of course, "slash commands can have a maximum of 4000 characters for combined name, description, and value properties for each command and its subcommands and groups", so you're not likely to hit that 62.5k command limit

This can be doubled again with guild commands

red mist
#

Thank you very much

#

You should put that into a tag lol

shell radish
#

?tag create cmd-limits You can have 100 commands, and each command can have up to 25 sub-command groups. Each sub-command group can have up to 25 sub-commands.

100 x 25 x 25 = 62.5k

Of course, "slash commands can have a maximum of 4000 characters for combined name, description, and value properties for each command and its subcommands and groups", so you're not likely to hit that 62.5k command limit

This can be doubled again with guild commands

limber wagonBOT
#

dynoSuccess Tag cmd-limits created.

red mist
#

So that's a total of 125K individual commands.

#

Damn

autumn gust
#

OKAY! guys

#

I need to know if this is theoritically possible

opal hamlet
#

It's not

autumn gust
#

okay so like, I have another python script which takes my input right

#

and then, when the bot script detects that a new thing has passed through to it

#

it forces the bot to say a message in a specific channel I set it to

#

it could be possible

opal hamlet
#

Sounds like something you'd do with sockets or shit, maybe rpyc, or just create a task that checks an external storage like a db and compares it via f.e. the last timestamp where a input was provided

#

That's something i'd have to look into at one point again too

autumn gust
#

on a scale of 1/10

#

how complicated do you think it is

opal hamlet
#

Doable if you find the right stuff

autumn gust
#

ahhhhh

opal hamlet
#

Smth like this

#
#

Dunno for sure tho

shell radish
#

no need for the bot shenanigans

autumn gust
shell radish
#

any specific reason?

#

On an unrelated note, you can also run the "communication" part through Discord as well

opal hamlet
#

Two instances/using the same token?

shell radish
#

there's many ways to go about implementing it

opal hamlet
shell radish
opal hamlet
#

Hmmm is there a prefix only bot Version that completely ignores application commands etc.?

shell radish
#

you can ignore interactions compleletly by overriding on_interaction

opal hamlet
#

Fair

#

I guess that might actually be, depending on what he's trying to achieve a somewhat easier solution then

#

What would you recommend tho for communication between bots? Have a bot that triggers multiple bots to play sounds in a specific server, like a multichannel soundboard that was... using ram like crazy

shell radish
opal hamlet
#

Hmmm

shell radish
#

there's probably better solutions like websockets and such

opal hamlet
#

Yeah i used websockets... wasn't really optimal, maybe just my implementation because iirc just the classic sockets websocket was blocking the bot by listening

#

I managed to fix that, but in doing that it started accumulating about 200-300mb ram and then crashed(after 10 hours)

shell radish
opal hamlet
#

Hmm still seems like it could do the job

#

What did you use for the api tho

shell radish
#

fastapi

#

and uvicorn

opal hamlet
#

... i think my issue would be that i have 5 bots i need to send it to... 5 apis?

shell radish
#

I don't know your system ¯_(ツ)_/¯

opal hamlet
#

Basically German Starmarine needs to send some kind of command/trigger to each of my gs bots

shell radish
#

why not Discord message event stuff

opal hamlet
#

My system to do that was just a for loop that connected to each bots socket and sent a message like f.e. play_soundpath, or stopplayback

opal hamlet
red mist
#

@little cobalt You said 1 cog per command, how do you do it with cog description, generally, what do you put in those, do you even use them?

Because you can also fetch command descriptions and names so...

Other question, how do you do it with subcommands?

little cobalt
#

I said that I do 1 cog per command to have it clean ;3

#

I dont use cog descriptions

little cobalt
#

How I get them to the other cogs?

red mist
#

Yes

#

if you have a folder call it developer (for developer commands)

and you have multiple cogs in it, restart.py and stop.py

#

how do you make both of them in the same subcommand group

#

/developer stop

#

/developer restart

red mist
#

ahhhhhhhh right

little cobalt
#
from pycord.multicog import apply_multicog

client.load_extensions()

apply_multicog(client) # after you load the cogs
little cobalt
# red mist ahhhhhhhh right

you just have one file with the normal command group and at the other files you just add

from pycord.multicog import add_to_group

@add_to_group(name="Name")
@slash_command()
#

you dont really have to change anything at the cogs

#

only add the group

red mist
#

oh wow. thats easier than I thought

little cobalt
#

its really easy

little cobalt
#

If py-cord-dev is installed you have to uninstall py-cord because pycord-multicog installs py-cord

red mist
#

ah

#

well we'll see when it gets put into 2.5

#

soontm I hope

little cobalt
#

Or they said it like that

red mist
#

wait wait wait what

#

so this wont work in 2.5?

#

🤔

little cobalt
#

what?

#

Why should it not work?

red mist
#

multicogs

red mist
little cobalt
#

Its not like V3 x3

red mist
#

uh

#

oh

#

I think my last 2 braincells just gave up

little cobalt
#

xd

red mist
#

should probably sleep

little cobalt
#

Same

red mist
#

ah well

little cobalt
#

Because of my Surgery soon

red mist
#

oh

wicked dirge
#

How do I verify a Member? Like as in what this button does

red mist
wicked dirge
#

im asking in support for a reason

red mist
#

not in discord docs?

#

Well then, I just googled

little cobalt
#

Can you show more than this?

wicked dirge
#

Looks like this isnt supported by pycord, found it in nextcord docs

red mist
#

Basically;

The Verify Member button bypasses the filtering rules you set up on your Discord server for new members. With this option, the server moderators can verify members manually, and the user doesn’t have to follow the verification process.

shadow junco
#

how to create a voice channel in a category (id is 1094616998169825330)

lofty parcel
shell radish
lofty parcel
#

Squid you really like hyperlinks

shell radish
shadow junco
shell radish
shadow junco
# shell radish categories are channels
@bot.event
async def on_voice_state_update(member, before, after):
    if before.channel is None and after.channel.id == int('1094617038351241366'):
        category = bot.fetch_channel('1094616998169825330')
        channel = await category.create_voice_channel(name=member.name)
        await bot.move_to(channel=channel)
#

AttributeError: 'coroutine' object has no attribute 'create_voice_channel'

mild sorrel
#

when i try to import discord it says this:
TypeError: function() argument 'code' must be code, not str

arctic plover
shadow junco
#

ok

shadow junco
arctic plover
shadow junco
#

tks a lot

arctic plover
#

np

shadow junco
arctic plover
#

not str

#

in your code channel_id is string

#

didnt see

late marlin
#
async def rps(ctx: discord.ApplicationContext, opponent: discord.User):
    print(f"{ctx.message}") # this prints None. I want to keep ctx to edit the message on timout
opal hamlet
#

its an interaction not a message, innit?

#

i think you'd need smth like ctx.interaction.response.edit() or similar

#

try

await ctx.respond('message')
await ctx.interaction.response.edit_message('othermessage')```
late marlin
late marlin
arctic plover
opal hamlet
#

should be i think, not too proficient if imma be honest

late marlin
#

ok. this is weird. ctx.response.edit_message() is fine in the original call function, but if I pass ctx to another function, to save for later, then self.__ctx.response.edit_message() doesn't exist. I think I'm using the wrong type.

arctic plover
late marlin
#

when someone presses a button I have the interaction, so no problem, but on timeout I don't

#

I tried keeping the context of the original slash command

#

when I call locally it works, but the saved context doesn't do the job. I get very strange inconsistencies.

opal hamlet
#

How about you know, you try to get/fetch the message later?

#

And edit that

late marlin
# arctic plover Tell me in detail what you want to do

this is accepted:

async def rps(ctx: discord.ApplicationContext):
    await ctx.response.edit_message()```

this is rejected: because: *await allowed only with async*
```ctx = discord.ApplicationContext() # returned from function, not None
await ctx.response.edit_message()```

using editor: VS Code
could that be the problem?
both cases refer to the same type, don't they?
what's going on?
late marlin
# arctic plover in 2nd your ctx is None

yes, None at runtime. but the compiler won't ever recognise it as the right object. I've tried variations of this, where ctx is passed as an argument and was not None.

arctic plover
#

to keep it

late marlin
#

yes. that's the example.

#

I edited the example

arctic plover
late marlin
# arctic plover can you send whole your code?

problem solved.... (edit) ```
import discord
import os # default module
from dotenv import load_dotenv
import time

load_dotenv()
bot = discord.Bot()

ctx = discord.commands.context.ApplicationContext()

await ctx.response.edit_message(content="global")

^^^^^ compiler error

class RPSView(discord.ui.View):
def init(self, ctx: discord.commands.context.ApplicationContext):
super().init()
print(f"{ctx}") # returns <discord.commands.context.ApplicationContext object at ...> not None
self.__ctx = ctx

def test(self, user, choice):
    # await self.__ctx.response.edit_message(content="test")
    # ^^^ compiler error
    pass

@discord.ui.button(label="button", style=discord.ButtonStyle.primary)
async def button_callback(self, button, interaction: discord.Interaction):
    await interaction.response.edit_message(content="button")
    # works fine
    # self.test()
    # ^^^^^^^^^^^ what I want to write

@bot.slash_command()
async def rps(ctx: discord.ApplicationContext):
await ctx.respond("first", view=self.rpsview)
# ^^^ this works
time.sleep(3)
await ctx.response.edit_message(content="command")
# ^^^ this compiles but doesn't work

@bot.event
async def on_timeout():
# savedrpsview.test()
# ^^^^^^^^^^^ what I want to write
pass

bot.run(os.getenv('DISCORD_TOKEN'))

arctic plover
late marlin
#

I tried to create a function test that would handle editing the message since on_timeout event cannot.

late marlin
#
        await self.__ctx.interaction.edit_original_response(content="timeout",view=None)```
#

not sure why the other functions didn't like await, but this works

#

thanks for looking :D

opal hamlet
arctic plover
late marlin
arctic plover
#

i wanted to say too

opal hamlet
arctic plover
#

just time.sleep() breaks async function

opal hamlet
#

ah

arctic plover
#

literally turns it into a regular function

little cobalt
#

time.sleep() is blocking the entire bot

late marlin
#

nah. it had issues before i imported time. i just wanted to check several functions in one run. anyhow. it's solved now. although there's still a type mystery when passing ctx

opal hamlet
#

wdym type mistery

little cobalt
#

If you want to use something like time.sleep() you should use asyncio.sleep() instead

arctic plover
little cobalt
#

Yes

opal hamlet
#

well... is the second func async?

little cobalt
opal hamlet
#

its about the editing of an already sent message iirc

little cobalt
#

For that you could use ctx.edit()

#

Or do you mean the original response?

late marlin
valid panther
#

I'm checking the documentation of the timeout on the buttons, but it should be like that, right?

valid panther
#

I'm using that page

little cobalt
valid panther
#

ye ik

#

The problem I am reflecting is that the disable _all_items is not behaving normally. It is not performing its function

little cobalt
#

what do you mean with that?

valid panther
little cobalt
#

Do you also edit the message?

valid panther
#

fix

#

I have been reading the one that returns the disable_all_items() method and it returns nothing, it just makes the change so it does not do the action.

oblique osprey
#

Hi, I'm trying to figure out how to handle my bot being disconnected from a voice channel. Is there an event I can listen for or am I going to have to check the state every time?

opal hamlet
#

@oblique osprey

oblique osprey
#

ah ok so I'd have to listen to that and then check the member param to see if it matches my bot

opal hamlet
#

Probably, never used that event 😅

oblique osprey
#

I'm surprised there's not an event on VoiceClient I can hook into

opal hamlet
#

Might be 🤷 i just did a bit of ReadTheDocs while eating

oblique osprey
#

Nah there's not, I read the docs before I asked

#

Ig I'll try and rewrite my code to make state easier to track

elfin quarry
#

Are general python questions (code using py-cord) allowed?

little cobalt
elfin quarry
#

i'll make a help thread and tag you there if you dont mind

trim escarp
#

Hello everyone, it's my first time trying this library (before I only worked with Telegram bots)
I copied the example from https://docs.pycord.dev/en/stable/installing.html#basic-concepts (using my token, of course)
But the problem is that I don't see message content, it's empty string. Tried to google the issue, ticked the "Message content intent" checkbox in bot's settings, but message content is still empty string :(

opal hamlet
#

Yeah no that's probably an outdated example, if you used the one i think you did

trim escarp
#

Hmm, yeah, because the "quickstart" example (https://docs.pycord.dev/en/stable/quickstart.html) works fine and it explicitly includes message content.

opal hamlet
#

Try

import discord

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

@bot.event
async def on_message(ctx):
   await ctx.respond(...)

bot.run(token)```
#

Probably want smth more like that, i wrote that on mobile so don't expect much from that

trim escarp
#

Oh, and 3. What's the difference between Client and Bot in code?

opal hamlet
#

client was also kinda used for user accounts IIRC, bot self botting is now against TOS, both work as bots but bot is just the common thing now

#

and to 1, yes

trim escarp
#

Okay, so I should use Bot class, okay.

opal hamlet
#

ye

#

if you want i can send you some random, semi efficient code for a bot itself if you have server you use for debugging/testing

trim escarp
#

Is it possible to just send a message to some topic without receiving and event first?
For example, if I want to use some specific Discord server as my notifications dashboard

trim escarp
opal hamlet
#

ill dm you

little cobalt
#

that is a message event

opal hamlet
grizzled loom
#

Hey Guys, I am building shut-down behaviour atm.
I was wondering if its possible to do without "import asyncio" as in the example created so far, cause pycord may already has the needed equivalent of asyncio.run ?


import asyncio
import atexit

async def my_function():
  # code here

atexit.register(asyncio.run(my_function())
upper flint
#

Is there a method to change the status of a discord.VoiceChannel? Or is it still not implemented yet?

little cobalt
grizzled loom
trim escarp
#

What are the limits for sending files by bot?

little cobalt
trim escarp
trim escarp
frail basin
#

any ideas why this didnt fire?

@tasks.loop(time=datetime.time(hour=18, minute=30, tzinfo=pytz.timezone("CEST")), reconnect=True)
async def schedule():
    print("something")
shell radish
frail basin
#

how do i start it

#

nevermind that, where / when should i start it?

#

rn i just put schedule into on_ready()

#

will that work?

shell radish
#

sure

frail basin
#

worked, cheers

tepid coyote
#

for bridge commands can you make the slash commands grouped and the prefix commands normal. e.g /music play <x> and .play <x>

shell radish
#

make a slash command and a text-based command separately

shell radish
#

If you want to share a callback make another function thing

slender lantern
#

One of my slash commands has a file option (for users to upload a file). This always gave me the URL pointing to the file once uploaded to Discord. Now, however, it's giving me a string of numbers, such as 1158187008557060226. Did something change?

shell radish
slender lantern
#

I wondered about that, but it just says new parameters. Thanks for looking into it

shell radish
#

mind creating a github issue?

slender lantern
#

Not home right now but can later. So it’s a library issue?

fickle salmon
slender lantern
#

Yeah

fickle salmon
#

No code changes?

slender lantern
#

Nope

#

Was hoping it was just a Discord bug

fickle salmon
#

interesting

slender lantern
#

Worth noting I’m on 2.4.x; 2.5 looks to have some breaking changes for me, and I didn’t want to deal with the hassle of the current semi-workaround to install it

#

But I don’t see anything in the changelog indicating there’s a fix for this issue

fickle salmon
#

I don't think 2.5 would touch this code path

#

The latest update for 2.5 is before this change I believe

shell radish
#

I still can't reproduce it

slender lantern
#

Okay, I managed to log in to my logging system on my phone, and it looks like it is in fact due to the ephemeral stuff

#

Guess my code isn't robust enough to account for it 😅

shell radish
#

must be something you're doing because the library is working as intended

slender lantern
#

Yeah, I'm just doing an "endswith" instead of using urlparse. Easy fix

#

Anyway, thanks for the help!

red pagoda
#

Is it possible to create description for each option in choices? PepeHmm

mild sorrel
#

how to make image appear at the top of an embed above the description?

deft kestrel
#

You mean the author icon?

mild sorrel
#

no, like an image that you set with URL

deft kestrel
#

You can set the author icon with a URL.

#

Do you have an example?

deep blaze
#

Traceback (most recent call last):
File "/usr/local/lib/python3.10/site-packages/discord/ui/view.py", line 421, in _scheduled_task
await item.callback(interaction)
File "/root/merl/src/modules/plugins/settings.py", line 719, in callback
await interaction.edit_original_response(view=self)
File "/usr/local/lib/python3.10/site-packages/discord/interactions.py", line 464, in edit_original_response
data = await adapter.edit_original_interactionresponse(
File "/usr/local/lib/python3.10/site-packages/discord/webhook/async.py", line 220, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook

line 719: await interaction.edit_original_response(view=self)

and i am not using a webhook i am using select menus

deft kestrel
hazy turret
#

I have an embed where I dynamically add buttons via the view. So every user who clicks on the button should have his own instance and the callback of the button should be only for the user so that there is no overlap with other users or do I see it wrong?

view = ShopView(categories)
await ctx.send(embed=embed, view=view)

class ShopView(discord.ui.View):
    def __init__(self, categories):
        super().__init__(timeout=None)
        for category, emoji in categories.items():
            self.add_item(Button(label=category, emoji=emoji, custom_id=category))

class Button(discord.ui.Button):
    def __init__(self, label, emoji, custom_id):
        super().__init__(
            label=label,
            style=discord.ButtonStyle.secondary,
            emoji=emoji,
            custom_id=custom_id,
        )

    async def callback(self, interaction: discord.Interaction):```
lapis dock
hazy turret
# lapis dock Yes, everytime you do `view = ShopView(categories)` it will create a **new** vie...

I have found my problem. The view with the buttons is created once, so each callback from the buttons is in the same instance. I then created another button in this instance and assigned it a fixed custom_id. So if 2 users wanted to press the button at the same time, it didn't work for the first user. I have now the custom_id of the second button also dynamically generated that this is not the same, so each user can also use only his button and everything works fine 🙂

late marlin
#

QQ: discord.ui.Modal has callback() for submit. what if the user cancels? where can I catch that event?

little cobalt
#

You cannot catch that

opal hamlet
#

Just timeout IG?

late marlin
#

pity. thanks anyhow

stoic patio
#

why does [activity for activity in member.activities if isinstance(activity, discord.CustomActivity)] sometimes include a member's custom status but other times it doesn't

upper flint
#

Is there a method to change the status of a discord.VoiceChannel? Or is it still not implemented yet?

lapis dock
lapis dock
#

You would need to use fetch_user(id) to fetch

#

.rtfm fetch_user

lapis dock
#

It is a method of your bot

stoic patio
#

does that contribute to rate limit

lapis dock
#

This is not the best solution as it requires an API call but I think discord does not give activity unless you specifically fetch the member

stoic patio
#

because i want something that's able to work every time someone joins a server

lapis dock
stoic patio
#

wdym by "have a status"

#

.activities sometimes includes customactivities, other times it doesn't

#

even though teh user's status is unchanged

#

(i meant always had a status)

lapis dock
stoic patio
#

but that is wrong, and we don't know if the member joining ACTUALLY has no status if that returns nothing

lapis dock
#

Yes but if they still don't after fetching you know they do not have one.

stoic patio
#

also i think most people who join a server don't necessarily have one

#

i wanna minimize my api calls

opal hamlet
#

Limits are meant to be broken /j

lapis dock
#

I understand, I just am unsure if there is a better way. Can you test and if that does not work it is know there is a bug

stoic patio
#

why doesn't [activity for activity in member.activities if isinstance(activity, discord.CustomActivity)] always contain custom activities tho

lofty parcel
#

Probably cache.

stoic patio
#

but then, when a member joins a guild, why does it sometimes contain that info but other times not

#

that's kinda inconsistent

#

and it SEVERELY messes with ppl

#

cuz what if you wanted to make something that kicked ppl with offensive custom statuses

#

but it doesn't always work cuz of platform limitations

burnt gate
#

there's any way to get ppl activities time?

lofty parcel
stoic patio
#

it doesn't always work for new members

#

i just realized lol, there's often a slight delay in joining --> actually being cached

autumn gust
#

just for the funnies

#

and so it's easier than typing /send text:abcdef each time

#

also, is there a way to check if a message has an embed, and if it does, include a link, if it doesn't, do something else?

mild sorrel
stoic patio
#

under what circumstances is Member.joined_at equal to None

opal hamlet
#

When they left the server already i guess

#

Or similar maybe?

lofty parcel
#

You won't have a member object outside a guild

lapis dock
#

Discord docs do not mark it as optional so either it is never None or it is a cache thing.

lofty parcel
#

Prob cache tbh

stoic patio
#

is the custom status not always being received on member join also a cache issue

little cobalt
#

client.sync_commands

lofty parcel
#

Why are you passing self?

#

And assuming you're inside the bot class

#

self is your bot

#

No?

#

sync_commands is a bot method

#

bot is self

#

This is why you to learn sparkles OOP sparkles

shell radish
stoic patio
#

oh

#

i see

#

also why does on_presence_update look like it runs twice evn though my i only have 1 mutual server with the bot

stoic patio
#

it's like sometimes we get it, other times we don't

fickle salmon
stoic patio
#

wdym

sour musk
#

I just realized one main thing, everything original is not a great solution to problems

#

I wanted to switch to a clean version of the discord library due to minor hosting conflicts, but in the end I thought about stupidly uploading local files there

autumn gust
#

I wonder

#

can I make a bot send a message whenever variable changes?

crisp pollen
#

is it possible to send an ephemeral response to a deferred reply
im putting ephemeral=True at the end of all my ctx.respond() yet none are ephemeral

red mist
#

You need to make the defer an ephemeral @crisp pollen

#

Basically when deferring, pass in ephemeral=True

#

that should do it.

lofty parcel
fickle salmon
stoic patio
#

i've tried that

#

does not work

limber terrace
#

quick question:
what da haaaaaaaail?

eager lintel
#

anyone know why im getting this error? i have tried everything:

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: string indices must be integers

rancid arrow
eager lintel
#

i dont believe anything is smth else

rancid arrow
#

you could also double check whether the index you're trying to take is something valid instead of like
my_list["seven"]

lofty parcel
rancid arrow
#

or they could be erronously trying to take the index of a string but they were expecting a dictionary

#

either way, check the variables you're trying to take the index of and make sure they're the datatype you're expecting them to be

eager lintel
#

i've looked and i cant find anything

#

wait no i found smth

#

but then at the same time i get throttled bc its getting 609 strings

#

{'errorCode': 'errors.com.epicgames.common.throttled', 'errorMessage': 'Operation access is limited by throttling policy, please try again in 47 second(s).', 'messageVars': ['47'], 'numericErrorCode': 1041, 'originatingService': 'com.epicgames.account.public', 'intent': 'prod'} 😭

lofty parcel
#

Huh

lofty parcel
#

And code

eager lintel
#

yeah

#
  File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
    ret = await coro(arg)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/commands/core.py", line 978, in _invoke
    await self.callback(self.cog, ctx, **kwargs)
  File "/home/ubuntu/cogs/friendslist.py", line 170, in friendslist
    display = e['displayName']
TypeError: string indices must be integers

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

Traceback (most recent call last):
  File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/commands/core.py", line 375, in invoke
    await injected(ctx)
  File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: string indices must be integers```
#

btw MzQ0NmNkNzI2OTRjNGE0NDg1ZDgxYjc3YWRiYjIxNDE6OTIwOWQ0YTVlMjVhNDU3ZmI5YjA3NDg5ZDMxM2I0MWE= is not my token, its a client id and cliend secret encoded in base64

#

had an issue with that in another server months ago

lofty parcel
#

?tag paste

limber wagonBOT
#

Please copy and paste your code here. This makes it easier for everyone helping you.

lofty parcel
#

Can you paste your code there

#

And also try printing type(e)

eager lintel
#

just did

#

yeah

lofty parcel
#

I'm asking if you could paste it in a pastebin

eager lintel
#

now what tho after i pasted

lofty parcel
#

Share it

eager lintel
lofty parcel
#

Thanks.

#

Gimme a sec to review

eager lintel
#

alr, ty

#

i appreciate it

lofty parcel
eager lintel
#

ye, but only after some time

lofty parcel
#

You're technically iterating over a dict

eager lintel
#

oh

lofty parcel
#

When you iterate over a dict you receive the values

#

That's why "string indices must be integers"

#

Cause e is indeed a string

eager lintel
#

ah

lofty parcel
#

Out of the whole issue,

#

I noticed you use pymongo

#

pymongo is sync. You can use motor which is pymongo but async

#

And you should init your db once, not in every cog you have. Having it as a bot var is probably the best

eager lintel
#

pymongo is on all my cogs, and i dont really have the time anymore to change all of it lol

lofty parcel
#

It doesn't change at all

#

You just await the methods

eager lintel
#

ah

lofty parcel
#

Shouldn't take more than 15 mins to switch correctly.

#

Better late than never.

eager lintel
#

ig lol

shell radish
shell radish
#

If you were to, then subclass bot at that point

brittle jasper
#

how do i make the bot send messages in forum posts?

heavy sky
lofty parcel
rugged lodgeBOT
#

Here's the background task example.

stoic patio
#

does pycord 2.4.1 support global names