#Basic Pycord Help
1 messages · Page 11 of 1
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
how did you even initialize the bot at the beginning of your code
hmhm
all of those are outside the class
@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
huh
gotta use @bot.event
Bots: Attributes activity, allowed_mentions, application_flags, application_id, auto_sync_commands, cached_messages, cogs, debug_guilds, description, emojis, extensions, get_command, guilds, intent...
neat
god i wish i could remember what part of my bot i was working on exactly
ADHD in a nutshell
"oh I should do this prob"
3 minutes in
"yo wat's that"
...
"what was I doing again?"
i know what it is and what it does, how it does it, but i forgot what else was needed lol
ever heard of... checklists?
do i look like i organize my shit?
sadly, my adhd wins over my autism in the organisation department
my urge to be as organized as can be is non existant
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
hmmm
ur shit workin?
trying to figure out the complicated tidbits
but somewhat
now to figure out how to check if user has default permissions or not
What?
I mean uhhh
if the user has the permissions required to run the command, and respond differently if they don't
AAAAAAAAAAAAAAAAAA
oh, good
why does switching from class to @bot.event have to be so difficult😭
for reference
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
AWESOME
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?
Don't care, one more notification doesn't hurt if i have my phone on mute lol
Yeah
sick, thanks bro
neat
so for a simple command system,
if input == "test1":
elif input == "test2":
else:
will work
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!')
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?
you can?
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?
Close
ctx.send('msg',ephemeral=True, delete_after=seconds) if you want it to auto delete after x seconds
`text` or
```py
```
you know you could make that thing 2 lines shorter right
sigh
of course
like this
I assume
await ctx.send(f'pinging... {bot.latency*1000}ms')```
o
some shit can just be ridiculously short
ctx.respond for slash commands
cant you still ctx.send
yes but not with ephemeral=True and you get every time a error
@client.slash_command()
async def test(ctx: discord.ApplicationContext):
await ctx.defer()
await ctx.send("test", ephemeral=True)
what does ctx.defer() do
prevents it from erroring that app isnt responding
ah
So, with slash commands you have to respond after 3 seconds
if you dont do it you get an error
bascially just tells discord, yup i saw that interaction
with ctx.defer you have more time
uhhh
show code
did you use ctx.send or ctx.respond?
use ctx.respond for slash commands
oh.
what the heck is command
bruh
it works
anger
why would you nag pillow to round numbers
friend
they're a python and xml nerd
oh I thought you meant https://pypi.org/project/pillow
@ember crane you never told me you were a library smh

that's so cute
lmao
yeah meet Pillow, he was carrying my ahh here until he redirected me here with stupid questions
fr
what's the on bot join guild event called
or is it discord.on_guild_join
and I'm just shit at reading
Yes
Literally need help to structurize my cogs.
Im unsure wether to make a cog with multiple commands or 1 cog per command.
Recommendations?
I do one command for every cog to have a clean structure
and with pycord-multicog I can use the slash groups at other files
idfk ab multicogs
i use one with multiple
otherwise i would have 80 extensions
& fuck that
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
Now I can't figure out how to get the TextChannel that gets stapled to every stage so I can send messages ._.
Well maybe you can actually send messages to the stages channel id?
Just get or fetch it
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.
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.
?
sync commands is working
Overall I dont think loading/unloading slash commands is good even if it technically works.
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
And what is your version?
i installed with -U option, and it shows "0.1.1" when i do pip list
Can you show your full pip list please
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.
hm, so a bot doesn't have to be just one file
neat
Cogs ✨
hi D!
Sup
my bot's alive and not heavily crippled
Thats great
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.
I can send you some crappy example code for cogs later
interesting
sure, just to understand what they are
Aka some shit i'll strip of functionality
also lockdown still doesn't work after global
Btw do you still hard code tokens? Probably yes?
yes
Cring
do I just use a variable instead
I'd recommend actual configs
or store it in another file and pull from that
Use env varibles
Some use txt, some json, many env i just use my sqlite3 db and initially enter the token via terminal input
you can use a env file or a json file for something like a token
Environment
the problem with txt/json is you can accidentally upload to git.
isn't it py import python-dotenv
yall use git?🤓
Lol who doesn't want someone to get their bot banned?
I use nothing, I live on the edge
you get a message from discord if you upload the token
Backups are futile, prepare to lose all progress!
Wait does discord search git for tokens inside files???
you mean in chat
that's just a warning
oh thx
also did anyone else already say your avatar is lowkey terrifying
At one point they invalidated tokens whne on git, I know it was broken for a while
the latest fully released version is 2.4.1 right
no, check out #library-updates
oh
Yes, technically there is 2.5 but due to some issues in uper management we have been unable to put this on Pypi. There is a substitute in #library-updates as a temporary solution.
Main difference is username change
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
so i tried with 2.4.1
and when i change my display name, the member_update event fires twice
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.
if you are working with usernames you will need to use the "dev" version. Hopefully uninstalling the other librarys fixxed the other errors
Yea ik, but did syntax change
oh ok
ic
Like did naming convention of stuff change
Nope, except things that would have actually been updated. Like username stuff
It should be a drop in replacement
I thought it worked in the dev version
i uninstalled every discord library besides the dev pycord
and the other discordutils library cuz i need it
it still happens
where member_update fires twice
It might, not sure. Would you hit ratelimits fast if you had ~20 commands in a cog and reloaded it 10 times?
That is a good question
@little cobalt you know ab this?
are the before and after the same both times?
Try printing before.whatever username you are changing and the same for after
i did print([before.global_name, after.global_name])
yes they are
I've been up for hours ._. how does one get the attached regular text channel if you have x = someStageChannel
Im not sure why that would be it is possible it is a bug. I have to go for now though sorry 🙁
The stage channel is the text channel, there is not another channel "attached". You can just do
StageChannel.send and other similar functions
Also one more question, when tf will @commands.isowner be available when only importing discord
and not also from discord.ext import commands
I just get AttributeError: 'StageChannel' object has no attribute 'send_message', or 'send' or whatever I try
Can you show your pip list?
nothing under discord, py-cord version 2.4.1
for an active developer badge, does your bot have to be public?
No
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.
Well some commands are guild only
No they worked before
Hmm
i did not change anything
odd
I had ran slash commands etc. yet it doesn't seem to pop up a prompt
like man
can you remove a reply from a slash command?
is there a guide about autocomplete, I literally don't understand it with options
like the @option decorator

I'm asking for the guide, not the docs.
docs is not guide
https://guide.pycord.dev/interactions/application-commands/slash-commands#autocomplete wait nvm found it
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
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?
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
how to create select menu options without decorator? i want to pass variable in it
Do you want the select options to be passed into it?
yes
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
class Test(discord.ui.View):
def __init__(self, input):
super().__init__()
self.select_options = [SelectOption(label=input)]
like that or I'm misunderstood? 
Nah instead of the self use the function you decorated(?) As a select func
Gotta get to my pc to scramble for code lol

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
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
ok thanks
hope it works lol
Uhhh I had a massive struggle with autocomplete because I forgot to make my debug guilds enabled.
Im officially a dumbass
lmao
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
channel is not required if there is a default
you mean the discord.TextChannel part?
channel: discord.Option(discord.TextChannel, "The channel where the giveaway should be hosted in.", default=gw_channel, required=True),
whatever this line is
how would i get the user's input then?
i guess ill just remove the default part then
@red mist @lapis dock wants the ratelimit 100 commands for slash?
I mean how many you can load
I forgot what the hell I asked
Es ging um das ratelimit für slash commands
oh right this
if when reloading a cog
and it has more commands
wouldnt you hit the ratelimit quickly
because each command gets reloaded
so at the end you cannot really use reload
or you have to create for every bot a new dc account
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.
so reload and unload is working fine
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?
required=False?
you cannot remove a option from a slash command sadly
You have to do it with logic in the function
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.
unless you want two slash commands, it's not possible
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
K thanks
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
what
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
right so basically we use mocks to manipulate my bot in certain ways, but the mocks never go to gc
send code for view
you haven’t provided any detail regarding implementation so it’s hard to say
mk
nvm simple mistake
Sounds like duplicate options in your list?
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.
yeah that sounds plausible
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
what was the default time for a button to expire?
3 or 5 minutes
Im not sure
I know I'ts possible to customly set these but, what's the limit to the custom time?
its 3 minutes without
ah
Im not sure if there is a limit for it and if there is one I dont know how long
ty
Default values to classes have been stated in the class's documented description, if in case you needed default values of other classes
https://docs.pycord.dev/en/stable/api/ui_kit.html#discord.ui.View
The library has helpers to help create component-based UIs. Shortcut decorators: Objects: Attributes children, disable_on_timeout, message, timeout. Methods cls View.from_message, def add_item, def...
wait this is a thing?
lmfao that makes it easy.
ig I should've re read the doc >~<
Wew
whoever made that, I thank you
yes
Can anyone tell me how can I implement Discord's US public release of App Subscriptions, from this article link?
https://discord.com/developers/docs/monetization/app-subscriptions
If it's in the library that is
I don't think pycord supports that
Would love to have App Premium implemented to the library hopefully in the future
Put it in #suggestions 🙂
Does a guild ban object/entry have a timestamp attribute
which object are you referring to here?
BanEntry
no
I seem to have found the answer
yup I’ll have to store that manually thanks
hassle tbh, I’ll try to manage storing only bans using the bot I’m coding
Anyway thanks!
yw
I did use </suggest:1094425102747185285> instead, since the bot for #suggestions does not work
use github issues
#suggestions is strictly for this server, not the library btw
Thanks!
Not sure if I did it right, but I tried my best
GitHub then
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)
You can just do no_dm: Option(bool, required=True)
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
value has to be the same type as the option type
iirc
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)```
You have to add it to both
So then like this?
await ctx.defer(ephemeral=True)
await ctx.followup.send(embed=embed, ephemeral=True)
Yes
Okay thanks!
how to send a msg in voice channel chat?
Just treat the voice channel as a normal text channel
It has a send function too.
Thanks
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
That's the expected results, use guild.member_count instead for an accurate count every time. You need the intent tho.
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.
Does the channel have application commands permission enabled?
Strangely, even when I create overrides per-command setting them to enabled, even that won't impact it.
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.
hmm, and this is enabled right?
Fair enough. What if I need more member info? Is there no simple way to get the entire member list?
I swear guild.members used to do that
That would be awaiting guild.fetch_members. Better yet, use discord.utils.get_or_fetch().
Gotcha
Is it possibly a proximity bot permission? I don't know anything about that bot
Let me look back over it.
No, should be fine.
Proximity is the bot I'm developing, for context.
Oh, gotcha
What on earth could possibly prevent non-admins from it? Certainly nothing in the code?
Well, something in the code could do it
Did you also try enabling that permissions specifically for the channel? Also how are you setting the permissions for the command in your code?
any way to make a slash command NOT respond to the user?
What do you mean by that?
like, /send text makes the bot send text with a reply like "Kriislol used the /send command"
I'd like it to just say text, that's it
You could send a hidden message first and after that a normal text message
An you cannot remove the "name used x command"
WAIT, what if:
I get the channel ID, and send a message to it
while the reply is an ephemeral
That is not anymore an Interaction and ephermeral only works with Interactions
I mean like
have an ephemeral "Done!", and then get the channel ID of where the command was used
and then send {text} to there
If you would do ctx.send it just send a normal message in the same channel
wait, so don't use ctx.reply and use ctx.send?
or ctx.reply ephemeral and ctx.send normal
ephermeral works with ctx.respond and not with ctx.reply/send
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
this worked perfectly
hidden ctx.respond you mean just ephemeral right
Yes
I wouldn't 100% trust view as role
Yeah?
I'm having a session with a bug tester in about 4 hours and they can confirm/deny.
just make an alt account
Booo.
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
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.
well that was fast 😄 thank you very much! You will see me asking some more stupid / simple questions
lmfao make a bot which welcomes users to the server under that file name
Yeah, a thing i also like to do using pathlibs Path and sys is to always define directories using
Path(sys.path[0], 'subdir')```
i want to participate in a hackathon, can you tell what all should i learn
haiiiii ppls
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?
How can I count the amount of time a user has spent inside a voice channel efficiently ?
Hey, quick question. Can one await discord.utils.get(guild.roles,...) command?
get isn't a coroutine
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.
How would awaiting it solve your issue
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.
And you're using get because you're searching it by name?

by id, yes
wait, sorry, my mistake, I searched by name
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 :)
show code?
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)
and what is the error?
No error, just anyone can use the command
The following section outlines the API of Pycord’s prefixed command extension module. Bots: Bot: Attributes activity, allowed_mentions, application_flags, application_id, cached_messages, case_inse...
is that for the bot owner only?
how did you decorate the slash command
The is_owner was more like an example
I remember there being some stupid edge case where it has to be a specific order
@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
I'm assuming the indentation is correct
maybe the predicate should be above the option(s)?
I will try
Still not
I does indeed work with commands.is_owner(), but this was more like an example
try using the@commands.check() decor instead
Anybody know how to load opus with an m1 mac? I was trying this https://guide.pycord.dev/voice/receiving but I got an error that opus didn't load
Pycord tries to keep the recording of audio as simple and easy as possible, to keep making Discord
is it possible to change bot's profile picture using code?
not per server but the global avatar yes, should be
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
Depending on use case some stuff could probably be done using Webhooks, tho i never used them and can only say that much
i am making a discord bots for general use (i mean not custom bot for a person), so a user of my bot asked whether it is possible for them to change pfp and name
so it can match with their server
I see, yeah no idea sry
its fine, thanks for trying 🙂
at which line?
guild.get_role(984842845208866916).members
outputs []
but the role has 10 members
any ideas?
are you sure you have member intent enabled?
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
this might be easier to read
i am using that
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
?tag get_x
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.
thanks
this also applies to on_member_remove
i switched to fetch_roles but it still doesnt work
role.id outputs the correct ID btw, its just that role.members is empty
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
Hows that?
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?
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
it is, I just don't know the name
?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
Tag cmd-limits created.
Oh lol
So that's a total of 125K individual commands.
Damn

It's not
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
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
hhhhhh
on a scale of 1/10
how complicated do you think it is
Doable if you find the right stuff
ahhhhh
Smth like this
@autumn gust https://docs.python.org/3/library/asyncio-stream.html might be better
Dunno for sure tho
sounds like just using a Discord webhook
no need for the bot shenanigans
except: I want the bot to send the message
any specific reason?
On an unrelated note, you can also run the "communication" part through Discord as well
Two instances/using the same token?
there's many ways to go about implementing it
That'd be whack with interaction tho
depends on implementation
Hmmm is there a prefix only bot Version that completely ignores application commands etc.?
you can ignore interactions compleletly by overriding on_interaction
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
I used a poll-based API and it worked fine
Hmmm
there's probably better solutions like websockets and such
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)
Oh I kinda lied a bit, because it wasn't for discord bots
... i think my issue would be that i have 5 bots i need to send it to... 5 apis?
I don't know your system ¯_(ツ)_/¯
Basically German Starmarine needs to send some kind of command/trigger to each of my gs bots
why not Discord message event stuff
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
Hmhm i think i tried that but it may have been prefix commands and not on message events, could work ye
@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?
I said that I do 1 cog per command to have it clean ;3
I dont use cog descriptions
what do you mean with subcommands?
How I get them to the other cogs?
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
ahhhhhhhh right
from pycord.multicog import apply_multicog
client.load_extensions()
apply_multicog(client) # after you load the cogs
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
oh wow. thats easier than I thought
its really easy
and for sub group you just add the sub group name
If py-cord-dev is installed you have to uninstall py-cord because pycord-multicog installs py-cord
Its currently not planned to get added to 2.5
Or they said it like that
multicogs
idfk
Its not like V3 x3
xd
should probably sleep
Same
ah well
Because of my Surgery soon
oh
How do I verify a Member? Like as in what this button does
Even I dont know this, but I was too lazy to google it.
So uh I suggest to google it >~<
No relevant results, nothing in docs by "verify" or "pending"
im asking in support for a reason
Are you sure its from a bot?
Can you show more than this?
Looks like this isnt supported by pycord, found it in nextcord docs
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.
how to create a voice channel in a category (id is 1094616998169825330)
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...

If you don't have the actual channel object then fetch the channel
Squid you really like hyperlinks
🤥
but fetch channel don't return category
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'
when i try to import discord it says this:
TypeError: function() argument 'code' must be code, not str
you never awaited it
category = await bot.fetch_channel('1094616998169825330')
ok
why you can make the words in the codeblock have color
just this:
print('Code here')
tks a lot
np
I change my code to this and it works
if before.channel is None and after.channel.id == 1094617038351241366:
category = bot.get_channel(1094616998169825330)
channel = await category.create_voice_channel(name=member.name)
await member.move_to(channel=channel)```
because channel_id must be int
not str
in your code channel_id is string
didnt see
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
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')```
what`s your intents?
thanks - I did filter some out, didn't want Admin.
await ctx.interaction.edit_original_response() won't work. the damned editor won't let me prefix await. and edit_message just doesn't exist. ctx is discord.ApplicationContext - is that the right type?
does your bot have message_content intent?
should be i think, not too proficient if imma be honest
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.
Tell me in detail what you want to do
I want to edit the message after timeout.
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.
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?
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.
did you try use global?
to keep it
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'))
Describe step by step how it should work\
- user calls command
- game sends one message that it edits continuously - this works if done through the interaction
- game ends after timeout and edits message (no interaction to reference, unfortunately)
I tried to create a function test that would handle editing the message since on_timeout event cannot.
solved
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
time.sleep bad, use await asyncio.sleep()
fr
thanks. it was just for the example. ctx behaves strangely when passed as argument.
i wanted to say too
wasnt time.sleep simply blocking or smth? just remember THAT its bad
nah
just time.sleep() breaks async function
ah
literally turns it into a regular function
time.sleep() is blocking the entire bot
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
wdym type mistery
If you want to use something like time.sleep() you should use asyncio.sleep() instead
if u dont want to stop the whole script
Yes
well... is the second func async?
why do you use ctx.interaction.x instead of just ctx.respond?
its about the editing of an already sent message iirc
yes. anyhow, I did find a solution to the problem I had, but the type issue is still weird
I'm checking the documentation of the timeout on the buttons, but it should be like that, right?
here is anything for buttons
yes ik
I'm using that page
;3

ye ik
The problem I am reflecting is that the disable _all_items is not behaving normally. It is not performing its function
what do you mean with that?
the normal behaviour of disable_all_items(), is to disable the buttons by changing their values to disable = TRUE. In this case, it does not perform its function
Do you also edit the message?
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.
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?
@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
Probably, never used that event 😅
I'm surprised there's not an event on VoiceClient I can hook into
Might be 🤷 i just did a bit of
while eating
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
Are general python questions (code using py-cord) allowed?
What is the python question?
i'll make a help thread and tag you there if you dont mind
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 :(
This is the documentation for Pycord, a library for Python to aid in creating applications that utilise the Discord API. Prerequisites: Pycord works with Python 3.8 or higher. Support for earlier v...
Yeah no that's probably an outdated example, if you used the one i think you did
Hmm, yeah, because the "quickstart" example (https://docs.pycord.dev/en/stable/quickstart.html) works fine and it explicitly includes message content.
This page gives a brief introduction to the library. It assumes you have the library installed. If you don’t, check the Installing portion. A Minimal Bot: Let’s make a bot that responds to a specif...
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
Thanks! Could you also please answer a couple of my "newbie" questions?
- What is guild? I suppose it's a "Server" here, right? So guild id means "server id"?
- What are Intents? How they are different from events? (upd: I guess, https://guide.pycord.dev/popular-topics/intents)
Oh, and 3. What's the difference between Client and Bot in code?
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
Okay, so I should use Bot class, okay.
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
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
Yes, please! The more the better
ill dm you
why ctx?...
that is a message event
ok?
i crapped smth together on mobile in a couple of secs, brain empty
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())
Is there a method to change the status of a discord.VoiceChannel? Or is it still not implemented yet?
Do you gonna run it with a command?
no. the bot should run it when it gets shut down by itself.
What are the limits for sending files by bot?
At one message?
For example, I want to send txt file with logs.
Some official doc (https://discord.com/developers/docs/resources/channel#create-message) say: "The maximum request size when sending a message is 25 MiB"
Is it file size limit?
yes
Thank you
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")
last time i checked, only utc worked and did you start the task?
how do i start it
nevermind that, where / when should i start it?
rn i just put schedule into on_ready()
will that work?
sure
worked, cheers
for bridge commands can you make the slash commands grouped and the prefix commands normal. e.g /music play <x> and .play <x>
just make two different commands
make a slash command and a text-based command separately
If you want to share a callback make another function thing
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?
might be related to #discord-api-updates message. Will look into it
Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.
I wondered about that, but it just says new parameters. Thanks for looking into it
mind creating a github issue?
Not home right now but can later. So it’s a library issue?
It's giving you just a snowflake?
Yeah
No code changes?
interesting
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
I don't think 2.5 would touch this code path
The latest update for 2.5 is before this change I believe
I still can't reproduce it
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 😅
must be something you're doing because the library is working as intended
Yeah, I'm just doing an "endswith" instead of using urlparse. Easy fix
Anyway, thanks for the help!
Is it possible to create description for each option in choices? 
how to make image appear at the top of an embed above the description?
You mean the author icon?
no, like an image that you set with URL
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
Try interaction.message.edit
sent ephemerally I guess?
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):```
Yes, everytime you do view = ShopView(categories) it will create a new view object. When you create this view you also create X new button objects. So even if the button looks the same it is different. There will be no overlap.
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 🙂
QQ: discord.ui.Modal has callback() for submit. what if the user cancels? where can I catch that event?
You cannot catch that
Just timeout IG?
pity. thanks anyhow
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
Is there a method to change the status of a discord.VoiceChannel? Or is it still not implemented yet?
It might have something to do with the cache. Could you try fetching the user and see if that makes it work every time?
like member.guild.get_member?
discord.ext.commands.Bot.fetch_user
discord.ext.commands.Bot.get_or_fetch_user
discord.ext.commands.AutoShardedBot.fetch_user
discord.ext.commands.AutoShardedBot.get_or_fetch_user
discord.ext.bridge.Bot.fetch_user
discord.ext.bridge.Bot.get_or_fetch_user
discord.ext.bridge.AutoShardedBot.fetch_user
discord.ext.bridge.AutoShardedBot.get_or_fetch_user
discord.Client.fetch_user
discord.Client.get_or_fetch_user
discord.AutoShardedBot.fetch_user
discord.AutoShardedBot.get_or_fetch_user
discord.AutoShardedClient.fetch_user
discord.AutoShardedClient.get_or_fetch_user
discord.Bot.fetch_user
discord.Bot.get_or_fetch_user
It is a method of your bot
does that contribute to rate limit
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
because i want something that's able to work every time someone joins a server
It would, you could check if you have a status first. Then if you don't fetch.
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)
If this returns a custom status you don't need to fetch.
but that is wrong, and we don't know if the member joining ACTUALLY has no status if that returns nothing
Yes but if they still don't after fetching you know they do not have one.
also i think most people who join a server don't necessarily have one
i wanna minimize my api calls
Limits are meant to be broken /j
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
why doesn't [activity for activity in member.activities if isinstance(activity, discord.CustomActivity)] always contain custom activities tho
Probably cache.
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
there's any way to get ppl activities time?
I haven't had problems with it
how
it doesn't always work for new members
i just realized lol, there's often a slight delay in joining --> actually being cached
oh sorry I didn't get notif for this and totally forgot about it
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?
i mean like an actual image like attachment
under what circumstances is Member.joined_at equal to None
You won't have a member object outside a guild
Discord docs do not mark it as optional so either it is never None or it is a cache thing.
Prob cache tbh
is the custom status not always being received on member join also a cache issue
client.sync_commands
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
OOP 
no, it's a Discord issue since they don't provide that info on join.
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
is there a way to solve this issue
it's like sometimes we get it, other times we don't
Get the user afterwards to fill in the field
wdym
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
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
You need to make the defer an ephemeral @crisp pollen
Basically when deferring, pass in ephemeral=True
that should do it.
Create a task, check if it changed after the X time, send a message
Call get_user on guild
quick question:
what da haaaaaaaail?
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
check the datatypes of your variables, one of them is probably a string but you were expecting something else
i dont believe anything is smth else
you could also double check whether the index you're trying to take is something valid instead of like
my_list["seven"]
You're trying to index a string and you're not using integers
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
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'} 😭
Huh
Can you show the whole traceback
And code
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
?tag paste
Please copy and paste your code here. This makes it easier for everyone helping you.
You sent the file
I'm asking if you could paste it in a pastebin
i mean that to this, lol
now what tho after i pasted
Share it
Does result query returns this?
ye, but only after some time
You're technically iterating over a dict
oh
When you iterate over a dict you receive the values
That's why "string indices must be integers"
Cause e is indeed a string
ah
And this is basically you getting ratelimited
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
pymongo is on all my cogs, and i dont really have the time anymore to change all of it lol
ah
ig lol
actually, initiating them in every cog is fine. Monkeypatching is the bad practice here
🐒 what
If you were to, then subclass bot at that point
how do i make the bot send messages in forum posts?
a task?
Just like in a normal channel, but get/fetch the forum post instead of a channel
oh great tyvm
Yes. Heres an example
Here's the background task example.
does pycord 2.4.1 support global names
I hope