#Basic Pycord Help
1 messages · Page 38 of 1
idk if you'd really want to restart everytime but eh whatever, i mean ultimately it depends on your setup? how you detect the file changes, beyond that ending the process and having a command to start it again doesn't seem impossible
Right now I'm trying to use pymon for this
Just thought anyone had experience with this kind of problem
maybe inotify https://stackoverflow.com/a/33469308
py-mon looks pretty good too
if you are using github, you can do a loop that when the git is not up to date it updated it and restart ur bot
you can also just reload cog or use the function importlib.reload to reload a file that is not from a cog
Well, yes and no. In order for bot to refresh this way I'd need to push updates to github by creating a new commit to repository
This way, repo will flood with a lot of commits with 1-2 changed lines
It's ok though, I already did what I planned to
I ended up using watchdog for monitoring file changes. I binded my dev directory with src directory in docker and now it works like a charm. Every update is almost instant, no need to do anything at all
yes
but like
if every time you edit a file its restart
it will do a lot of restart no ?
Yes, indeed
Consider looking for a better option without ur bot restarting if you plan to have a bot public, (more user mean it will take way more time to reach the on_ready like 30min)
No, I don't use it for production. Of course my main container is always up and running w/o constant restarts
I have a separate bot instance in which I develop and test my code. It's on it's own isolated server so no one except me has access to it
So there are no problems with command propagation
perfect so
if that can help you
im using a command /update that make the bot up to date and restart it
Why does guild doesnt have any attribute guild attribute fetch_role while it has every other fetch ?
because you can't fetch a single role
should be possible imo
why ?
like discord doesnt allow it
yes
that kinda stupid
like if you have an id of the role
so you have to fetch all the role to then itinerate in it to find the corresponding id
just fetch all and filter
im using the method guild._fetch_role
but yeah if not i will have to use the fetch_all and filter
that's what _fetch_role does
what intput_type should i use for an message_id ?
should i use float and then convert to int or someone has a better way to deal with that
that doesnt work
string works thanks
How can i use paginator to put 2 embed in each page ?
for result in results:
id, embed_data = result
embed = discord.Embed.from_dict(eval(embed_data))
id_embed = discord.Embed(title=str(id))
embeds.append(embed, id_embed)
paginator = pages.Paginator(pages=embeds, timeout=None)
like something like that
Create a list of pages instead of just passing embeds
https://docs.pycord.dev/en/master/ext/pages/index.html#discord.ext.pages.Page.embeds
This module provides an easy pagination system with buttons, page groups, and custom view support. Example usage in a cog: API Reference: Page: Attributes content, custom_view, embeds, files. Metho...
why do u use eval
im just dumb, i should do embeds.append([embed, id_embed])
thanks dark
to convert it from str to dict
use the json lib
but its not safe
why ?
import json
embed = discord.Embed.from_dict(json.loads(embed_data))
same length, just 1 more import
arbitrary code execution
i dont really see a world where they can
youre living in it
tell me if im wrong
you are wrong
you're wrong
wait lmaoo
the embed_data is just the embed.to_dict, how can the eval of that can do something ?
its an embed.to_dict()
that its store in my database
like how can he used that to attack my bot
embed content :)
i will try
well
still give me the same
but yeah if i only eval 1+2 its does 3 thanks for make me learn that
code = eval(str({'fields': [], 'type': 'rich', 'title': '1+2'}))
print(code)
# outpout = {'fields': [], 'type': 'rich', 'title': '1+2'}
i dont think that eval can be used by an attacker since its a str(json) like that, but if someone knows an exploit where the eval can work feel free to ping me
overall eval is used to evaluate code
and with json.load i havean error:
import json
code = json.load(str({'fields': [], 'type': 'rich', 'title': '1+2'}))
print(code)
# AttributeError: 'str' object has no attribute 'read'
loads
not load
load accept file
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
make it double quotes
just change it in that one line lol what
that how discord return the embed.to_dict
thanks ;)
can you send me the text ?
i like to try thing
but even the user cant really do that
{'test': 'test'}; print("a");#'}
i will try it rn
or you could just change 2 lines of code and use a standard library for parsing json
eval is also just bad practice
if you're using eval you're doing something wrong
i tried with json
lemme check sth
however i got an error
i have an idea
because you're not dumping it properly
this one
how should i dump it ?
ok thanks
is that base64
yep
code = eval(str({'fields': [], 'type': 'rich', 'title': '{\'test\': \'test\'}; print("a");#\'}'}))
print(code)
# outpout {'fields': [], 'type': 'rich', 'title': '{\'test\': \'test\'}; print("a");#\'}'}
its the timestamp convert into base64
to then be able to load the embed
ok tell me if you find anything
I mean that eval in general is not safe and can work well, however, there will always be a person who comes up with something so you anyway should consider it unsafe
yes better safe than sorry
mostly someone with try with closing quotes like plun above
also u can use unicode in eval
What permissions are required to send messages in channels?
Checking using can_send returns True but send throws a Forbidden 50013 exception. This behaviour happens in production
The bot has that permission but it still throws Forbidden
I added a check before the call for this permission but it didn't work
and yes I made it check for the channel, not the server
Does it have the View Channels permission on the target channel? Frustratingly, that's a requirement in order for it to be able to send a message.
this is what it looks like rn
still throws an exception right under when I call send on the channel
there shouldn't be any line ending issues as I have git configured to convert to Unix
and the bot server runs Debian 12 which I updated 2 hours ago so there shouldn't be an issue
is it only for that channel or any channel
Only for that channel
might try out with different discord permission settings
check the permission overrides for that channel, maybe something is weird
and also try viewing the server as the bot role
also fyi you can use delete_after=5 in the send() to schedule deletion automatically
can we saw the channel_perms definition ?
how do I convert Member instance to User instance or is that the same thing essentially
even if normally that doesnt change anything the channel.can_send should check that also
member is also user
user is not member
there is member.user i think but you usually never need that because member has everything user has
what warning
i think thats just a typehint error, permissions for a user make no sense
just a dumb question but
I think the check for overrides may have patched the bug, I'll check in a while, meanwhile I'll implement proper logging
why are you using can_send() and check if it has the perm ?
like just use can_send()
because can_send() for some reason returns true and then it throws an error at literally the next line saying Missing Permissions
I don't think can_send() checks permission overwrites
i will check the code
it should
it does
if not getattr(channel.permissions_for(channel.guild.me), permission):
return False
but maybe
your bot just have any permission in the whole guild
and not only in the channel
(even if the can_send should handle that)
you could also print the exception text, maybe it has some info
Exception Hierarchy:- Exception,-- DiscordException,-- ClientException,- InvalidData, InvalidArgument, LoginFailure, ConnectionClosed, PrivilegedIntentsRequired, InteractionResponded.,., NoMoreItem...
When I rerun a slash command it sometime give me NOT found error
The first time I run the slash command it works. After I do the up arrow on keyboard to redo the same command. When I do that, I get error on bot. An embed is still sent, but it is a wrong one ...
Here I I run the command for the first time (no errors):
after I run it a few time, it start crashing and sending wrong embed:
show the code
for the show, all I am going is creating a paginator, and after
await paginator_server.respond(ctx.interaction, ephemeral=ephemeral)
Maybe it is new version, it never done that before. That code has been working for more than a year
@SHOW_GROUP.command(guild_ids=guildIds, name="member", description="Show all the individual, global and recurrent timed role of a member")
@option(
"role",
description="The member which roles will be show",
type=Member
)
@option(
"ephemeral",
description="If the bot respond as ephemeral",
type=bool,
default=True
)
async def show_timed_role_of_member(self, ctx: ApplicationContext, member: Member, ephemeral: bool):
await self._show_timed_role_of_member(ctx, member, ephemeral=ephemeral)
change the name "role" to "member"
sorry sent the wrong command.
@SHOW_GROUP.command(guild_ids=guildIds, name="me", description="Show all the individual, global and recurrent timed role of you")
@option(
"ephemeral",
description="If the bot respond as ephemeral",
type=bool,
default=True
)
async def show_timed_role_of_me(self, ctx: ApplicationContext, ephemeral: bool):
await self._show_timed_role_of_member(ctx, ctx.author, ephemeral=ephemeral)
yea idk tbh, something about the interaction already being used or something
Im too tired for this today
wait how is this code working 😄
I put the wrong name there, it is not suppose to work
but is does
diff command
this is the show member
that one
oh
But appart from that, I get the bad Request on all slash commands
if I redo them with up arrow
Even with slash command that have no code changes.
Any support for user-installable apps with Py-cord Stable yet?
Theres probably a pr
But wont be merged until discord takes it out of preview
Ahhhhhhhhh~
Not me here trying to make a user-installable app...
I've got the guild-install side of it all working, but I'm waiting on what is likely v2.6 to allow user apps 😭
I would wait for an update so its stable and tested
The current PR is stable unless discord changes anything
At the moment they're making up their mind on permissions
So if you wanna use it just install the branch as per the pr's instructions
Just found it, #2409 if you want to remember it for anyone else who asks.
Do we know if there's an ETA for when Discord releases user apps officially or when Pycord is supporting with user apps?
Nope, at minimum when discord takes it out of "preview"
They typically don't give specific timelines on this stuff though
Typical Discord. I'm convinced that their business model aims to piss off developers as much as possible-
but the profit is rising wdym
Eh ultimately this is a pretty significant feature with a lot of implications so they have to take their time on it
Seeing the progress on it it shouldn't be too long, and it's still functional as far as we're concerned so using the early PR isn't particularly dangerous at this stage
I'm not overly against using the PR, I'm just weiging my options:
- Get an early start on developing my app and hoping that Discord don't change it too much; or
- Wait for ages and pray Discord release it to stable soon, but possibly risk months of lost time.
At this stage there really isn't a lot they CAN change, but if there are any major changes it'll be clear in the pr
As always, it's "possible" but weighing out everything they've put out so far it's unlikely
I'm tempted to just say f*ck it and pray Discord don't screw it up too much
One pip command later...
I'd just say go for it, if there's any issues leave a comment on the pr or feel free to ask here
Also you can preview the docs for it if you go down to the actions and find readthedocs
I think I'm just going to blame Discord if there's any issues because Py-cord is too good to be making errors. Then again, I see Discord just using the "it's in preview" for any issues that come up so that says alot.
Managed to find the docs while looking for the PR, not sure how though...
@errant trout can you take a look at #1241170479834988706 , Im to tired and I want to go sleep now
xd
I was today years old when I learned you could grab a channel category with .get_channel() - I think that says a lot 🤣
Is it possible for a bot to send a voice message? (Not sending a .mp3 file)
no
Any thoughts on how I can send an audio recording so it shows on mobile as well?
:(
Idk send it as an mp4
i was about to say that lmfao
I had the test bot that I forgot to close in the docker, So 2 instance of the bot running at the same time 😄 🫠
Oof okay, that sucks but thanks
yeah pretty silly that the app can't play audio files
i dont really know how but this keeps on erroring ```py
await memeber.add_roles(discord.Role(1239192685022023771), reason="test", atomic=True)
it should just be discord.Object(1239192685022023771)
What's atomic arg?
can you show me your code, starting with how the command is made, up to this permission check part you just posted, please
from top to bottom:
main.py cog definition
on_message listener in leveling.py
getting channel perms and overrides
and then ✨Le code spaghetti✨
if I remove the channel_overrides check it starts throwing errors
but I think it won't send messages anywhere unless the permissions are overridden as the channel overrides are None
whats the error you're getting?
Please copy and paste your code here. This makes it easier for everyone helping you.
Including the error, it will be easier for us
do not bother with can_send and overwrites_for, just use permissions_for
can_send is meant to take the objects you're trying to send, but it should be noted that it doesn't actually check the view_channel permission
that's an oversight I'd say
if can_send returns true you should absolutely be able to send
Can I have 2 dropdown menu's on the same row of an interaction. I have 5 rows in the following setup
- 3 buttons
- disabled button with info text
- dropdown 1
- dropdown 2
- confirm button
and I would like to add a second dropdown on the same row as the 1st dropdown, is that possible at all or will I need to re-order stuff
Im pretty sure you can’t have 2 dropdown on the same row
You cant.
Dropdowns use a full row.
I believe its 5 items per row, dropdowns use 5.
Ah ok, makes sense
Can you sned multiple followup messages to interactions? Say I have an interaction which will take a while to process so I defer it and then want to send a followup once the response is partially complete, can I then send another followup when it;s finished?
U have 15 min to do follow up
okay, but can I do 2 followups?
.tias
why would you need 2 followups is the first question that comes to mind
To answer 2 times to an interaction ?
why?
Why not lmao It depend in his code, for example you answer 1 time to ask them to send a message, and answer again afer the bot.wait for
2 followups are just clutter, i do not see any use case for that
toothy please i beg of you, and i mean no offense, learn that people have use cases beyond what you personally use
multiple messages in a single command isn't strange by any stretch of the imagination
no but like, you can edit the message, or just use a send, or anything
and i mean i did ask them why, but luma decided i needed the answer from them
i dont know why
regular bots can use followups and send interchangibly, but in many instances when commands are limited to interactions bots won't be able to use ctx.send
editing is pretty neat, but there's also cases where you don't necessarily want to overwrite the original message
U literally ask me why …
yea but now i have 2 answers from 2 people who aren't the person that actually holds the info :>
i mean, i'm not speaking for them; i'm just speaking in general
yea ik but like lol
"why would you need 2 followups" just sounded a little silly to me
yea, because i rarely come across even a single followup in the many bots i use
The fact that everytime u don’t use something u say yeah but why the heck use that
Is disappointing
deferred responses are followups
i just asked them why, both to possibly educate myself and or to suggest a better way of handling it
I give up with u toothy
i'm not saying "oh you are so stupid for 2 followups"
U ask me why too
quit twisting the words i write
And then u say why luma answer me
to my very initial question
i want to know from THEM not you
the way that you asked it had that connotation
Doesn’t seem clear that ur not asking that to everyone but only to him
Well yeah you mean him when you never talk about him and when the 2 last message where not from him
I’m sorry to not read ur mind…
How can I create a prefix and a slash command at the same time? discord.py have method hybrid_command, is there an analog to this in pycord?
bridge commands
and you will need the master branch, current branch is broken for bridge
how do I add a bridge command without putting it in a cog?
decorating it normally doesn't work, and idk if im supposed to add_command or add_application_command lol
?
@bridge.bridge_command()
async def ping(ctx: bridge.Context):
"""Checks the latency between the bot and discord."""
t = f"WebSocket: `{round(ctx.bot.latency * 1000)}ms`"
await ctx.respond(t, ephemeral=True)
this doesn't get added to the bot since its in the runtime file and not a module
Hold on
I'm thick, @bot.bridge_command
idk why my intellisense didn't show me that existed when I tried it lol
how can i get discord.Member object from userid and vise-versa
discord just did!? Am I dreaming?
whats that VScode theme, it looks cool
Just for understanding, you can't get the member object directly in any way?
And do you know the guild you wanna get the member in?
Does bot.run fully close the event loop before returning? or can I still use the loop afterward
whats the problem
its fine, I fixed it :)
I was using the wrong decorator
nvm i figured it out thanks for the help
@bot.event
async def on_message(ctx):
open(f"{ctx.channel.id}_log.txt", 'a').write(ctx.author+": "+ctx.message+"\n")
on_message does not appear to be working unless the bot sends a message, user messages are not causing it to run
this is the error we get when interrupting
you dont have the message_content intent
# --- BOT ---
intents = discord.Intents.all()
intents.message_content = True
intents.members = True
client = discord.Client(intents=intents)
bot = Bot(command_prefix='&', intents = intents)
``` that's what i thought too so i checked and turns out we do
are you sure it isn't just erroring
on_message takes message, not ctx; as such, ctx.message is actually message.message and errors
you're using bot.event on a bridge or prefix bot for on_message
doesn't that make it not process anything
ima make a thread
unless it is, in which case yeah you need to process them
yea true just wanted to bring that up if it becomes an issue
whatever works
heres the whole code
ok wtf, it says it has permissions above but still throws missing permissions error?
Source: (Lines 128 to 139)
view the channel as the bot role and see if you can send a message
I don't have access to the server
I don't even know what server this is happening on
order_group = SlashCommandGroup(
name="order",
description="Manage Everything related to order",
checks=[
commands.has_permissions(administrator=True)
],
guild_ids=[974347594866237461]
)
why commands.has_permissions(administrator=True) dont work for slash command groups
do you want it to be hidden on discord?
yeah
you should use default_permissions
.rtfm default_permissions
alright
rather, default_member_permissions; this takes a Permissions object https://docs.pycord.dev/en/master/api/application_commands.html#discord.SlashCommandGroup.default_member_permissions
default_permissions is the decorator version
then i dont know, sorry
does reset_cooldown() will reset cooldown for all user or for current user ?
I'm using user
is there any way to reset for a particular user.
then reset_cooldown would reset it for that particular user in the current interaction id guess
or do you wanna reset it for someone else
for that particular user
Looking for a little advice, not specifically Pycord but this seems to be a good place to ask.
I'm making a bot that can be both installed to a User & to a Guild. When storing data from these commands, would it be best to have 2 DBs - one for users & one for guilds or 1 DB for both methods to share?
TIA
one DB, two tables
That's what I meant by 2 DBs - whoops 😭
Thanks though
(thats how i'd do it)
in the same table you can do for example guild_id = .... if its the guild and if its for global you can do guild_id = 0
i will do that
i mean ultimately it depends on what you wanna save
depend on your preference and code ig
That's not quite how this bot would work. When installed to a user, commands only work in a DM channel. When installed to a guild, you can only use the setup commands in a channel in that guild.
It makes sense to me at least.
In terms of what I'm storing, I'm essentially making a message tags bot, similar to Dyno/Carl ?tag commands. It's just going to be data for the tag name, tag content and who owns the tag (member or guild id).
Not too sure how exactly I'm going to do this yet but any suggestions would be appreciated.
I mean yea, you could make one boolean column "guild", and then an "ID" column that saves either the guild or the user ID
or you seperate it into two tables, might be a bit cleaner
i would seperate it personally
well you can do for your table :
guild_id
member
name
content
if its in guild you save also the guild_id, if not you put None for guild id.
so if user app select * where member = ... and guild select * where guild_id =
depend on ur preference
i personally prefer not having 2 tables that will do the same thing just for user app and normal app
I'm tempted to make 2 different tables, just not too sure exactly how I want to do it yet. Trying to figure out the logistics of what needs to be stored for each type of interaction (user/guild) and how to separate these methods, tempting to use 2d classes:
class db:
# blah blah
class user_install:
# put all the user_install methods here
class guild_install:
# put the guild_install methods here```
Also trying to figure out with a little testing if `iscord.IntegrationType` is data that's passed with an interaction or not, trying to use ```py
if discord.IntegrationType == 0: #guild
if discord.IntegrationType == 1: #user```
id just check if its a DM or not since you said its DM for user, and channel for guild install
.rtfm get_user
discord.ext.bridge.Bot.get_user
discord.ext.bridge.AutoShardedBot.get_user
discord.ext.commands.Bot.get_user
discord.ext.commands.AutoShardedBot.get_user
discord.Client.get_user
discord.sinks.Sink.get_user_audio
discord.sinks.MP3Sink.get_user_audio
discord.sinks.MP4Sink.get_user_audio
discord.sinks.M4ASink.get_user_audio
discord.sinks.MKVSink.get_user_audio
discord.sinks.MKASink.get_user_audio
discord.sinks.OGGSink.get_user_audio
discord.AutoShardedBot.get_user
discord.AutoShardedClient.get_user
discord.Bot.get_user
discord.Invite.target_user
discord.sinks.WaveSink.get_user_audio
is any better way to send DM to a user whos only userID is know to me? rather than get_user
I have this logic at the moment. Just not sure how I'm going to actually make the methods. I'm literally just brainstorming ideas at the moment, did you want to see my rough outline?
not really, you need to get the user somehow to send a dm
tbh i hate any kind of code that handles DB actions, and i'm not great in it
I know SQL fine but the "connection" part just kills me
so i wont be much help lol
Yeah I'm quite new to DBs. This is the kinda thing I'm going for - hopefully it makes a little more sense than my waffle:
yea, i mean the discord-side of things is simple enough really, you just need to make sure to address the proper DB functions (e.g. tag_save_user vs. tag_save_guild)
DB schema should also be simple enough for both tables
Just User / Guild ID | tag name | content i suppose
get or fetch user
alright
Not too sure how I'd go about distinguishing user ids from guild ids though, think it would be better for me to use seperate tables and then I can search the tables dependent on where the command was executed.
Yea that's why I'd do two tables
yea that was what i was suggesting, imo the cleanest way
Yeah, I'll consult some of my friends and see if they can give me a hand with this db stuff, not too sure how much it'll help but there's only one way to find out.
Thanks for the help :)
np
Just start with something, that'll get you most of the way there
you can always change stuff later
Was the plan, just going to see what happens.
Worst case scenario, I have to start the DB stuff again 🤷
meh if you just do two tables with the schema I said I don't see much need to change that
Neither, just going to hope my friends can give me a hand - some of them have been doing dbs for many years so hopefully all will be okay :p
yea it'll be fine
Just quick question, would you advise 2d classes?
class db:
class user_install:
pass
class guild_install:
pass```
never used something like that, no idea
I'd just duplicate the functions for the dB access in the dB class, once for guild and once for users
but maybe that works better but yea
Yeah I have no idea what's better - I'll just do some experimenting and see what works I guess
yea that'll probably show what's better (or if it doesn't really matter)
Ignoring exception in on_connect
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 400, in _run_event
await coro(*args, **kwargs)
File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 1178, in on_connect
await self.sync_commands()
File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 754, in sync_commands
app_cmds = await self.register_commands(
File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 531, in register_commands
prefetched_commands = await self._bot.http.get_guild_commands(
File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 367, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access``` i get this error randomly and im not entirely sure what's its being caused by, does anyone have any ideas? the bot has like 20k lines of code in total so hard to debnug
On startup or during runtime
both. it gets thrown before on_ready is fired. and sometimes when the bot is running randomly
Have you, by chance, got suggestions for permissions a user must have to be able to create/edit the message tags? Thinking of MANAGE_MESSAGES but I don't really know the world of permissions >.>
I feel like that's too strict. Might make it configurable in the future (maybe add compatibility for a guild to specify a role) but I think that's too much work to put into the first release. I'll put it on timeline for the v1.1 update :)
I don't know really, maybe someone else who knows the library a bit more in depth can tell you better but I don't think that error is in your control really
Ideally, you make the entire command restricted using @discord.default_permissions(manage_messages=True) and that way every server owner can override it
Yeah I'll just experiment and see what works
If you wanna make it configurable definitely use that decorator, don't try to make that yourself
way more work and everyone can still see the command
thats kinda what ive been thinking as well, because no user has ever reported any sort of issue to me
yea judging by the error there seems to be an issue getting a guild's commands
user_member = commands.Bot.get_or_fetch_user(data['user_id'])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Client.get_or_fetch_user() missing 1 required positional argument: 'id'
why this error is occuring
read the error
the first one is self,
wait
that's.. not how it works lmao
.rtfm get_or_fetch_user
discord.ext.commands.Bot.get_or_fetch_user
discord.ext.bridge.AutoShardedBot.get_or_fetch_user
discord.ext.commands.AutoShardedBot.get_or_fetch_user
discord.Client.get_or_fetch_user
discord.Bot.get_or_fetch_user
discord.AutoShardedBot.get_or_fetch_user
discord.AutoShardedClient.get_or_fetch_user
discord.ext.bridge.Bot.get_or_fetch_user
check every guild_ids you have set on your commands
one of the servers you've specified has de-authorized or kicked the bot
what's the difference? like I've only ever heard of kicking, what's deauthorizing
settings > integrations > remove app
but that also kicks the bot no?
Doesn't that just kick the bot?
yes, but it's also possible to have a bot without the commands scope
in which case it isn't authorized
ic
(discord put some effort into preventing this but eh some edge cases exist)
im only specifying two guilds, using guild_ids both the bot have access too / i use the commands in both servers
you're 100% sure there's no stray guild ids? because that error is only possible with an invalid one
oh wait youre definitely right thats my apology. i forgot, that in the second server i only have the "Beta" bot not the main bot in it
rip
i wont be able to properly test until i restart the main bot, so probably within next day. But thank you.
its where i was using a slash command group
and specified two guilds, one of them the main bot doesnt have access too.
hi, what are the limit for embed title and description
2000 combined for the entire embed i believe, not sure if there are specific limits for the title etc
https://docs.pycord.dev/en/stable/api/data_classes.html#discord.Embed there are limits apparently, see here
Some classes are just there to be data containers, this lists them. Unlike models you are allowed to create most of these yourself, even if they can also be used to hold attributes. Nearly all clas...
- Embed title is limited to 256 characters
- Embed description is limited to 4096 characters
- An embed can contain a maximum of 25 fields
- A field name/title is limited to 256 character and the value of the field is limited to 1024 characters
- Embed footer is limited to 2048 characters
- Embed author name is limited to 256 characters
- The total of characters allowed in an embed is 6000
https://www.pythondiscord.com/pages/guides/python-guides/discord-embed-limits/
yeah it's pretty long actually
they changed that at some point then
i firmly remember it being 2000 for the entire embed at one point
I've managed to make a script that makes a new .sqlite file for every user/guild, it's the only way I can see this working properly. You got any suggestions to trim it down into 1/2 files (user/guilc tags)?
import discord, logging, os, aiosqlite, asyncio
async with aiosqlite.connect('tags.db') as db:
table = f'tags_{ctx.guild.id}' if ctx.guild else f'tags_{ctx.author.id}'
await db.execute(f'''
CREATE TABLE IF NOT EXISTS {table} (
name TEXT UNIQUE NOT NULL,
content TEXT NOT NULL
)
''')
try:
await db.execute(f'INSERT INTO {table} (name, content) VALUES (?, ?)', (name, content))
await db.commit()
await ctx.respond(f'Tag "{name}" created successfully!')
except aiosqlite.IntegrityError:
await ctx.respond(f'Tag "{name}" already exists.')
Why not just have 2 tables with a column for guild_id or user_id respectively?
User_Tags cols: user_id name content
Guild_Tags cols: guild_id name content
if they run tag as a user command it would be a user id?
yeah ik i already told them about just using one more collomn but they prefer to use 2 tables
I was recomending 2 tables. What it looks like they are doing now is a new table for every guild and every user id
table = f'tags_{ctx.guild.id}' if ctx.guild else f'tags_{ctx.author.id}'
oooo i see now srry i didnt understand that
hey there
So I have an existing /ban command that logs the ban into a log channel and I would also like to log bans that are issued directly with discord interface so I thought about using the the event "on_member_ban" but it seems there isn't a direct way to retrieve the reason nor the author who did the ban.
Maybe there's a better way to do this, any ideas?
yup that was the reasoning. My console is clean now!
you would have to look at the audit log for that
yeah that's what I thought, the best would be to use on_audit_log_entry event I think
yeah, probably
tho I'm having an issue, the entry.target is always None
according to the docs the target is the user who got banned
sure
getting this when printing entry
<AuditLogEntry id=XXX action=AuditLogAction.ban user=<Member id=XXX name='js7457' global_name='JS7457' bot=False nick='XXX' guild=<Guild id=XXX name='XXX' shard_id=0 chunked=True member_count=8753>>>
the member id is mine and there's no info on the target
This section outlines the different types of events listened by Client. There are 3 ways to register an event, the first way is through the use of Client.event(). The second way is through subclass...
can you try the raw one?
sure
As the user is not cached It returns None. You will have to get the ID and convert it to a user manually
@little cobalt @lapis dock I can indeed get the target id using the raw event
thank you
however I do not understand the cache thing
what is that about?
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
whenever i am running any command, i am getting this error.
but if i like run the same command twice, the command runs perfectly ol
why is it happening i have deferred also
using
await ctx.response.defer()
If your bot stores all of the information about every user, guild, channel, etc it can see it would use up massive amounts of memory. So it only stores the information of the first X of all of those categories. When the bot receives a members information is "deletes" the most out of date information it has to make room.
is the defer at the top of the callback?
order_group = SlashCommandGroup(
name="order",
description="Manage Everything related to order",
guild_ids=[1241794451958136993,1236055846308286637],
default_member_permissions=discord.Permissions(administrator=True)
)
@order_group.command(description="Create an order")
async def create(
self,
ctx,
name: Option(str, "Enter name of the order", required=True), # type: ignore
user: Option(discord.Member, "Mention the user you want to send", required=True), # type: ignore
time: Option(str, "Enter the Delivery time", required=True) # type: ignore
):
await ctx.response.defer()
...
yeap
i have defer every command like this
on the top
but then why would it delete the most recent info?
I'm banning an alt account to test this event and it shows up well in the audit logs in the server settings
there haven't been any other audits between the tests
When you restart the bot user cache is generally not filled. So your alt is not known by the bot. Discord does not give the information of a banned user on the ban event (which is why we use cache to get user info). You could try running one of your bots commands on your alt before banning and it would probably not be None
ohhh okay now I understand, thank you 😄
but I suppose the best way is to go with the raw event for my case?
specifically what line in your callback is this error from?
yeah, for accurate logs you generally need to use the Raw event.
for every slashcommands in the group
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.12/site-packages/discord/bot.py", line 1130, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.12/site-packages/discord/commands/core.py", line 376, in invoke
await injected(ctx)
File "/home/container/.local/lib/python3.12/site-packages/discord/commands/core.py", line 131, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.12/site-packages/discord/commands/core.py", line 1370, in _invoke
await command.invoke(ctx)
File "/home/container/.local/lib/python3.12/site-packages/discord/commands/core.py", line 376, in invoke
await injected(ctx)
File "/home/container/.local/lib/python3.12/site-packages/discord/commands/core.py", line 139, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
but then if I want to retrieve the username of that target id wouldn't that pose a problem if the user is banned?
i think its because it take to munch timen maybe use defer and see if that's better
u already used it
yeap
can you show us that command ?
?tag paste
Please copy and paste your code here. This makes it easier for everyone helping you.
wait
Why would it be an issue?
oh just thought that I wouldn't be able to retrieve the username of a banned member
Unrelated but why the hell are you replying with empty views to every command
You have to fetch the user if you want that information.
just tested that and works perfectly
thank you !
its only that group ?
that have this issue ?
yeah
oh ill remove it
empty view can be the issue
lemme try wait
go even further up in the traceback. There is one more section above this
ignoring exception in command order complete:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.12/site-packages/discord/commands/core.py", line 131, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.12/site-packages/discord/commands/core.py", line 1009, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "/home/container/commands/order_manage.py", line 149, in complete
await ctx.response.defer()
File "/home/container/.local/lib/python3.12/site-packages/discord/interactions.py", line 748, in defer
await self._locked_response(
File "/home/container/.local/lib/python3.12/site-packages/discord/interactions.py", line 1243, in _locked_response
await coro
File "/home/container/.local/lib/python3.12/site-packages/discord/webhook/async_.py", line 220, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.12/site-packages/discord/bot.py", line 1130, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.12/site-packages/discord/commands/core.py", line 376, in invoke
await injected(ctx)
File "/home/container/.local/lib/python3.12/site-packages/discord/commands/core.py", line 131, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.12/site-packages/discord/commands/core.py", line 1370, in _invoke
await command.invoke(ctx)
File "/home/container/.local/lib/python3.12/site-packages/discord/commands/core.py", line 376, in invoke
await injected(ctx)
File "/home/container/.local/lib/python3.12/site-packages/discord/commands/core.py", line 139, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
strange that its the defer that cause this issue
is your host really slow? The problem is it takes more than 3 seconds for your bot to respond even with the defer
yeap i removed the empty views and it worked thanks!
nope, its working fine now
ok, that is very weird. Glad it works now
WHAT
you're making a new db for every user lmao
You need ONE sqlite file
Everything else you do with SQL inside of that sqlite file
One sqlite file = one entire DB
I knowwwwwww
I just can't figure out wtf I'm doing 😭
Gimme an hour to go learn sql again
I still see a reason to split it up with 1 table having user tags and one table having guild tags incase you want to add functionality to one in the future but not the other. That is up to you however
yea, thats also what i suggested to them earlier
async def callback(self, interaction: Interaction):
channel = interaction.channel
seller_id = channel.topic
seller = discord.utils.get(interaction.guild.members, id=seller_id)
tickets_cat = discord.utils.get(interaction.guild.categories, id=1234319572706791424)
print(seller_id)
print(tickets_cat)
ow = {
interaction.user: discord.PermissionOverwrite(read_messages=True, send_messages=True, view_channel=True, read_message_history=True),
seller: discord.PermissionOverwrite(read_messages=True, send_messages=True, view_channel=True, read_message_history=True),
interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False, view_channel=False)
}
ticket_channel = await interaction.guild.create_text_channel(name=f"{interaction.user.name}-account-buy", category=tickets_cat, overwrites=ow)
print(ticket_channel)
await ticket_channel.send(f"Added {interaction.user.mention} as Buyer and {seller.mention} as Seller.")
await interaction.respond(f"Created your ticket <#{ticket_channel.id}>")```
I get this error when clicking the button:
768682559634538566
TICKETS
Ignoring exception in view <AccountBuyView timeout=None children=1> for item <AccountBuy style=<ButtonStyle.success: 3> url=None disabled=False label='Buy' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\Acer\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\view.py", line 426, in _scheduled_task
await item.callback(interaction)
File "C:\Users\Acer\PycharmProjects\lcmp-bot\views\account_buy.py", line 32, in callback
ticket_channel = await interaction.guild.create_text_channel(name=f"{interaction.user.name}-account-buy", category=tickets_cat, overwrites=ow)
File "C:\Users\Acer\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\guild.py", line 1217, in create_text_channel
data = await self._create_channel(
File "C:\Users\Acer\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\guild.py", line 1096, in _create_channel
"id": target.id,
AttributeError: 'NoneType' object has no attribute 'id'
printing the tickets category prints out the name so why cant it create the channel
read the error
it being none means it didn't "find" it
all of em, i have similar code n a different view whch works just fine so think the bot does have the ability to see the category
well yeah but it was able to print out the name of the category a bit earlier in the code
so im lost as to how its none
view the server as the bot role and see if it can see it first of all
okay
also, it might simply not be cached (for some reason), so try get_or_fetch instead
how would i access the bot object inside my view tho, should i pass it in as an arg
discord.utils.get_or_fetch
yeah just fetch it
and yes, that's how I do it
what do i put in for the attr arg
"channel"
tickets_cat = discord.utils.get_or_fetch(interaction.guild, id=1234319572706791424, attr="channel")
something like this?
whoops i removed .categories
no, you shouldn't have categories
oh
all CategoryChannel objects are GuildChannel objects so it should be a channel
yea i was also a bit confused by that, but shouldn't that still work?
both d.CategoryChannel.get_channel and d.CategoryChannel.fetch_channel don't exist
so leaving it like this is the right way, yeah?
ah
and besides, categories returns an array
should be
yeah still gave me the same error
Ignoring exception in view <AccountBuyView timeout=None children=1> for item <AccountBuy style=<ButtonStyle.success: 3> url=None disabled=False label='Buy' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\Acer\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\view.py", line 426, in _scheduled_task
await item.callback(interaction)
File "C:\Users\Acer\PycharmProjects\lcmp-bot\views\account_buy.py", line 33, in callback
ticket_channel = await interaction.guild.create_text_channel(name=f"{interaction.user.name}-account-buy", category=tickets_cat, overwrites=ow)
File "C:\Users\Acer\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\guild.py", line 1217, in create_text_channel
data = await self._create_channel(
File "C:\Users\Acer\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\guild.py", line 1096, in _create_channel
"id": target.id,
AttributeError: 'NoneType' object has no attribute 'id'
768682559634538566
TICKETS
<class 'discord.channel.CategoryChannel'>```
oh wait you didn't await the coro
i did
i saw the error and added it myself
this is probably jank but can't you just do ticket_cat = discord.Object(id= category ID)
i think there's some permissions thing in the backend
nope still throws the same error
print your overwrites variable ow
if you define ticket_cat as this? yea then its not that being the issue i think lol
seller_id = channel.topic
seller = discord.utils.get(interaction.guild.members, id=seller_id)```this 100% returns None
and breaks the entire overwrites
{<Member id=768682559634538566 name='thunderins2' global_name='thunderins' bot=False nick=None guild=<Guild id=1234305926702432277 name='Banana Marketplaace' shard_id=0 chunked=True member_count=20>>: <discord.permissions.PermissionOverwrite object at 0x00000186DF5179D0>, None: <discord.permissions.PermissionOverwrite object at 0x00000186DF5A4460>, <Role id=1234305926702432277 name='@everyone'>: <discord.permissions.PermissionOverwrite object at 0x00000186DF5A4280>}
ah hey
why's that?
because channel.topic is a string
yep
convert it to int and use interaction.guild.get_member
right
allgood
How to ping a server event?
Don't think that's possible if you mean an inline ping like #general
you can only send the share url and that'll show the event embed
Alright, thanks
Is there a way to take custom emoji inputs in a Modal InputText without entering the full name with ID (copied from escaping the emoji)?
text (str) only
Well technically emojis are strings lol. That's annoying. For now we'll escape them
Idk if you can do it with copy and paste
Why does pycord doesn’t have a setup_hook like discord.py ( if I understand what is it is something that run prior to the bot.run) that will be useful for the load_extension etc or does it already exist something similar
there isn't any implicit need for it. It's not like discord.py where load_extensions is asynchronous
Well ur right
Can still be useful but it’s not that important as in dpy since load extension are asynchous
(I forgot that in dpy it’s async)
Traceback (most recent call last):
File "/data/main.py", line 373, in <module>
client.run('Token')
File "/usr/local/lib/python3.10/site-packages/discord/client.py", line 766, in run
return future.result()
File "/usr/local/lib/python3.10/site-packages/discord/client.py", line 745, in runner
await self.start(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/discord/client.py", line 709, in start
await self.connect(reconnect=reconnect)
File "/usr/local/lib/python3.10/site-packages/discord/shard.py", line 475, in connect
raise item.error
File "/usr/local/lib/python3.10/site-packages/discord/shard.py", line 180, in worker
await self.ws.poll_event()
File "/usr/local/lib/python3.10/site-packages/discord/gateway.py", line 603, in poll_event
await self.received_message(msg.data)
File "/usr/local/lib/python3.10/site-packages/discord/gateway.py", line 555, in received_message
func(data)
File "/usr/local/lib/python3.10/site-packages/discord/state.py", line 818, in parse_interaction_create
interaction = Interaction(data=data, state=self)
File "/usr/local/lib/python3.10/site-packages/discord/interactions.py", line 171, in __init__
self._from_data(data)
File "/usr/local/lib/python3.10/site-packages/discord/interactions.py", line 201, in _from_data
self._guild = Guild(data=self._guild_data, state=self)
NameError: name 'Guild' is not defined. Did you mean: 'guild'?```
What does this error mean
fixed on master
Bot crash and doesn’t restart
error?
This
then you aren't on master
pip install git+https://github.com/Pycord-Development/pycord
Since when I need master
That bug is fixed on master
Yeah but why the bot crash with this error
Well it tells you
It imported stuff wrong and there's some other minor issues on 2.5
An error occurred: 'SelectOption' object has no attribute 'append'
k_options = discord.SelectOption(label="Ticket", emoji="🎫")
class CreateTicketSelect(discord.ui.View):
def __init__(self, guild_id):
super().__init__(timeout=None)
self.guild_id = guild_id
@discord.ui.select(
custom_id="bro_i_dont_know",
placeholder="👆 | CLICK ME!",
options=keks,
)
async def ticket_select_callback(self, select, interaction):
if "Ticket" in select.values:
labels = [option.label for option in select.options]
print(f"Labels: {labels}")
k_options.append_option(k_options)
else:
select.disabled = True
await interaction.response.edit_message(view=self)
my command @ticket.command(description="Add a ticket option")
async def select(self, ctx, name: str, emoji: str):
global my_option_count
await ctx.defer(ephemeral=True)
ticket_message = await db.get_message(ctx.guild.id)
if ticket_message:
try:
if await db.name_exists(ctx.guild.id, name):
await ctx.respond("This name is already in use. Please choose a different name.", ephemeral=True)
return
if my_option_count >= 5:
await ctx.respond(
"You have reached the maximum number of options (5). Please remove an option before adding a new one.",
ephemeral=True)
return
message = await ctx.channel.fetch_message(ticket_message)
view = CreateTicketSelect(k_options)
k_options.append(discord.SelectOption(label=name, emoji=emoji))
view.add_item(k_options)
await message.edit(view=view)
await ctx.respond("The option was added successfully.", ephemeral=True)
my_option_count += 1
except Exception as e:
await ctx.respond(f"An error occurred: {e}", ephemeral=True)
print(name)
await db.add_option(ctx.guild.id, name)
else:
await ctx.respond(f"The ticket message was not found. Please {self.bot.get_cmd('ticket setup')} First!", ephemeral=True, delete_after=10)```
what were you expecting ```py
k_options = discord.SelectOption(label="Ticket", emoji="🎫")
...
k_options.append_option(k_options)
and down there below your CreateTicketSelect view k_options.append(discord.SelectOption(label=name, emoji=emoji))
it seems k_options should be a list or you want select.append_option
how can I do this differently?
what are you trying to do
options.append to add
...i'm struggling to see how k_options is meant to work ```py
view = CreateTicketSelect(k_options)
k_options.append(discord.SelectOption(label=name, emoji=emoji))
view.add_item(k_options)
- Why is `CreateTicketSelect` taking `k_options` when it's meant to be a guild id?
- you use `k_options.append` as if it's meant to be a list, but then on that 3rd line you use `add_item` - which is it?
it feels to me that you don't know what's happening in your own code
Okay
But on other bots from me it wont happen
Because it doesn't affect every bot
Idk
just gotta read it https://github.com/Pycord-Development/pycord/blob/v2.5.x/discord/interactions.py#L198 ```py
self._guild: Guild | None = None
self._guild_data = data.get("guild")
if self.guild is None and self._guild_data:
self._guild = Guild(data=self._guild_data, state=self)```
Can someone tell me how I can fix this error, I get it all the time and I don't know how to fix it
TypeError: expected Item not <class 'discord.ext.commands.bot.Bot'>```
full traceback
How so ?
what is the full error in your console
Ignoring exception in modal <command.ticketview.TicketModal object at 0x0000021B051E3D10>:
Traceback (most recent call last):
File "C:\Program Files\Python311\Lib\site-packages\discord\ui\modal.py", line 341, in dispatch
await value.callback(interaction)
File "c:\Users\faust\OneDrive\Bureau\Bot-Discord\command\ticketview.py", line 33, in callback
await ticketchannel.send(f'Ticket créé par {interaction.user.mention} pour la raison suivante : {reason}', view=CloseTicketView(self.bot))
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\Python311\Lib\site-packages\discord\ui\view.py", line 184, in init
self.additem(item)
File "C:\Program Files\Python311\Lib\site-packages\discord\ui\view.py", line 291, in add_item
raise TypeError(f"expected Item not {item.__class!r}")
TypeError: expected Item not <class 'discord.ext.commands.bot.Bot'>```
ok, so what are you doing in CloseTicketView
I give it self.bot
My brain is dead, could you tell me where do I use it?
somewhere in CloseTicketView.__init__, probably
probably super? i bet you have something like ```py
class CloseTicketView(View):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)```
I have that
No
that
can you show your full init
def __init__(self, bot):
super().__init__(timeout=None)
self.bot = bot```
you're 100% sure this is CloseTicketView?
just make a screenshot of the class with your init in it
press ctrl+s
that too
How can buttons / components be used in locked threads?
?
you click them
make sure your file is saved
I enable the auto save
Like how? This symbol is there if i hover above the button 🚫
if it's locked then you can't interact at all in the thread
Aight ✅
Thought there is a way
So i can just reopen it by command or discord default by right clicking the thread
indeed, unlocking it works
though considering that mods can talk in a locked thread, perhaps the UX for that should be improved
yeah pretty weird i thought one of the ticket bots out there have it like that but looks like i thought wrong lol
Or maybe the message with the component have to be sent after the thread was closed idk have to try it. rn im doing it for the inital message
nah it doesn't work for new messages either, despite the fact that the bot can send messages at all
ok thx then i can spare that time
kinda feels like an oversight if anything
Why Have I that error now :
AttributeError: module 'discord' has no attribute 'ui'
reinstall py-cord
inb4 discord.py
Is there a way to make a slash command group be clickable in a message? I can have standard slash commands be clickable via </name:id> but I'd like a way to be able to click a slash command group for it to show all the sub-commands
no, but you can still mention each subcommand individually
Yeah, but there's a bunch lol
oh well, thanks anyway
you can automate it easier by iterating through commands and using command.mention
even better if they have descriptions set already so you don't have to write them out again
or perhaps for groups, consider making use of components/paginator to display them
Yeah, but I want to keep certain ones out and it's easier for me to do this. I was thinking of switching that in the future
fairfair
Can I use bridge commands for command groups?
there's bridge_group
awesome. I just realized I'd need to add a crap ton of code to now account for the required parameters that aren't necessarily passed, so i'm sticking with slash commands haha
(i only found out bridge commands was a thing about 10 minutes ago)
yeah not always ideal
Guys, a question, is the timeout attribute of a .View object reset after each interaction?
Yes
ok, ty!
Is there a way to get the lib + version in a command?
import os
packages = os.system("pip list")
something along those lines should do
This show the complete list?
its like giving the line into a terminal
there might be a better way to do it. that's just the first thing that came to mind when reading your question
discord.__version__ will show what version you installed through pip
If you mean for other libraries then it may vary, __version__ is a recommended implementation by PEP8 but it's not guaranteed to be present
In which case perhaps the pip command would be better
Which version is master?
i have a really dumb question
what does vc = ctx.voice_client do exactly
(it was from an older guide i think, and it says "define our voice client")
but i don't exactly understand how it works
what about it
i'm trying to make it so that i don't have to run a command
and it would just automatically connect to a specific voice channel
on startup?
well, then you'd need a set voice channel for every server, or if you only have your bot in one server, hardcode it into your on_ready
i only need it in one server
but i don't know how to specify the voice channel
is it just get_channel?
yes
You can do circular imports even though its generally not recommended, just import the variable exactly then when you need it, inside a function for example.
Because if you import it directly at the beginning, it's loaded for the entire cog and when you then try to import something from that cog back into your main.py then it says circular import, except for when you import only a specific part of your cog, a function or a variable when you need it.
It was because the variable was only on the on_ready, and there was no reason tu be rhere
Honestly didn't read further because chat didn't load 🐔
Is it possible to run a asynchronous function within a regular function and have it run via asyncio?
@property
def balance(self) -> int:
""" Returns the balance of the user
"""
async def fetch_balance() -> int:
...
# TODO: can i run fetch_balance async here?
loop.run_until_complete(fetch_balance())
but it's better to already do async functions to get/set rather try to do it in property
what's stopping you from making the balance function async
@property
.rie
You can run blocking code (such as PIL/Pillow) in an executor to run it in a separate thread: ```py
def my_blocking_func(*args):
...
@bot.command()
async def test_command(ctx):
ret = await bot.loop.run_in_executor(my_blocking_func, 'put', 'args', 'here')``` See the python documentation for more info.
Else remove the property
how to get discord profile pic from ctx?
take a look what you have at ctx
discord.ApplicationContext
discord.ApplicationContext.author
discord.ApplicationContext.bot
discord.ApplicationContext.channel
discord.ApplicationContext.channel_id
discord.ApplicationContext.cog
discord.ApplicationContext.command
discord.ApplicationContext.defer
discord.ApplicationContext.delete
discord.ApplicationContext.edit
discord.ApplicationContext.followup
discord.ApplicationContext.guild
discord.ApplicationContext.guild_id
discord.ApplicationContext.guild_locale
discord.ApplicationContext.interaction
hey there!
I have an existing join log, made a while back and recently the member mention doesn't show the name of the user anymore
example of someone leaving the server
when I click on the mention it says I do not have access
completely normal, that has always been the case
mentions in embeds do not resolve if the mentioned user isn't in the client cache
I never really realized this
Is there a way to solve this like keeping it in cache or something else?
ping them in the message
or wait
i think they did recently do some changes where even that isnt possible anymore, but not sure
try it out
Make an alt, join with it, leave with it, restart your main discord, and see if the ping resolves if you put the ping in the message content
thanks
import discord not working?
run pip list in a cmd and show the output
discord is there, but when running my bot i get the error ModuleNotFoundError: No module named 'discord'
no, show the output
that is not pycord
that is discord.py if i'm not wrong
uninstall whatever that is and run pip install py-cord
discord is a shortcut package for discord.py
pip install discord will install discord.py
is py-cord still compatible with all of discord.py
alr now what
restart your IDE and try again
okay well see my issue tho is running the bot because i have ```py
import discord
in the python code
yea, thats correct
and its just not found
do you have a venv?
show the files and folders in your project (within vscode if possible)
oh is that why i cant find the discord library
like the structure
see i've just been copying my old code from replit and its shitting itself
yeahhhh
but you dont have a .venv file/folder in your structure right? those are all?
eh just work through it, probably nothing major
correct
most are probably just "module not found" aka discord
yup thats most of it i think
open your terminal in your IDE (it should default to the venv) and run pip install py-cord again
id imagine it has the most used ones there
ohh
i just wonder how they differentiate between e.g. pycord and discord
thats why i dont use repl.it, it kinda shit
i found that out trying to migrate after 3 years 😭
i think the last time i seriously touched this code was like 2 years ago
VPS, thats all you need
Few euros a month and no worries
or just run it off my pc
24/7? nah
its on 24/7 anyways

well i run my minecraft server usually 24/7 too
so
why not a bot too 💀
anyways how do i get these libraries
?
like the discord library
pip install
lol
do you run it from inside vsc or normal cmd
vsc
try a normal cmd
its been too long since i've ran anything, can i get a quick refresher on what to do
?
did you?
i quit python a few years ago
can you do python -m pip list
@errant trout
nope, different command
same output tho
including py-cord?
yup
what if you type python, then in the console that shows up type import discord
doesnt exist 😭
then how about python -m pip install -U py-cord
yeah
can you show a screenshot of the console output from all those commands
very slow upload speed
also go to your python path here and check the lib > site packages folder
did you never actually run python main.py...?
(also you'll need to uninstall discord and discord.py, but that's for later)
all things i already said -w-
wow no way
also, you still did it wrong
you have to type python > ENTER > then try import discord
just stops recognizing import as a thing after typing python
show.
no feedback
yea okay
now do exit()
and from that very same cmd, navigate to your bot directory and run python main.py
i forgor how 😭
cd
screenshot
wait
if its a venv issue imma kms
FUCK ME DUDE
IT WAS THE STUPID FUCKING VERSION
IT DIDNT LIKE THE OFFICIAL PYTHON VERSION, IT LIKED THE MICROSOFT BETTER
YOU GOTTA BE FUCKING JOKING
bruh
I got one last error
File "C:\Users\hudso\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\commands\context.py", line 271, in ApplicationContext
@discord.utils.copy_doc(Interaction.respond)
^^^^^^^^^^^^^^^^^^^
AttributeError: type object 'Interaction' has no attribute 'respond'. Did you mean: 'response'?
PS C:\Users\hudso\Downloads\Super Awesome Bot> & C:/Users/hudso/AppData/Local/Microsoft/WindowsApps/python3.12.exe "c:/Users/hudso/Downloads/Super Awesome Bot/main.py"
Traceback (most recent call last):
File "c:\Users\hudso\Downloads\Super Awesome Bot\main.py", line 22, in <module>
import discord.commands
File "C:\Users\hudso\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\commands\__init__.py", line 26, in <module>
from .context import *
File "C:\Users\hudso\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\commands\context.py", line 69, in <module>
class ApplicationContext(discord.abc.Messageable):
File "C:\Users\hudso\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\commands\context.py", line 271, in ApplicationContext
@discord.utils.copy_doc(Interaction.respond)
^^^^^^^^^^^^^^^^^^^
AttributeError: type object 'Interaction' has no attribute 'respond'. Did you mean: 'response'?
PS C:\Users\hudso\Downloads\Super Awesome Bot>
cant find the issue
like whats causing it
that file path tells me its still the windows store version
yeahhh
stop using that, people only ever have issues with that crap
thats what fixed my issue tho
fug
can you run python -m pip list again
and you ONLY have this version of python installed now right
in a bit, i gotta drive home
How can i set a regex in automod
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 ...
error py An error occurred: 'TutorialSelect' object has no attribute 'append' mein code ```py
@ticket.command(description="Add a ticket option")
async def select(self, ctx, name: str, emoji: str):
global my_option_count
await ctx.defer(ephemeral=True)
ticket_message = await db.get_message(ctx.guild.id)
if ticket_message:
try:
if await db.name_exists(ctx.guild.id, name):
await ctx.respond("This name is already in use. Please choose a different name.", ephemeral=True)
return
if my_option_count >= 5:
await ctx.respond(
"You have reached the maximum number of options (5). Please remove an option before adding a new one.",
ephemeral=True)
return
select = TutorialSelect()
select.append(discord.SelectOption(label=name, emoji=emoji))
await ctx.respond("The option was added successfully.", ephemeral=True)
my_option_count += 1
except Exception as e:
await ctx.respond(f"An error occurred: {e}", ephemeral=True)
print(name)
await db.add_option(ctx.guild.id, name)
else:
await ctx.respond(f"The ticket message was not found. Please {self.bot.get_cmd('ticket setup')} First!", ephemeral=True, delete_after=10)``` meine class ```py
class TutorialSelect(discord.ui.Select):
def init(self):
super().init(
min_values=1,
max_values=1,
placeholder="Triff eine Auswahl",
options=t_options
)
async def callback(self, select, interaction):
if "Ticket" in select.values:
labels = [option.label for option in select.options]
select.append_option(t_options)
await interaction.response.edit_message(view=self)```
read the error
you are trying to use .append on your own class
that makes no sense
Besides, i dont think what you're doing would work anyway but not sure
i have fix
How would I pass labels and values to the autocomplete, instead of just values (or labels?)? Is the only way using OptionChoices or can I also just use dicts?
you cant, thats not how autocomplete works
yes, you need optionchoices
Can sub-application-commands have their own default_permissions?
pretty sure no
or wait actually
i think i did do that once, one second
you can
you just have to use optionchoices
aw man that sucks, thanks
I'll just have to make a subgroup with the perms
wait is that a thing?
or are perms down to the root
root only
you can always add your own checks
whats the command and the subcommands in question
like why do you need just one / more subcommands restricted
self-roles, I want /sr give to be world accessible, but /sr create, /sr edit, and /sr delete to be manage-roles only
Ok, so plain dicts (like {"label": "mylabel", "value": 123}) are not (currently) supported?
i believe so
no, as per the docs
it's probably fairly easy to convert that though
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
yeah it is
only takes a list of str or optionchoices
if you want to pr it I would approve
hm
could make it so you have another command like /settings where everything is grouped under
like all the admin cmds
I do have that, but /settings is more a meta-thing (e.g. configuring prefix, log channels, etc). grouping it under /sr clearly indicates that its specifically for the self-roles system
its fine though, i'm just requiring manage_roles, nobody will care
/settings sr add

I doubt anyone changes slash command permissions from their defaults anyway
eh could do
Most don't, some do
I'll play about with some testing
the minority that do probably wouldn't mind two or three commands having hard-coded permissions anyway
manage_roles is generally a sensible requirement for... managing roles, lol
yea
Oh that's just reminded me
can options be dynamic?
or will I have to use autocomplete and validate
Options are static
I think it depends on what your options contain- autocomplete for channel selection for example can be different on every guild, no?
so i tested stuff for my new help command and comes to the point where the bot throws me the following error:
help.py konnte nicht geladen werden. [Extension 'commands.help' raised an error: ClientException: Too many arguments passed to the options kwarg.]
my next question, only two Options for one command allowed? :O
@slash_command(name="help", description="When you know, you know (WIP)",
options=[
Option(
input_type=str,
name="options",
description="What type of commands you want to see",
choices=[
OptionChoice(name="User Commands", value="user"),
OptionChoice(name="Slash Commands", value="slash"),
OptionChoice(name="Message Commands", value="message"),
OptionChoice(name="Slash Command Groups", value="group")
],
required=False
),
Option(
imput_type=str,
name="group",
description="Specific group you want to see",
required=False
),
Option(
input_type=str,
name="command",
description="Specific command you want to see",
required=False
)
]
)```
or....

wait....
alright nvm, got it
missed one varible in the definition head
does pycord support that feature some bots have where like, it responds with a different name and pfp than the bot actually has?
idk how to actually describe it
webhooks?
have to setup a webhook beforehand or create one through the bot, then retrieve through channel.webhooks
thank you :3
Cosmetic question:
embed.description=f"Description: `{command.description}`\n" \
f"Usage: `{command.name} {', '.join([f'<{i.name}>' for i in command.options])}`\n" \
f"Type: `{type(command).__name__}`"
how to accomplish this ^^^^
the picture is the output and i dont wanna have to use cheat chars xD
random ideas appreciated
i dont get your question lmao
doesnt that code, do that?
Thanks