#Basic Pycord Help
1 messages · Page 33 of 1
do you have a bare except? IE except: with nothing between the except and the :
No, i have discord forbidden and HTTPException
👍
whats the limit for changing voice channel names?
thank you!
Oh yea
That arrangement wasn't the first thing on my mind while figuring it out. Thank you
By the way is it an short way to disable the buttons when it's used when editing the message?
When editing I think the view gets sent again, so guessing put disable as last part?
try it and see
My bot won't run- I copypasted the starter from the guide, but it throws an error
AttributeError: module 'discord' has no attribute 'Bot'
show your pip list
Package Version
------------- -------
aiohttp 3.9.5
aiosignal 1.3.1
attrs 23.2.0
frozenlist 1.4.1
idna 3.7
load-dotenv 0.1.0
multidict 6.0.5
pip 24.0
py-cord 2.5.0
python-dotenv 1.0.1
yarl 1.9.4
Yes- Python 3.12.3, however also doesn't work outside of it
is that the pip list from inside your venv?
Yes.
did you try reinstalling?
Not inside of it no, but I have outside of it
well try reinstalling it in the venv
first restart your IDE'
Done- still doesn't work
same error?
Yes.
right after import discord add print(discord.__version__)
I get a new error:
AttributeError: module 'discord' has no attribute '__version__'
Well, thats new. Kek
Can you show your pip list pls
they did
@little cobalt
Package Version
------------- -------
aiohttp 3.9.5
aiosignal 1.3.1
attrs 23.2.0
frozenlist 1.4.1
idna 3.7
load-dotenv 0.1.0
multidict 6.0.5
pip 24.0
py-cord 2.5.0
python-dotenv 1.0.1
yarl 1.9.4
oh nvm xd
can you go into your venv > lib > site packages > discord and show whats in there
Quite a bit in there- do you want a dir or a screenshot or two?
just show some stuff, no need to show everything
Alright.
Do you have any files or folders that you created named discord?
No.
well, looks like it should
Yeah- it's odd.
can you show your project files
import discord
import os.path
print(os.path.abspath(discord))
print(os.path.abspath(discord.__file__))
can you run this
take out any personal info in the file path before sending btw
No, it crashes-
NameError: name 'my_module' is not defined
forgot to edit it to discord you can copy paste the above again
Alright.
Still crashes-
File "<frozen ntpath>", line 599, in abspath
File "<frozen ntpath>", line 566, in normpath
TypeError: expected str, bytes or os.PathLike object, not module
ok get rid of the first print statement than.
Same happens.
ok, try just the first printstatement not the second
Same error.
try
import discord
print(discord.__path__)
tf lol
_NamespacePath(['C:\\Users\\[REDACTED]\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python312\\site-packages\\discord'])
wtf is that folder name
I'm using the Microsoft store version of Python.
I can swap it out for the python.org version- I have both.
It should look like this
[More Path Here]\[Your Project Folder Name]\.venv\Lib\site-packages\discord
It appears to install globally.
well, even so, does it work with the normal python?
I'll test it again.
you probably need to activate your venv before installing
if it is installing globally
do you run your bot via the IDE or just via the cmd btw
in the terminal as well?
(.venv) PS [Path to project folder]> pip install py-cord?
The command prompt- python3 main.py
Yes.
yea, that doesnt use your venv
Usually you run it via the IDE because your IDE handles the venv
How do I do that? (VSC)
You can look up how I'm sure. I have never done that though
yea no clue with vsc either
but im confused that it even imports without erroring then
I don't use VSC but if you look up how to set up a python venv in VSC you will find something
🎉
Hi again! Does anyone know how I can add an optional argument to a / command? Guide doesn't seem to mention it.
required=False
of course
How do I provide it? Syntax looks a little different.
How? The guide shows subcommands as looking like this
math = discord.SlashCommandGroup("math", "Math related commands")
@math.command()
async def add(ctx, num1: int, num2: int):
How do I set required on it?
well, use the option decorator or the option typehint lol
like you do with other commands too (i hope)
This is my first command
under math.command, put @discord.option(name="num1", type=int, required=False)
and the same for your other option
thats how you explicitly make options
So like
Do I put it in
@math.command()
async def add():
@discord.option(name="num1", type=int, required=False)
@math.command(@discord.option(args))
async def add:
pass
UNDER
not in
and again, you leave the rest as it is
you just removed half your function header lol
@math.command()
@discord.option(...)
async def add():
pass
leave the function header as it was before
dont change the parameters of it
@math.command()
@discord.option(...)
async def add(ctx, num1: int, num2: int):
...
like that
and then you need another option decorator for the other option
doing it this way also makes the typehint in the function header optional and really just to help yourself
Is num1 the option (discord.option(...))?
.
Options pick the parameter they bind to via the name parameter (usually)
So if I name my option asdf and then add
async def add(ctx, asdf: int)
asdf is the option?
yea
wdym undefined
Not supplied.
by default None is passed
So
if asdf == None:
pass
else:
pass
Thank you.
just wanted to know if 2 discord.ext.tasks loops are run simultanously or one after the other
its async, so, kinda both
actually running heavy tasks in both so cant really have much delay as then the results wont be perfect
but thanks will give it a go and see
as long as it uses no blocking code
meaning?
ah
no worries i think no blocking code just heavy queries andstuff ongoing
yes.
so to convert to async just right async def or need to change the code?
do you do db queries or API requests?
i do api requests through requests.get atm
use aiohttp
how can i create a command that restarts the bots? like /restart stops it and starts the entire bot again as if i were running my bot file
why do you need to restart your bot so often that it needs a command
its for config changes, im using a json file and i have commands to update it but i need to restart the bot each time for it actually reflect those changes
what are you updating that needs a restart
you can definitely update configs without restart
just read the json file again lol
please read #how-to-get-help
fuck wrong link
Help rules-
This is not a server that will write code for you (AKA spoon-feeding.) We will offer help but questions like "How to make a warn command?" will not be answered.
meh
granted i did the same earlie-
they were more asking for a way to restart the bot because there's no bot.restart
When someone sends #channel, that carries the channel id right?
if it looks like a mention its formatted like one
Do you mean something like #app-commands?
ah. So if I want the bot to get a channel id from a response, getting it from a channel mention would be most useful I'm guessing
slash command?
Yes basically I'm testing a command that allows me to use the bot to post text to another channel
you can use discord.TextChannel as option
so I would run the command, it would prompt me to mention the channel, then it would read the message for a channel id if its a channel mention(?)
at least that's how I see the first part working
no
you just make the channel a normal option like any other
itll even list the channels of the server
and then you select that and the parameter will be the channel already, no id or anything
just make an option and use discord.TextChannel as the input type
or if you don't explicity use discord.Option you can just typehint the parameter as discord.TextChannel
so would a channel mention be an appropriate discord.TextChannel input?
Ok
Anyone know why the status of this (certified) bot don't load after 5 mins, while it load instant on a test bot ?
I just switched to pycord, on discord.py it took like 5 mins to load (idk why), now it dont load anymore
sharded?
might be the reason then, not sure tho
it will take more time or just don't load ?
someone else might know
is the status change in your on ready or in your bot definition
in my onready
should I moove it ?
just set it in your bot definition
how ? Do you have an example ?
my bot definition is : bot = commands.AutoShardedBot(intents=intents, command_prefix="Cl", shard_count=2)
just copy the activity= part over to the bot definition
you dont have to set a shard count btw
my bot has 700 servers so if i don't set it, it will have 1 shard
You cant even shard until 1000 for all i know
he i can't explain bcs i don't know.. 
yea just copy this over to your bot definition and replace "stream" with the actual discord.Streaming
no.
fine 
Please don't send screenshots of code. Copy/paste ot amd wrap it in
```py
# Your code goes here
```
discord.Bot(...status=discord.Status.online, activity=discord.Streaming(random.choice(status), url=....))
deleted, this clogs the chat
if i needed that i wouldve asked for it
this just clogs the chat now
You joined today and are already minimodding, and its a bit annoying
bot = commands.AutoShardedBot(intents=intents, command_prefix="Cl", shard_count=2, status=discord.Status.online, activity=discord.Streaming(random.choice(status), url="https://www.twitch.tv/potentielsaumon")
yea
this doesn't allow the status to change...
?
you see the random.choice(status)?
yea?
the intention is for it to change every 10 seconds
sorry :c
but once the bot is ready, the changeStatus() will start
but toothy is suggesting for you to remove changeStatus
"copy" != "move"
and even if that isn't the case, you are just getting an extra request
They want the status to be there once the bot starts
This achieves that
so does the latter
i have no idea what the problem is
So now my bot definition is bot = commands.AutoShardedBot(intents=intents, command_prefix="Cl", shard_count=2, status=discord.Status.online, activity=discord.Streaming(random.choice(status), url="https://www.twitch.tv/potentielsaumon"))
And I have this error :
TypeError: Streaming.init() takes 1 positional argument but 2 positional arguments (and 1 keyword-only argument) were given
@sage tendon i'm not sure what you are trying to achieve
Then read up from the start
yess thanks it works
i did

Read, up
my certified bot (idk why the beta don't) takes time to display the status
You can just let the task do it
my god
it is the same internally
they said at the very start it takes like 12 minutes for it to reach on ready
.
Because on_ready fires once the bot caches everything
if this works and change_presence doesn't then there's something wrong with discord/the lib
ok, so the best way to display the status is to set it on the bot definition, no ?
nvm it works
thanks Toothy
np
and squid, according to the docs, acvities passed via the bot definition start immediately upon logging in
and evidently it seems to work
yes, but for some other reason it does not
It does work. I've used it
you solved the surface problem, but not the internal problem
Previously they only set the status in their on ready
which takes time
to reach
the onready
so it takes time to set the status initially
there is no problem anywhere but with their long bot startup which isnt a problem but unavoidable most likely
i literally dont see what the issue is
the intention of changeStatus is to change every 10 seconds, but this will not happen until on_ready. you haven't solved everything
Better than starting the task before on ready imo
i don't see the issue of starting the task before on_ready
At least the bot will display something on the status
until on_ready
then it will rotate
but that's still better than a just online bot with no status
presence should have nothing to do with cache so on_connect should still work
yes maybe, I didn't use the on_connect event
Well, he got a point kek
so here's what i did :
@bot.event
async def on_connect():
await changeStatus()
and it works
thank you everyone
i never used the on connect event
this is on discord.SlashCommandGroup
Any reason why it shouldn't be created manually? I've always done it like this and have never had issues
and wtf is the functional interface
it should be @bot.listen() instead of @bot.event
because application commands
you sure ? It worked
yeah
it's updating too right?
(i'm not sure because usually you start tasks with <task_name>.start())
follow up on this, i create slashcommandgroups manually but never call bot.add_application_command(math) as the guide suggests
is that because of using cogs or was the functionality changed
because abstraction :)
and the functional interface means bot.create_group?
not sure
cant even do that in a cog unless im dumb, because you cant access self unless in a function (or im too tired rn)
@bot.listen()
async def on_connect():
await changeStatus.start()
ok
yes now i see it update
thanks
It works but I have this error on the console :
Ignoring exception in on_connect
RuntimeError: Task is already launched and is not completed.
(it don't affect the bot but why ?)
make sure you aren't launching changeStatus anywhere else
How can I add a description to a subcommand?
No i dont
in the decorator of it
@group.command() ?
yea
so
@group.command(description="Pycord is cool")
you can also be very fancy and instead do it by doing this
async def function(ctx,...):
""" Description here """
self.bot
cogs take bot as an argument
so if you do
def __init__(self, bot):
self.bot = bot
and the setup function correctly it will work
My IDE is saying that self is undefined

could be indentation
haha
yea
i had that same issue like 10m ago
thats why i simply used SlashCommandGroup when i first made my bot i guess
how did you fix it?
SlashCommandGroup() :3
doesn't that need self.bot too?
Here's the slash cog groups example.
This might help
wow so even tho the docs say "dont use slashcommandgroup() manually" the examples still do
well then go fix it
nuh uh
complaining is less effort and more fun
and i mean its fine like this ig, i just cant imagine many people not using cogs
@edgy nest ignore ping
okay yeah i need a way for a full restart of the bot, like in my main.py file, i need to restart the entire python script but i have no clue as to how i should go abt this
Don't simply restart. do bot.close(), wait until it's shut down, then restart it
.tag restart-cmd
The only good way to restart your bot is to shut it down and have your process manager handle it. You can shutdown your bot by running Bot.close().
Do use
- Run your bot in a process manager such as:
- Systemd
- Openrc (Gentoo, Devuan)
- Runit (Void Linux)
- Supervisord
- Upstart (Old Ubuntu)
- Docker
- Manually reboot it
Do not use
- A bash loop (it can eat your C-c by rapidly spawning python and if your bot fails it won't stop it from constantly failing)
subprocess.call(you will eat your memory up by not letting your old processes die)os.exec
Tag Credit: discord.py server
A good starting point
well yes but i still dont know how to use nay of that or how to go abt starting lmao
i saw this tag before but, as i said, im not sure how im supposed to do it
@discord.ui.select(
placeholder="Pick Your Modal",
min_values=1,
max_values=1,
options=[
discord.SelectOption(
label="First Modal", description="Shows the first modal"
),
discord.SelectOption(
label="Second Modal", description="Shows the second modal"
),
],
)
async def select_callback(self, select: discord.ui.Select, interaction: discord.Interaction):
await interaction.response.edit_message(view=self)
hi, In @discord.ui.select can I keep selected value after user select an option? Currently, after select an option, select box will be back to placeholder, not keep selected value
if you respond, yes
How the heck is it possible for entry.target to be None?
it doesn't tell me anything about the person who was banned
<AuditLogEntry id=1231845452564004964 action=AuditLogAction.ban user=<Member id=313950673932779520 name='Gary' discriminator='6941' bot=True nick=None guild=<Guild id=1156330712060936312 name="Cypheriel's Epic Server" shard_id=0 chunked=True member_count=50>>>
I had try to response with this: await interaction.response.edit_message(view=self)
but select box still not keep selected value
you edit the view so its gonna reset
what is I should do to keep selected option?
are you sure Gary isn't the person who was banned
Gary is my bot...
so, yes, I'm sure
hm
The name always makes me recall fallout 🤡
https://www.youtube.com/watch?v=8WwZ7G87v0g
Here's the link example.
Yes I know
So I only make string
Can btw someone tell me how I check in a command if a server has subscribed to a bot
p sure that's not possible
you have so many questions regarding premium and boosts and bot premium lol
what are you building
This is like the 6th time you ask about premium docs and you received an answer for all of them
Whats hard about reading the docs we already provided, trying to understand something and experiment to see if that way you understood it works?
I mean the one which is on the bot profile
I don’t know how I build this into commands
hey did you solve it btw? I am facing the same issue, the command is working perfectly for me and the people I know but some users are reporting the issue "The application did not respond"
Defer the interaction.
Yeah i was trying to do it, but running into this issue atm - #1231993577580662795 message
Let me have a look.
Yeah, I did solve it. Combination of errors on my end and on the user's end.
I had just recently found that I was screwing up the kwargs for the @commands.slash_command decorator, and was doing ids = [guild IDs here] instead of the correct kwarg, guild_ids = [guild IDs here], so it wasn't actually restricting the guilds where the command could be used.
So I had just fixed that and restarted the bot, right before the issue occurred. However, the user was trying to use the bot in a server that I never intended for it to be used in (which is why I was trying to filter the guild IDs in the first place). This caused some very weird results.
It looks like Discord was still letting the user "use" the command, because Discord hadn't purged the command from that server's usable commands list - but when the user "used" the command, it just black-holed the interaction because I had since told Discord that it wasn't usable in that server.
So the user thought everything was working correctly but my bot just wasn't responding, whereas I thought everything was working correctly, but I never even got anything from Discord for his interaction. Very confusing.
I asked the user to ctrl+R his Discord client, and that solved the problem, since he was no longer seeing my command in the server it wasn't supposed to be in. He then tried to use the command in the correct server, and it worked correctly.
(I did go ahead and swap to a deferred flow, though, since it didn't really hurt anything to do that.)
oh.. got it, I think my case maybe a little different but will update here when i find a solution
Is there a way for bridge commands to have the command as a slash command in a group but also as a normal command in no group?
I have no idea what i should use for that. entitlements?
Looks like it.
What else do you need?...
not that i know of, and that would make no real sense
A check like permission check
Why
Create your own check?..
As slash command i want to have /moderation ban
As message command !ban
why?
Because having 2 commands that is the same command is pointless
How?
Welcome to the magic of creating your own decorators for your specific needs
then make !ban a pure prefix cmd
Noo
uh, yes
How should i do that
def my_decorator():
async def predicate(ctx):
pass
That's literally how you create a decorator
If you were expecting me to literally spoon-feed you with the whole code for your check, you're wrong
Code:
i!jsk py
test = discord.Entitlement(guild_id=1131636325880184854)
await ctx.send(test)```
Error:
```py
Traceback (most recent call last):
File "/data/cogs/eval.py", line 75, in _eval
ret = await func()
File "<string>", line 2, in func
TypeError: Entitlement.__init__() got an unexpected keyword argument 'guild_id'
The fuck is that supposed to be
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 ...
I want to fetch one
discord.Member and discord.Guild have their own method to create test entitlements
you never create that yourself
And an entitlement isn't just a simple guild ID, plus what toothy said
I only want to fetch if a server has this
OK, fetch your entitlements, keep track of them look if the guild is in there and return the appropriate response
What's hard about that
And how?

And we replied to u
Thanks 😄
More than 20 times
The bot object has a method and you have events to even keep track of them
You really can't solve stuff on your own
He knows…
How much is that lol
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In content: Must be 2000 or fewer in length.```
how much? about 2000 characters
This man is allergic to providing context about his stuff
something something missing required argument ctx
Like the 10 others times 🤡
And u told me stfu lmaooo
That guy can’t be real
Oh, believe it. Its right in front of you.
The fact I said it here.
And here
🤡
And if ends_at is before today's date, is it canceled?
i think that isn't possible
because if it ended, it doesnt exist anymore, meaning you cant fetch it
I do have to ask tho, Dark, what would you ever need to create a test entitlement for
... ends_at=2024-03-26 ...```
so basically in a few years itll be a gigantic list? or do they ever disappear
ok
@sage tendonU said to me I should use timeot_for.
If i use this instead timeot i get this error:
datetime.datetime.now(datetime.timezone.utc) + duration, reason=reason
TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'datetime.datetime'```
Toothy told me i should use member.timeout_for to timeout members for 28 days
I changed member.timeout to member.timeout_for and the error cone
timeout_for only receives a timedelta object
so its enouth to give it a timedelta?
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In communication_disabled_until: Invalid communication disabled timestamp```
What means that?
(27 Days Work)
@lofty parcel^^
The max is 28 days.
Yes but with timedelta 28 doesnt work
return timedelta(days=time_val)
28 doesnt work
¯_(ツ)_/¯
whats wrong
Discord or your code or the library.
Can i remove one hour?
Or 1 min
Or smth like that
Yes?... tiemdelta takes days, hours, minutes, seconds and milliseconds
i genuinely dont see what it matters for
a 27 day timeout will see most people leave anyway
if you're doing 28 days your system clock might be desynced
enough to where it think it's more than 28
^ it's a you issue. works fine for me.
check this on https://time.is
.
dont think there's a max for those specifically
is there a way to get how long a member is timed out with member.timed_out
.rtfm communication_disabled_until
fabio
in all honesty
use the fucking docs
90% of your questions are just "who can put my words into the docs"
this made me laugh
good because its laughable
There is
A group is like a command
So 100 groups, 25 subgroups
So 2500
Against 62500 for everything
(Sub sub group doesn’t exist)
I didn’t know that actually
pretty sure 200 commands is the max, not 62500..
Nope you can do 62500
man your lack of knowledge of the library would suggest you dont know anything about that
Isn't it 100 global plus 100 per guild?
200 per day registered anyway
thats a seperate one tho
so you need like months for 62500
which is nonsnse
90 global 5 user 5 guild
100 groups x 25 subgroup x 25 sub = 62500
.tags slashlimit
- gif_avatar
- foo
- name-conventions
- sqli
- timestampgenerator
- xy
- local-file
- discord.app
- snowflake
- docs
- orjson
- get_x
- subcommands
- um-cmds
- bridge
- cmd-limits
- virtualembed
- specialchannelmentions
- username
- cross-post
- developermode
- asset
- message content
- tokens
- nohello
- examples
- 429
- mongodb
- objects
- woc
- official
- timer
- install github
- announcement-channel-options
- swasvid
- ephemeral
- rie
- usernames
- invite regex
- nziie-examples
- gateway
- applicationcommands-registration-delay
- exception
- inline-fields
- update
- bitwise
- gather
- option
- solved
- get-help
.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
well, then i confused that with the 200 commands registered per day liimit
Thats wrong
Sub command are maybe not command
I do
what about command groups?
sorry, was already answered. should read first
and you'll have a question for every single one of them, right? 😄
its all premium commands
Sure
No i made a long coding break and try to get back in it but sometimes its harder than i thought xD
Yeah but how should i know the premium stuff and communication_disabled_until
the search?
mutes are obviously part of a member
so you go to "member" and start looking
If i search timeout_until i doesnt find it
.
gn
I feel really dumb to be asking this and this probably isnt the best description of what I'm looking for so apologies:
How can I create pre-selectable options for an argument in an interaction (slash) command? I've tried using the argument options as seen by arg3 in this amazing example: py @bot.command(name='command', description='This is a commmand!') async def command(ctx, arg1: int, arg2: str, arg3: str in ['a', 'b', 'c']): but I cannot get that to work, nor can I find anything on the internet (hell, I even went to ChatGPT)>
Any pointers would be appreciated!
i'd always recommend explicitly doing options via the options decorator
like this
@bot.command(name='command', description='This is a commmand!')
@discord.option(name="arg1", input_type=int)
@discord.option(name="arg2", input_type=str)
@discord.option(name="arg3", input_type=str, choices=["a", "b"])
async def command(ctx, arg1, arg2, arg3):
string is the default so you can also omit that if you want
I'll put it into context and maybe it'll make a little more sense:
I'm trying to make a /color <col> command in which users can set the color their profile shows as in the server (done with roles), and I cannot for the life of me make a list that people can select from for the col argument.
I've tried stuff like discord.Role but then it lets people select any role and that just causes a whole host of other issues & errors
yea, uses choices like in my example
Sounds good, is there a way to assign an ID or etc to each value to read what they choose or is it just done with the string?
yes, but thats a bit verbose
you need discord.OptionChoice for that, which allows you to show a name in the UI, and then the value is whatever you want it to be
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...
I'll take a look at the docs and see what it's like, thanks so much.
Just an update on the server malarchy from the other day: I scrapped it and it's now a public server :)
so it'd be
choices=[discord.OptionChoice("purple", value="#42171")...]
ideally you import OptionChoice directly because that gets really long, and you probably need to use linebreaks
I use a lot of linebreaks anyways as it just keeps my code structure all nice, shouldn't think that will be too much of an issue but will have a look :)
Thanks for the links though, should make this a whole ton easier 😅
This has saved my life for many many different things so thank you so so so much for this, I think I would've just ended up giving up on this tbh so thanks youuuuuuu <3
why am i seeing this
C:\Users\darkp\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py:753: RuntimeWarning: coroutine 'Client.run.<locals>.runner' was never awaited
future = asyncio.ensure_future(runner(), loop=loop)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
File "C:\Users\darkp\Downloads\Not stupid AI\Bot.py", line 33, in <module>
bot.run("...")
File "C:\Users\darkp\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 754, in run
future.add_done_callback(stop_loop_on_completion)
^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'add_done_callback'
clean install btw
which pycord version
future = asyncio.ensure_future(runner(), loop=loop)
is this in your c ode?
show your code
any reason you use client instead of bot?
:)
import discord
from discord.ext import commands
import json
from main import AIModel
# AI
Model = AIModel()
# Bot
intents = discord.Intents.default()
intents.messages = True
bot = commands.Bot(command_prefix="!", intents=intents)
@bot.event
async def on_ready():
print(f'Logged in')
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if bot.user.mentioned_in(message):
await Model.ask(message.content)
if message.reference and message.reference.cached_message:
if message.reference.cached_message.author == bot.user:
await Model.ask(message.content)
await bot.process_commands(message)
bot.run("...")
did you actually put a token in your run
did it work before or is htis your first try
i'm reusing the code from something else where it worked fine
can you do print(discord.__version__)
2.5.0
C:\Users\darkp\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py:753: RuntimeWarning: coroutine 'Client.run.<locals>.runner' was never awaited
future = asyncio.ensure_future(runner(), loop=loop)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
File "C:\Users\darkp\Downloads\Not stupid AI\Bot.py", line 35, in <module>
bot.run("")
File "C:\Users\darkp\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 754, in run
future.add_done_callback(stop_loop_on_completion)
^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'add_done_callback'
hm
i can try commenting that line out in the pycord code
yeah bot didnt start
can you show your pip list
really no clue
nah
i think my asyncio is corrupted
i tried discord.py and it has another weird asyncio error
dont install both at once
try re-installing python then
are you by any chance using the microsoft store version
use 3.12 if theres no reason not to
i think that screwed python even more
PS C:\Users\darkp\Downloads\Not stupid AI> pip list
Fatal error in launcher: Unable to create process using '"C:\Users\darkp\AppData\Local\Programs\Python\Python311\python.exe" "C:\Users\darkp\AppData\Local\Programs\Python\Python311\Scripts\pip.exe" list': The system cannot find the file specified.
ah yeah i probably have to fix path
allow me to reinstall all of my packages
ok that fixed it nice
thanks
love you python
Anyone happen to have any advice for avoiding rate limits during startup? Getting at least 3 per startup (they look like this): 2024-04-22 23:10:45:DEBUG:discord.http: A rate limit bucket has been exhausted (bucket: None:1229906624613842994:/applications/{application_id}/guilds/{guild_id}/commands, retry: 59.818). and it's stopping anything working for a solid 30 seconds to a minute. Bot is only in one server with 3 commands...
did you change a command a lot?
Nope, added 3 of the command options like you suggested to the /color command and that was it. It does it every startup too, and I have absolutely no idea why.
Will probably be gone tomorrow or so
ratelimits can be weird
Yeah but it's hella annoying and stopping me from using the bot for literal minutes at a time-
Is that possible to answer an interaction without sending anything ?
i tried interaction.reponse.pong but it didnt wokr
Are there any restrictions preventing me from tracking a message that's only 30 minutes old?
something like that
Is it because messages that are only 30 minutes old don't trigger the on_message_edit() function?
nope there shouldnt
did u restart ur bot between those ?
maybe that trigger only for cache message(im not sure about that)
nope
same for me
waiting for mod reply
maybe its just not that important to save everyhing
There should be a way to save everything.
so
i check the code and
there is a maxium of message by the client
Okay, not everything, but anything.
so you can either use on_raw_message_edit
umm wait
or increase the max_messages <Client>
how ?
message logging? no
nope
that's literally "saving everything"
*Okay, not everything, but anything.
so i guess
bot = discord.Bot(max_message=...)
yyep excatly
its by default to 1000
I need to keep track of a message until I restart the bot
this message
I don't need to track all messages, just this specific type. I hope that's clear.
you cant really decide
then just save it
oku wait
but you cant increase the limit only for this one
track not save
what if i set this to infinity ?🙂
your cache will.eventually.explode
i guess that ur bot will be slow
umm okh 🙂
on_raw_edit will be more useful in ur case
If the message is not found in the internal message cache, then these events will not be called
okh
yeah i am reading all doc
okh thanks a lot ❤️
yep that why on_raw_edit is better (doesnt care about the cache)
is there any way to clear cache ?
@fresh sierra
self.bot.clear()
i think
nope
it will not
i check again and no
but restart it will clear the cache
ty
u can still do bot.cached_messages = None, bot.cached_channel = None but i dont think that a good idea
seems that i find 2 bugs
first the one with the interaction.message, and also when a message is edit, even if we dont touch the view, the view parameters will be updated to the last one
explanation :
@tasks.loop(seconds=1)
async def snake_update(self):
for game in snake_games:
embed = discord.Embed(title=translator.fun.snake.embed.title)
try:
await game.message.edit(embed=embed)
except discord.NotFound:
snake_games.remove(game)
the view is set for each command like that :
await ctx.respond(embed=embed, view=Fun_Snake_View(self.bot, translator, ctx.author.id))
that mean that the author_id should not change for the same user, however if another user run the command, the old author_id will be replace by the new one when the message will be edit
(i will do futher test to test that)
how i can use a command that mantion another command?
our bot works perfectly fine and I don't have any problems with doubled messages, but then there is this one function for my Bot I implemented that for some reasons send the lost embed before the won embed even I enterd the right answer (its a quiz and if I enter the right answer I get the wrong anwer embed and directly after that the right answer embed)
this is the function:
right_input_user = await self.create_quiz(thread, gameid)
em = discord.Embed(description=f'<@{right_input_user}> answered the question right!', color=self.none_color)
if p1.id == int(right_input_user):
await thread.send(embed=em)
actual_position -= 1
elif p2.id == int(right_input_user):
await thread.send(embed=em)
actual_position += 1
and the create_quiz function:
with open('json/quiz.json', 'r') as f:
quiz_data: dict = json.load(f)
random_question = random.choice(list(quiz_data.keys()))
answer = quiz_data[random_question]
em_question = discord.Embed(description=random_question, color=self.none_color)
em_false_answer = discord.Embed(description=f'wrong answer! Try again', color=self.none_color)
await thread.send(embed=em_question, view=SkipQuestionButton(self.bot, thread, gameId))
def check(m):
return m.channel.id == thread.id and m.author != self.bot.user
while True:
message: discord.Message = await self.bot.wait_for('message', check=check)
if message.content.lower() == answer.lower():
return message.author.id
else:
if message.content.lower() == answer.lower():
return message.author.id
await message.reply(embed=em_false_answer)
while true..
is this the problem?
didn't read it yet because I'm not on pc but usually it's best to avoid that
oh I see, because of the while True the bot isn't just waiting until the message is there, but performs the line again and again so it is possible that the bot gives me mulitple responses based on the line the interpreter currently is in the while. Am I right?
can someone help me fix that
no clue from a quick look over it, use prints / debugger to see why it does that
debugger preferrably in this case
you dont need a while true
you can just remove it
wait_for will handle that
or you want the bot to check for each message ?
but then the user can only guess the right answer one time.
like when the guess is wrong the bot don't wait for another guess message
in that case while true can be an option
so if i understand ur issue is even if the answer it correct it still send the wrong embed ?
yes
if message.content.lower() == answer.lower():
return message.author.id
else:
if message.content.lower() == answer.lower():
return message.author.id
await message.reply(embed=em_false_answer)
first what the point of that ?
if else if
like if the first time is false, the second it will be also
if message.content.lower() == answer.lower():
return message.author.id
await message.reply(embed=em_false_answer)
i will check for the error let me 5s
it sends the wrong message embed and then directly the right message embed
do you have all the code ?
for i can check that ?
yea I don't really understand myself this part is coded by one of my friend
yes
dw
can i check that pls i will help with that
can we do it later? I need to go now
he said it was for testing prupose
I will ping you then
but
i think i know
when the bot answer
it trigger the while true
that then send from embed
maybe
or not
i will check with ur code
use prints or the debugger of your IDE to see the flow of execution
Will do it
Hey I have a quick question: I'm retrieving messages with my bot and I use message.content to get the string version of it. However, when someone is mentionned it appears like this in the str: <@user_id>.
In the doc I saw you can get all the mentions of the message with message.mentions, and I would like to replace the <@id> with the display name of the mentionned person.
My first idea was to use regex and to replace it with the display name of the corresponding user, but i would like to know if there's a built in way (I tried system_content but it's the same thing).
Thanks 😄
you can do a split
this might help you get all the IDs, and then you can probably get_or_fetch the users in question by the IDs that raw_mentions returns, and replace the mentions with the fetched user's name
that split will check for the <@ and then the last > to replace it
but use a regex will be more easy
you can still do message.mentions
to get the mention
and then get the member, take the display name and do a replace
for member in message.mentions:
message.content.replace(member.mention, member.display_name)
something like that
Ok thanks I'll try something like this !
i found a better way @cursive zealot
message.clean_content
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 ...
yes but this put name and not display_name
no idea what name it puts there
Guess they'll tell us if they try that
docs dont specify it
I'll try it thanks
it should be display_name if the text is correct, because "...mentions are transformed into the way the client shows it..."
there is a parameter
you can use use_nicknames = true
it puts the display name so it's perfect
yep use_nicknames is by default true
help
i dont think that's the correct line
there is not line in the error
can you show like, more
remove interaction
its ctx: discord.ApplicationContext
not discord.Interaction
and btw it worked like 5 min ago
in which you changed what?
i just updated my pycharm to 2024.1
.
yea, that has nothing to do with it not working lol
also then the whole thing, we cant see all the options
.tag blackstick
Tag not found.
.tag code
Please put your code in a code block:
```py
Here is your Code
```
That makes reading code in Discord a lot easier:
print("This is an example.")
use that pls
it was because of the missing ctx ?
yh
no errors and only the first 2 prints are getting printed
what even are these kwargs in your slash command decorator
and, well, add more prints then, if only those 2 are printing
make sure everything is not null
Honestly I dont even see why his total seconds wouldnt even get printed.
most likely because the options are strings (?)
if its 0 by standard it would just multiply by 0 and then add another 0 which should just return 0 per default.
- remove these, those do not do anything for a slash command decorator
how / where are they strings?
- make your options explicit via discord.Option or the @discord.option decorator
option default is string and i'm not sure whether this implicit method takes the default value into account when selecting the input type
ah, good question.
and so string * int would likely 💥
yeah but it would still print an error into the console xD
not if their error handling is crazy
we'll never know if they dont respond but it seems likely given what they said
how i can put the member count in a button label?
read the docs
and take a look at the examples and get creative
- Understand how buttons work, 2. Know how to get member count, 3. Put member count onto button, 4. Decide if you want to have a live member count, if yes; 5. Update your button, constantly using event listeners. 6. Read the docs.
Not sure if this has been answered but here:
</verify:1232073080969367673>where:
- "verify" is the name of your command;
- the list of numbers ("1232073080969367673") is the ID of your command
if you get the command via https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.get_application_command
^That's probably better to use for if you want to mention it within your bot's code, I was more on about typing it out 😭
I find it incredible how you guys just have thesee links to-hand :p
Well I know how to use it, it's just incredible how quickly you go from a question to having multiple links to various doc pages
would it be against the TOS if you log all the messages with the on_message event.
BUT I mentioned it with a verify button that they confirm it that the messages is getting collected from a bot?
There's probably somewhat of a data privacy concern there if you keep them long term
but im not a lawyer, and im not sure if the ToS is specific on that
for what purpose anyway
where i can get the id of the command?
Techincally speaking, no, but I would suggest making a privacy policy somewhere (public!) for your users to see at any time. Make sure it outlines specifically what happens with the message & profile data.
When you autocomplete a command (i.e: /verify), right click it and select Copy command ID
With discord.Bot.get_appliciation_command: py command = bot.get_application_command(verify) id = command.id
just use .mention when you get the command
more reliable
and you need to pass the name as a string
did it thanks
May have forgotten that minor detail :/
thats why i am here to mercilessly correct mistakes if i see some :)
I rate it :p
its not for a public bot
I did put no, the policy was just a suggestion. 👏 user trust 👏
but I still would mention it and that they have to press a button to accept it that the messages would get collected
Application Command raised an exception: TypeError: Object of type function is not JSON serializable
class WelcomeButton (discord.ui.View):
def __init__(self, bot):
self.bot = bot
super().__init__(timeout=None)
async def _get_member_count():
members_count = await getMembers()
return "You are the " + members_count + " th Member!"
@discord.ui.button(label=_get_member_count, style=discord.ButtonStyle.green, custom_id="Now members", disabled=True)
async def welcomeMassage(self, button: discord.ui.Button):
members_count = await getMembers(GUILD_ID)
button.label = f"You are the {members_count}th Member!"
command:
Create a new thread: #969574202413838426
which line is that from
122
yea well and what line is that
The file is 63 lines, that doesn't help-
button without interaction?
oh
also you will most definitely need to defer that command because you are running like a billion db operations ever time
its just for the testing
Still applies.
I'd also suggest using the discord.Bot.get_application_command().mention feature in your code rather than mention strings.
get_application_command*
ok thanks
made
self.bot usually
That's what I saidddddddd 🙄
I know about the bot malarchy, but the method is derived from discord.Bot
still
This code makes no sense at all
Wasn't a compliment but ok
You have to instance a button by yourself and just add it to a view, given you don't need a callback.
count = len(ctx.guild.members)
button = discord.ui.Button(f"You are the {count}th member!", type=..., disabled=True)
view = discord.ui.View()
view.add_item(button)
oh😢
You can't randomly slap a function into the label, that's not how it works.
That's why it throws the "not serializable error".
and how i am adding the bottun to a embed?
ok
Isn’t that just label= missing ,
added it
You need to update the view interaction.message.edit(view=self)
You don't add a button to an embed. You add it to a view (which I already did for you) and you send that view
oh ok
Looking at code on mobile is an absolute mess
i know
I didn't even bother to open his file.
I opened it on pages
However édit the view should correct ur things
And edit the message to replace the view
i finished with thsi for now i am cleaning the code now
Use cog
i am with cog
They don't need that.
That view is useless, you're doing an extra step for something you can achieve with 1 step.
A disabled button which just displays the member count
I highly assume it's for a welcome message.
So why use a callback ?
They don't need it.
And not just add a view with the label as the number
I already provided an answer.
I understand now
I was thinking it was for an verify button
That also display the number of member
I hack around it by try/excepting (or contextlib.suppress()-ing) sending a message with empty content. It marks it as responded but doesn’t send anything
Thanks :)
why?
just send a small and simple message
There are times where you don’t want to. For instance, I have a response with an Embed, and UI elements (buttons/dropdowns) that update that . I don’t need to send confirmations for that
(Granted I think this workflow was updated to edit_original_message or something, but at the time I don’t think it was available)
Anyway, point is that there are situations where a separate message response is not needed
Is it possible to have a sub command like so;
/help info
returns info
While also having
/help
returns help
There's a reason discord added intents onto bots.
p sure no
Erg okay
It would not only go for messages
Oh you mean avatar changes etc.?
Like dyno and carlbot log?
A lot of stuff
bro's CCP
CCP?
Wat bedeutet dat?
Chinese Communist Party
Because you log everything
not to mention that could also be german during 1930's
or the 60-80s
Well I have never accepted any confirmation of dyno or carlbot which allows them to document everything I do see type write join whatever. So I'm guessing it's fine, however making some kind of notice that you log everything is a good ethical practice.
I dont trust the people from the big bots
For the record I said guessing. This does not mean I am sure.
You're not allowed to use it without their consent or as allowed by Law, which I'm guessing GDPR makes it difficult for you.
That is why you have to mention it and all the other stuff like that they need an option to be able to remove there stored messages and other things
Now- I am guessing as big bots have own policies as well; they would state somewhere that if you as a server admin enable logging features of the bot, you have to be within the ToS and juristic restrictions.
Because if you wouldn't they'd just state that you chose to enable this option making you liable and not them.
however if they store your messages even after disabling the logging features and they state they don't keep such information but they do- then it's their mistake for making their bot so shitty that stuff still gets stored on the database.
So if you're going to make such a bot- and enable it on your server- make sure to have a privacy policy somewhere.
cogs.verify_v2 could not be loaded. [Extension 'cogs.verify_v2' raised an error: AttributeError: 'property' object has no attribute 'name']
pls help me i am stack on this error for a lot of time
which line is that error from
i dont know that the problem
you dont have ctx in your slash command
wait
i did some changes and its now saying
cogs.verify_v2 could not be loaded. [Extension 'cogs.verify_v2' has no 'setup' function.]
i am fucking hateing myself right now
look at my content in #creations, if it was sending a message each time it would be impossible to play, rn im just defering but i dont think that the best idea
class Ticket(ezcord.Cog, emoji="🎫"):
def __init__(self, bot):
self.bot = bot
self.ticket_owner = None
@ezcord.Cog.listener()
async def on_ready(self):
self.bot.add_view(TicketRole(self.channel_name, self.logs_channel_name, self.ticket_feedback))
self.bot.add_view(TicketView())
self.bot.add_view(CreateTicketSelect())
self.bot.add_view(QuestionsButton(self.ticket_owner))
``` ```py
[ERROR] Error while sending error report to webhook. Please check if the URL is correct.
[ERROR] Error in event on_ready
Traceback (most recent call last):
File "C:\Users\Dark_Angel\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 400, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Dark_Angel\Desktop\Jinx-Bot\cogs\ticket.py", line 94, in on_ready
self.bot.add_view(TicketRole(self.channel_name, self.logs_channel_name, self.ticket_feedback))
AttributeError: 'Ticket' object has no attribute 'channel_name'```
What's ezcord supposed to be?
The error come from ur class ticketrole
Because there are no self.channel_name define
Pycord is already easy enough.you shouldn't need an extension
class TicketRole(discord.ui.View):
def __init__(self, channel_name, logs_channel_name, ticket_feedback):
super().__init__(timeout=None)
self.channel_name = channel_name
self.logs_channel_name = logs_channel_name
self.ticket_feedback = ticket_feedback
@discord.ui.role_select(placeholder="Wähle Rollen aus", min_values=1, max_values=1, custom_id="role")
async def role_callback(self, select, interaction):
try:
teamrole_id = select.values[0].id # Access values from the select object
await db.set_teamrole(interaction.guild.id, teamrole_id)
selected_role = interaction.guild.get_role(teamrole_id)
role_mention = selected_role.mention if selected_role else "Unknown Role"
embed = discord.Embed(
title="🎫 Ticket System Setup",
description="Welcome to the ticket system setup. Follow the instructions below to configure your ticket system.",
color=discord.Color.dark_green()
)
embed.add_field(name="🔘Open Tickets",
value="``{category_name}``",
inline=False)
embed.add_field(name="🎫 Ticket Channel ", value=f"``{self.channel_name}``", inline=False)
embed.add_field(name="📜 Log Channel", value=f"``{self.logs_channel_name}``", inline=False)
embed.add_field(name="⭐ Ticket Feedback", value=f"``{self.ticket_feedback}``", inline=False)
embed.add_field(name="Great! Now you can select roles that should have access to tickets.",
value=f"The following roles can access tickets: {role_mention}\nClick on Continue afterward.",
inline=False)
await interaction.response.edit_message(embed=embed)
except Exception as e:
print(f"Error setting teamrole: {e}")
``` her is my ticket role
you have a ticket.channel_name somewhere
Check for that
The problem with most extensions, regardless if it's for pycord, some sql, or something else entirely is they tend to dumb down things. they become easy to use and its easier to do entry level things, saving time, brain cells and frustration.
Sounds good right? That's mainly what they are build for.
There is however two sides to any coin;
As soon as you try to modify what you have or build something unique you have no idea about the basics going on underneath your extensions. not only can't you do it without learning all the things you avoided with the additional wrapper but it'll hit you with twice the frustration.
first with the usual frustration that comes with learning those basics then the additional frustration that ships with modification or building sth. unique or case specific.
Don't get me wrong on the "frustration" thing. I think learning is mostly rewarding and fun, in my mind that frustration thing is just a normal part of it.
you also risk those becoming abandoned soon, and then you have code that's only partly compatible with the original library and you need to rewrite parts of it to native syntax of the original library
it's overall a bad deal imo
= 🎯
and I'll be honest, the only part of py-cord I'd consider due for a remake are views
and that's already planned
everything else is so straightforward AND well documented
own vc activity in pycord when