#Basic Pycord Help
1 messages ยท Page 53 of 1
well... you might be trying, but your cog is creating prefix commands
you're probably using the wrong decorator
ToT
its ok, i figured it out now c:
one question, is it possible without using define to call a function?
i want to all to below @pagetest.command() so i can call a var
Anyone to explain me the point of the mock, is that to test the code before the bot run that ?
Can I defer modal interactions?
no
oooh
Hello !
How can I get my own slash commands ID to mention them in another commands ?
.rtfm discord.SlashCommand.mention
yes but how can I get all the others commands from one ?
I mean... from the /help command, I would like to mention the /ping command.
How do I get the mention for /ping command from the /help command ?
I precise that they are in cogs
whether it's done all at once or one at a time I think
thanks
k thanks
does not exists on sharded bot I think.
No problem, I will not do it
it does
Hi so, I had a question. Whenever my bot goes offline, all previous views sent become permanently unfunctional, i.e. I need to resend the same msg when the bot goes online again. Is there any way to fix this? Or is the onnly way to store the message ids of these, then resend them in on_ready()?
Here's the persistent example.
you need persistent views
it is kind of what you said with messages ids
check the example above out
Feel dumb asking this, but any reason why on_member_join would simply not fire?
I have member intents enabled, and other events (i.e. on_ready) in the same cog do in fact fire.
regular member joining?
yeah
@commands.Cog.listener()
async def on_member_join(self, member: discord.Member):
logger.info("Member joined")
if member.bot:
return
await member.add_roles(self.add_role)
try:
await member.send(self.config["welcome_dm"].format(member))
except discord.Forbidden:
logger.warning(f"Failed to send welcome DM to {member.display_name}")
show intents
is there a way to change intents later on before running the bot
?
like bot.intents.smth = True
because I am working in something modular
I mean probably
like bot._connection.intents
or something
idk
because
@property
def intents(self) -> Intents:
"""The intents configured for this connection.
.. versionadded:: 1.5
"""
return self._connection.intents
but tbh
just set the intents as late as possible if it's modular
or what am I missing
I can't
let's say
I have a "welcome" extension
which needs members
but no other needs
if I disable that extension, I don't want member intents to be enabled
event on_interaction or bot.add_view(class)
meh idk
the thing is that (you might have seen it) I have a thing I made called botkit which I use as a template for all my bots now
and that is nice but oh well
at this point just gonna ad a feature in that for intents
tho
i dont get whats wrong with like, getting all disabled modules from the DB, then setting intents accordingly, then starting the bot
because I do not know what modules I have
like
the point is it being a template
so yeah sure I can know what intents are needed for the default example extensions
but for all the ones added after the template is cloned
i would have to define that
yeah actually it's what I meant
I missed the underscore
eh, is it modifiable after identify?
is there an event for when someone add a bot for user installable commands ?
I know on_guild_join when the bot joins a server, but what about user install ?
yeah thanks !!
The member flags contain stuff like "suspicious account activity" etc right?
trying to figure out how to detect if someone has one of those flags, since its not really documented at all in pycord
and i fear it's just bare
there's the SPAMMER flag as 1048576, but the other modview flags are not available
it's not included in the library because discord doesn't want it documented (i think?)
Yea, im getting a lot of users with the red account activity flag, i think that is that
how would i go about checking whether someone has that tho
i'd doubt it, you can check with #general message but it won't match up
if member.public_flags == 1048576
?
oh weird
they are different flags, SPAMMER isn't what the members view shows
oof
i think anyway
so no way?
nop
this the one btw
in the 2 minutes we talked another one joined
shows how big of a problem it is :>
i mean you can just check over all your members with the bitwise method
so this does work?
no but that's not what they asked for
yes, but to my understanding it's not what you're looking for - if it DOES work, then go for it
oh fair LOL
man idk lmfao
what i want is for every on_member_join member to be kicked if they have this
but seems not possible then if its different flags
for that you'd need to restart the bot :3
just check if the people with that spammer flag method i linked match up with what you're seeing in the mod view
yea kinda hard to test lol
a mod already kicked them so i have to wait for someone new to join
or wait, it should be on User right? so i can test it with a user app mb?
just fetch the user
you can just fetch the user yeah
it might show up
with a user app too?
can't do guild shit
it's just a fetch_user call
can do user shit
https://github.com/discord/discord-api-docs/pull/3961 for a better discussion on that flag
i hate these shitty 1 << 20 notations, they tell me nothing and its all over the discord docs
it's a bit shift
would your solution detect this combination btw?
so..
that changes the 20th bit?
probably not
no, it shifts 1 by 20 bits
so it's 100000000000000000000 (probably)
in binary
half of discord relies on bitwise logic
yea so basically what i said, makes the 20th bit 1
i guess
yea i hate discord for that
eh it's more convenient for them
sike
because bitlogic is incredibly easy
instead of having a dict of true/false/null for permissions, it's a single integer
how to use persistent view for buttons in cogs ?
The work the same way as normally.
You can use a listener in the cog to add the views when on_ready
no like i mean where to add them
i am not getting it
you add them in on_ready
so like ...
thanks sir :)
lrt me try and letting you know
@commands.Cog.listener
async def on_ready(self):
await self.bot.add_view(WhitelistButtons())
await self.bot.add_view(WhitelistRejectModal())```
Traceback (most recent call last):
File "d:\Code Projects\Fallen SMP\Fallen-SMP-BOT\Version 2\Main.py", line 7, in <module>
import COGS.Whitelist
File "d:\Code Projects\Fallen SMP\Fallen-SMP-BOT\Version 2\COGS\Whitelist.py", line 901, in <module>
async def on_ready(self):
File "C:\Users\SOHAM\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\cog.py", line 406, in listener
raise TypeError(
TypeError: Cog.listener expected str but received 'function' instead.
still after bot restart it says interaction is failing
no like i sent it
also did you add a custom ID to the buttons
then i restart the bot
opps i forgot
and set the timout to None
also dont use the same ID for every button
no i have ids for button
and timeout is to none
then just say that lol
still same
like then what to do sir so that even after bot restart it reponds to buttons and all
show your button definitions
class WhitelistButtons(discord.ui.View):
def __init__(
self, user_id: int, user: discord.Member, bot: commands.Bot, main_embed
):
super().__init__(timeout=None)
self.main_embed = main_embed
self.user_id = user_id
self.user = user
self.bot = bot
self.mongo_client = MongoClient(os.getenv("MONGO_URI"))
self.db = self.mongo_client["Users"]
self.collection = self.db["UserData"]
@discord.ui.button(
label="Accept", custom_id="accept", style=discord.ButtonStyle.success
)
async def accept_button_callback(self, button, interaction):
if interaction.user.id not in ADMINS:
await interaction.response.send_message(
"You Are Not Allowed To Use This Button", ephemeral=True
)
else:
document = self.collection.find_one({"ID": self.user_id})
if document:
username = document.get("Username")
ConsoleChannel = self.bot.get_channel(CONSOLE_CHANNEL)
await ConsoleChannel.send(f"whitelist add {self.user}")
embed = discord.Embed(
title="User Whitelisted",
description=f"User `{username}` Has Been Whitelisted",
color=0xD5E4CF,
)
user_embed = discord.Embed(
title="Whitelist Application Accepted",
description=f"Your Whitelist Application Has Been Accepted. \n## Join Now : `play.fallensmp.xyz`",
color=0xD5E4CF,
)
try:
User = self.bot.get_user(self.user_id)
await User.send(embed=user_embed)
except Exception as e:
pass
await interaction.response.send_message(embed=embed, ephemeral=True)
message_id = interaction.message.id
self.disable_all_items()
button.style = discord.ButtonStyle.secondary
self.main_embed.add_field(
name="Whitelist Accepted By",
value=f"{interaction.user.display_name}",
inline=False,
)
await interaction.followup.edit_message(
embed=self.main_embed, message_id=message_id, view=self
)
else:
embed = discord.Embed(
title="User Not Found",
description=f"No Whitelist Application Found For **{self.user.display_name}**.",
color=discord.Color.red(),
)
await interaction.response.send_message(embed=embed, ephemeral=True)
message_id = interaction.message.id
self.disable_all_items()
button.style = discord.ButtonStyle.secondary
self.main_embed.add_field(
name="ERROR", value="User Not Found", inline=False
)
await interaction.followup.edit_message(
embed=self.main_embed, message_id=message_id, view=self
)
Keep in mind that pymongo is not async and can create issues
oh ... then is there any async one ?
you also dont need bot at the button
motor
hmm i will look into it
you have to look into it ;3
also you dont need bot at the button
you already get the bot with interation.client
but the important thing right now
okk wait let me remove it
you can remove the bot at the __init__ and replace the other stuff with it
ok
should i retry ?
did not work ๐ฅฒ
any suggestions on what to do ?
Ok so atomic means if one role fails all fail
my friend said don't use on_ready but on_interaction bcs it's more praticale
on_ready is not really a problem
and on_interaction also reacts to slash commands
if (interaction.type != discord.InteractionType.component): return
I never use on_interaction
hmm will it fix the issue ?
prob
read discord.Interaction first
ok
i have another question, possible to remove help command in bridge ?
help_command=None at the bot
page_buttons = [
pages.PaginatorButton(
"first", emoji=":backskip:", style=discord.ButtonStyle.blurple
),
pages.PaginatorButton("prev", emoji=":backwardbtt1:", style=discord.ButtonStyle.blurple),
pages.PaginatorButton(
"page_indicator", style=discord.ButtonStyle.gray, disabled=True
),
pages.PaginatorButton("next", emoji=":forwardbtt2:", style=discord.ButtonStyle.blurple),
pages.PaginatorButton("last", emoji=":nextskip:", style=discord.ButtonStyle.blurple),
]
page_groups = [
pages.PageGroup(
pages=[embed_p1, embed_p2, embed_p3, embed_p4],
label="Back",
description="Detail Cards",
use_default_buttons=False,
custom_buttons=page_buttons,
disable_on_timeout=True,
timeout=300,
loop_pages=True
),
pages.PageGroup(
pages=[
total_embed
],
label="Summary",
description="All cards info in one!",
show_disabled=False,
show_indicator=False,
),
]
paginator = pages.Paginator(pages=page_groups, show_menu=True)``` it wont display custom button, somehow
can a synchronous thing inside an asynchronous function that is called inside another asynchronous function raise an Unknown Interaction error ?
Example :
async def SomeFunctions():
Calling synchronous function from flpc or fnmatch.fnmatch
@command
async def myCommand():
await SomeFunctions()
```(this is pseudo-code, not the real one).
Can the `Calling synchronous function from flpc or fnmatch.fnmatch` block the full python bot or not ?
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.
okay thanks !
done sir thanks
Personally I would start a help thread with more info. I can't help rn tho
it alr, i solved it mins ago, but another question how do i change the placeholder of the menu
discord.ext.pages
pass menu_placeholder
(i highly recommend going through paginator docs)
ok thanku
if in my error handler i raise an exception (for the case where i dont know what the underlying error is) does that stop the bot or not
im a bit dumb rn
I don't think it does
by error handler I assume you mean in the on_error event
because currently i just have this and i was told i should throw an exception instead
it would be best practice to raise back the exception (it would not break anything), or at least use the logging module instead of a print, but it shouldn't cause any problem practically
so raise(err)?
Or print the traceback
like logging.error
yea but we have different log files
with pm2
prints go somewhere other than error logs
so the print would go to an info log instead of an eror log
I mean in any case your code is not going to break
also what exception should i raise
i legit never ever work with exceptions except ignoring them explicitly
just do
raise err
or raise from as seen here
so you can have your own "UnknownError" class or whatever and you do raise UnknownError(f"{ctx.author.blah}...") from err
too much for my head rn
This is what I would do
if you wanna know
hm but i kinda dont wanna lose the information of the command used etc
that wouldn't be lost
because
- you can add it in your message
- you do raise from so it keeps the traceback
but the only exception i expect at that point is of some API providers
so idk
you decide it's your code
Just raise err

how to get a ctx.args ?
What do you want to do
I need to get parameter member by ctx.args
but idk how it work ๐
yea I got about that much
but what do you want to do
why can't you grab the option directly for example
well, ctx.args[0] if it's the first option
like for exemple to get args in View
member should be an arg not a kwargs
kwargs are generally in command the *, things
like for say command it's good
last question we can't use the args ?
like this
@bot.command()
async def test(ctx, membre : discord.Member):
await ctx.reply(f"> args : {ctx.args[0].id}")
here
async def buyer(self, ctx: LumabotContext, arg: discord.User, *, kwarg: str):
pass
for exemple ctx.args[1] will be the member, ctx.kargs["kwarg"] the kwargs
I know wth is the index
i think ctx is the first one
nice ty
done tysm
like ?
twice ๐
is pycord convert all parameter ?
like discord.TextChannel it convert id in channel
yes
Hi guys! Is there a way to create bot linked roles using py-cord?
So I was able to get it working for both pc and mobile. I was followed what someone did in the disnake server and just added a couple things. #1242420866806190091 message (Altering waveform to get discord voice message to work)
from io import BytesIO
from json import loads
import base64
from aiohttp import ClientSession, FormData
import asyncio
BOT_TOKEN = ""
channel_id = 0
async def send_voice_message(voice_bytes: BytesIO):
len_bytes = voice_bytes.read()
voice_bytes.seek(0)
async with ClientSession() as session:
async with session.post(
url=f"https://discord.com/api/v10/channels/{channel_id}/attachments",
headers={
"content-type": "application/json",
"Authorization": "Bot " + BOT_TOKEN
},
json={
"files": [{
"file_size": len(len_bytes),
"filename": "result.mp3",
"id": 0
}]
}
) as response:
data_response_upload = loads(await response.text())
url_to_upload = data_response_upload["attachments"][0]["upload_url"]
filename_upload = data_response_upload["attachments"][0]["upload_filename"]
data = FormData()
data.add_field("file", voice_bytes, filename="result.mp3")
async with session.put(
url=url_to_upload,
headers={
"Content-Type": "audio/mp3"
},
data=data
) as response:
pass
async with session.post(
url=f"https://discord.com/api/v10/channels/{channel_id}/messages",
headers={
"Content-Type": "application/json",
"Authorization": "Bot " + BOT_TOKEN
},
json={
"flags": 8192,
"attachments": [{
"id": 0,
"filename": "result.mp3",
"uploaded_filename": filename_upload,
"duration_secs": 42,
"waveform": base64.b64encode(len_bytes[:100]).decode("utf-8")
}]
}
) as response:
pass
async def get_voice_bytes(file_path: str) -> BytesIO:
with open(file_path, "rb") as file:
return BytesIO(file.read())
async def main():
voice_bytes = await get_voice_bytes("result.mp3")
await send_voice_message(voice_bytes)
asyncio.run(main())```
I won't lie I didn't do much I just have been hunting for the past couple days to find something that would work. I needed this to work for my one bot as the main thing is sending voice messages so mobile can hear too.
Can anyone help me with this problem? I have uploaded my bot to a server on Digital Ocean and the bot starts up with no problems, but the application commands have stopped working.
I tested them locally and they do work.
I get this error
Unknown integration.
I have restarted discord and the commands no longer work.
now I checked again and the commands are no longer displayed
hahaha I know what I did wrong, sorry for the inconvenience

Is there a reason that it is not built into Pycord?
bots aren't really meant to be sending them
it's not documented
title=f"Item #{self.item.id} ITEM(S)"
)```
how `{self.item.id}` works with paginator?
This is what I meant. Just maybe change Exception to something else, example RuntimeError, Exception should in theory never be used directly
def check_owner(self, ctx : commands.Context):
if await self.bot.is_owner(ctx.author):
return
else:
raise commands.NotOwner
@commands.command()
@commands.cog(check_owner)
# traceback is smthing like that :
"""
Missing 1 required argument ctx
"""
if that function isn't in a class, you have to remove self
and so I can do a thing like that :
def owner_check(ctx, bot)
@commands.check(ctx=commands.Context, bot=self.bot)
in my memory I can't use self
but how to do that
The following section outlines the API of Pycordโs prefixed command extension module. Bots: Bot: Attributes activity, allowed_mentions, application_flags, application_id, cached_messages, case_inse...
@commands.is_owner()
thats all you need
how to fix that
ahhhh
tyyy
"A decorator that adds a maximum concurrency to a command"
??????
if you dont understand it, chances are you dont need it
alr
plus it literally describes it below this

is it transform float into a datetime.datetime and after a dt or not ? discord.utils.format_dt(datetime.datetime(second=int(myfloat), style="R")
ok so it's nice for me
is there a way to center within an embed text?
nope, you can however, send an image
How can I know if a member has timeout?
thank you
Is it possible to remove an embed sent by another bot?
ye u need to do a thing like that :
message = bot.get_msg(id)
# get the message
await message.edit(embed=None)
# edit the msg
mb I didn't read right
no u can't.
okh ty
np
not a specific embed, you can just remove all embeds though I believe
yeap
how to remove ?
send a message edit with suppress=True
okh let me try
thanks ๐
Besides using ```py
@commands.slash_command(integration_types={
discord.IntegrationType.guild_install,
discord.IntegrationType.user_install,
},)
Nevermind this question, i forgot to remove command syncing.
remove dt=
go on dm
because it's style, check the docs
Please do not DM for help unless the person helping you specifically says you can. The help channels are for help so there is no reason to not use the help channels for help.
nah it's cause he is french and french is my main langage so
@opal swan just create a thread and you can talk in french there
nice
ty
for the information
code :
invitation = await random.choice(guild.text_channels).create_invite(max_age=500, max_uses=1)``` and yes I try guild.text_channels[0] but it return an another error
Traceback : Command raised an exception: IndexError: Cannot choose from an empty sequence
means guild.text_channels is empty
but no...
did you print it?
hmmm no
that's litterally what the error means
yeah so it is
do something else
use this:
the first one
but in logic it will work
alr
'NoneType' object has no attribute 'create_invite'
๐ญ
NoneType
bruh
It isn't always set
What I meant is use that in preference, and else create an invite in a random channel
Command raised an exception: HTTPException: 400 Bad Request (error code: 30001): Maximum number of guilds reached (10)
10 the max ???????
nahh
channel = guild.get_channel(guild._system_channel_id)
if channel:
invitation = await channel.create_invite(max_age=500, max_uses=1)
.tag get_x
Any function that starts with get_ in Py-cord is retrieving the related object from your bots cache. If the object is not in the bots cache the get_ method will return None. Because of this behavior you should check if the get_x method is None and if it is use the fetch_x method.
Why Is Using fetch_ Without Using get_ First Bad?
The fetch_ method makes a call to the discord API. This API call is unneeded if you already have the information. It will also make your command take longer because it will have to send and than wait for a response from the discord API. It will also contribute to the discord APIs global rate limit of 50 requests per second.
What Is Cache?
The cache is a temporary storage inside your bot. It holds many objects from members to messages. When you restart your bot the cache will be empty. When the cache is full it will delete older objects to make space for the new objects.
wtf is "max_age" lol

nuh uh
:3
just did
hello, i was trying to make a bot join a voice channel, but ctx.author.voice.channel.connect() does not work. has pycord updated to deprecate ctx.author.voice?
it doesnt even raise any errors
show your code
This requires
Intents.voice_states.
Do you have this?
i have enabled discord.Intents().all().
the problem persists in a server where the bot has admin privileges.
For testing you should always enable every permission individually
was told bots don't work with the admin permission as expected
either way, show your code
almost as if i asked that twice already
@quaint cipher
from discord.ext import commands
intents = discord.Intents().all()
intents.voice_states=True
bot=commands.Bot(command_prefix="!", status=discord.Status.online, intents=intents, help_command=None)
@bot.slash_command(guild_ids=[...])
@discord.option("text", type=discord.SlashCommandOptionType.string)
async def test(ctx:discord.ApplicationContext, text: str):
print(1)
await ctx.author.voice.channel.connect()
print(2)
bot.run(token)```
this code prints 1 and the bot joins my voice channel, but 2 is not printed.
also, ctx.voice_client returns None even the bot is in a vc.
first guess was that there was something off with intents, but using .all() and enabling .voice_states directly did not work.
you dont need intents for slash commands
???
is that true? very interesting
That's not true, idk what zervy is talking about
That was from Squid a few months ago
hmm
But I cannot find the old Basic PyCord help
should i move my question to a new post
I always said they need it
Well, it's not the issue in this case no matter what
@quaint cipher what are your bot permissions?
i enabled admin and the problem was there. I saw this and tried ticking all permissions by hand and reinvited the bot, the problem was still there.
can you print ctx.author.voice
and did you enable the intents in the dev portal too, just to make sure
you cannot start the bot without it if you added it to your code
so they are enabled
my bot is small so all privileged intents are enabled. also i think voice intents are not prevliged
and yes ctx.author.voice properly prints True
well ctx.author.channel properly prints as well
is the bot in a voice channel already in the server?
wait it was not true
it prints some long python object
type is VoiceState
show the object?
yes.
<VoiceState self_mute=True self_deaf=False self_stream=False suppress=False requested_to_speak_at=None channel=<VoiceChannel id=1090650007738265655 name='์์ ๋ฐฉ
_1' rtc_region=None position=0 bitrate=64000 video_quality_mode=<VideoQualityMode.auto: 1> user_limit=0 category_id=1090650007738265652>>
hm looks fine
.connect() does work and the bot joins, but it hangs and the following codes does not execute.
same problem happens with the bot already joined.
does this code work in other peoples envs?
it reliably spits error in my computer
This is giving you an error? If so please send the error
im gonna try
sorry the problem was that there was no error
if the second print statment runs it worked
in my enviroment 1 prints and the bot joins but 2 dosent get printed
you do not have any sort of global error handling or similar do you?
yes the code above is all there is
hmmmmmm
1
INFO:discord.voice_client:Connecting to voice...
INFO:discord.voice_client:Starting voice handshake... (connection attempt 1)
INFO:discord.voice_client:Voice handshake complete. Endpoint found milan10014.discord.media
INFO:discord.gateway:selected the voice protocol for use (xsalsa20_poly1305_lite)
INFO:discord.gateway:received secret key for voice connection
2
makes my head hurt
have you tried recreating the venv / using another bot token entirely?
just to see if that changes anything
oh maybe i should try debug mode
.tag logging
Pycord logs errors and debug information via the logging python module. It is strongly recommended that the logging module is configured, as no errors or warnings will be output if it is not set up...
oh thanks
hmm
pycord is in the latest version....
there is a new line that popped up some time later
WARNING:discord.gateway:Shard ID None has stopped responding to the gateway. Closing and restarting.
I'm gonna try to vpn in south korea to see what it does
thanks! although other music bots do work so i think it is not a regional problem
who knows
at this point
yea this is being a major headache
ctx.voice_client also returns None at all times, could this problem be related?
yeah no
1
INFO:discord.voice_client:Connecting to voice...
INFO:discord.voice_client:Starting voice handshake... (connection attempt 1)
INFO:discord.voice_client:Voice handshake complete. Endpoint found south-korea1121.discord.media
INFO:discord.gateway:selected the voice protocol for use (xsalsa20_poly1305_lite)
INFO:discord.gateway:received secret key for voice connection
2
it is None for me as well
I assume you did pip install py-cord[voice]
yes
py-cord should already got that stuff if Im not wrong?
just in case ill try to uninstall and reinstall [voice]
At this point nothing feels sure
try to recreate your venv entirely
does [voice] show up differently in pip show?
no, but you should see PyNaCl
ahhhhh
god
reinstalling worked
just for the record
i tried pip install py-cord[voice] --upgrade in a py-cord environment
sorry guys it was problem on my side
thanks for helping out
np, happy coding
thanks so much
how can i check if a token is valid and has the 3 intents enabled on the panel of discord ?
Exception Hierarchy:- Exception,-- DiscordException,-- ClientException,- InvalidData, InvalidArgument, LoginFailure, ConnectionClosed, PrivilegedIntentsRequired, InteractionResponded.,., NoMoreItem...
its more to do a requests to check if its enable, if yes then i can say its a valid token and else say there is an issue
im gonna make a thread i thing its more diffcult
why..?
Is there a way to pull message formatting from a message? For example Bold with the asterisks.
You can't in the footer
oh what about the field value?
thatโs not a valid URL
it should be with the protocol?
yes
tyvm I'll have a look
alr ty
just add https:// to the second pair
do I have to add views at the on_ready event or can I also do with before starting the bot?
i.e. [www.vinted.it](https://www.vinted.it)
has to be after start
so I cannot just do it like the cogs?
well, just add an on_ready in your cog
I just currently doing it like this
that's fine
no
only in one of them, not the other
i.e. they shouldn't match
...though at that point, you don't really need to use the markdown do you
unless you really don't want the https:// to show
oh thanks got it
yeah i dont think im going to ever click on the link but it's better looking
isee
is it possible for a bot to see options enter by an other bot command in ephemeral ?
no
how do I create a message_command in a cog ?
@commands.command
I am speaking about the context menu
oooh my bad sorry
I am a bit tired
lol
is it possible to get the client language using pycord ?
client language?
yeah, for me it is french. Is there a way to get this ?
my discord client is in french
sure
yeah, this is for a message_command from the context menus
you mean the right click at messages?
yes
and apps?
yes
hey there! i have this command which takes a role as an argument. is there a way to add "None" into the roles list-autocomplete? so the user could choose none/nothing (doesnt really matter what its called) instead of a role?
do they show up immediatly ? I don't have them on my discord but the ping test I have made was showing up immediatly
put the option as not required
example :
@option(
name="allowed",
description="True or False",
required=False,
type=bool
)
required=True/False
I never used message commands
okay, np
sometimes you have to refresh dc
I will find what I have made that I should not lol
already done lol
oh
thank you both! that worked
how can I put the message_commands in the DM too ? I tried with the IntegrationType set but that's why my commands disappeared from the menu ๐ญ
context, not type
public_flags
It returns a discord.PublicUserFlags instance
*object
an object is an instance of a class
Womp womp
thiz
instances are pointers, not objects
that is not right for all i know and was ever taught
should i catch those with except (Forbidden, HTTPException)?
Is support for recurring subscriptions being worked on? I noticed 2.6.0 only supports one-time
Wdym, it support both
Oh, the patch notes said one-time and I haven't tried it out yet
you can do just httpexception, forbidden is a subclass
i can do selfbot with pycord?
good question ๐
If you want to get banned
and if i want to get banned?
This gotta be sarcasm right
idk you tell me
so it mean yes ? imo
I hope it is, or you're dumb as hell
needlessly rude
Many used self botting to scam people
Maybe with older version

There's an entire part of the docs talking bout that
where ?
Migrating to v2
thanks
When I have an on_auto_moderation_action_execution event and the AutoMod action has multiple actions, it causes things to run multiple times, how do I avoid this?
I guess compare the rule id and keep a small list of previously received events
and then ignore further events with the same rule id if it happens within like 1s or whatever
or you can use the message object for that
that's probably easier actually
Well it's time to make a temporary in memory database for only this
I made a list and use a tuple of rule_id and message_id, it ain't broken
I copied the code from another location in the code and changed it slighlty
yea
but that's not at all what an in memory db is lol
it kind of serves as a in memory db, except it has alzheimers as it forgets after 1 second
a list isn't an in memory db
H2 is an in memory db
:)
any idea to do that if someone use an autocomplete but the value that he pass is not inside the autocomplete, it does not trigger the command ?
handle it inside the command
yeah but how ?
how can i get autocomplet choice if you prefer
(if there is a easy method, else i will trigger the fonction)
my question is how to get that (if there is a built in thing)
else i will trigger the function and check
wdym lol
you already have that list saved somewhere
else, what are you autocompleting on
its a dynamic func
trying to do something kinda like so if u prefer
when running slash command how can I get the channel command was ran in?
thanks
is there an option for getting timestamp for when user was banned? i know there is joined_at.timestamp() is there a syntax for ban?
is it possible to catch all the errors from events (on_message, on_guild_channel_create etc.) globally like with the slash command error event or is there only the option to use try/except?
yes, on_error
discord.on_error
discord.Bot.on_error
discord.Client.on_error
discord.ui.View.on_error
discord.ui.Modal.on_error
discord.Cog.cog_command_error
discord.ext.commands.Bot.on_error
discord.ApplicationCommand.has_error_handler
discord.ext.commands.Group.has_error_handler
discord.ext.pages.Paginator.on_error
discord.on_application_command_error
discord.ext.commands.Command.has_error_handler
discord.Bot.on_application_command_error
discord.ext.commands.Bot.on_command_error
discord.ext.commands.HelpCommand.send_error_message
I see thank you
discord does not keep this info
I keep getting this error after testing my slash command that i'm trying to get a cooldown on.
Appreciate any help on this problem and thanks to anyone that does.
the error:
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: Scommands.test_error() takes 2 positional arguments but 3 were given
@discord.slash_command(
name="test",
description="Used for testing! :alien:",
guild_ids=ALLOWED_SERVER_IDS
)
@commands.cooldown(rate=1, per=5*60) # WIP
async def test(self, ctx: discord.ApplicationContext):
await ctx.respond("Test success! :muscle:")
@test.error
async def test_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.send("Command is on cooldown! :man_guard:")
else:
raise error
you're missing self
omg I'm so dumb, but you're not so thank you very much
Keep in mind to use ctx.respond and not ctx.send
I am having a heck of a time trying to create a cog that runs a task at 10 minute intervals, that sends text to a specific channel. I have some blocky ass code and thought that maybe using a cog would clean things up. Quite a few examples i am finding are pretty old...
In guide says : 'bridge commands do not currently support per-command error handling". It mentions Issue #1388 but in that issue it says that PR #1411 was made to close the issue. So, is it now possible to use the per command error in slash commands?
def check(member):
return (member.id == ctx.author.id) and (member.guild.id == ctx.guild.id)
member = await bot.wait_for('member_join', check=check)
is it right ?
try it and see
I'm just unsure on what it'd achieve
you're basically waiting for the command caller to rejoin the server
Feel like a moron asking this, but I can't find an actual answer anywhere. Is there a button type to copy text to the clipboard?
no
I want this so bad. I even looked to see if there was some way to open a link just to copy text but to no avail.
i'd say your best bet is open a modal with preset value
my embed has 3 fields but im getting an error saying it has more than 10 elements but I'm almost certain it doesn't unless im missing something, anyone have some insights here?
Show the traceback
Ignoring exception in command mma queue:
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\commands\core.py", line 138, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\commands\core.py", line 1078,
in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "c:\Users\User\Desktop\Test\cogs\mmq.py", line 265, in queue
await paginator.respond(ctx.interaction, ephemeral=False)
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\ext\pages\pagination.py", line 1197, in respond
msg = await interaction.response.send_message(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\interactions.py", line 908, in send_message
raise ValueError("embeds cannot exceed maximum of 10 elements")
ValueError: embeds cannot exceed maximum of 10 elements
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\bot.py", line 1137, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\commands\core.py", line 435, in invoke
await injected(ctx)
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\commands\core.py", line 138, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\commands\core.py", line 1486,
in _invoke
await command.invoke(ctx)
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\commands\core.py", line 435, in invoke
await injected(ctx)
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\commands\core.py", line 146, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: ValueError: embeds cannot exceed maximum of 10 elements
How are you defining your pages?
I use a for loop to make a embed with the fields I need for displaying the data, then, make a page with the embed and fields and add it to a list, python pagelist.append(Page(embeds=embed)) paginator = Paginator(pages=pagelist) await paginator.respond(ctx.interaction, ephemeral=False)
hey guys any quick idea on why my slash commands stop working when i log out? on windows
pinging the bot still works though
Try embeds=[embed]
You can also just pass a list of embeds to the paginator itself pages=pagelist, pagelist being a list of discord.Embeds
okay, thank you. So if I'm understanding correctly, if I pass multiple embeds it will treat each embed as a page?
Yep
You kinda don't need a Page unless you're adding more stuff than just an embed
hey guys, maybe you could help me.. when I access overwrites property within ctx.channel it returns empty dict..
did I miss something that may change within developer portal that I need to enable?
simple code example:
async def test(self, ctx: discord.ApplicationContext):
print(ctx.channel.overwrites)```
try fetching the channel
thanks, that works. but it worked before without the fetch, do you know if there is any particular reason for this change?
not really
it's like discord.Member.banner we need to fetch_user by Bot class
but no reason for using fetch to get a banner
๐ค
nah i'm stupid it use the discord api I forgot it
how long discord.ui.View.message expires? sometimes return discord.Message or None
does it have message_id attribute?
Pycord. When I was not using cogs, i was doing this..
await chan.send('my message')```
In my cog, I am trying:
```chan = discord.utils.get(self.bot.get_all_channels(), name='my-channel')
await chan.send('my message')```
But i get a `AttributeError: 'NoneType' object has no attribute 'send'`
the easy way is how to make the buttons work after restarting the bot?
or do I need to save the message to my database and edit it when the bot starts?
you can use persistent buttons
I'm sorry, I do not know what it is, that's why I'm asking, can you give me a link to the documentation or give me an example?
Here's the persistent example.
thx!
Np
How to disable a button?
button.disabled = True and edit the message with the updated view
await self.message.edit(view=self)
is it possible for me to implement the twitch API with my discord bot, so certain actions on a twitch channel can be done through a interaction through a discord bot?
or should I write a seperate program for that?
is it any good?
Just check the examples and read through docs for what you wanna implement
yeah the docs look pretty good, i'll have a try at implementing it.
It's also fully async so shouldn't cause any blocking
.tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
class bot(commands.Bot):
..
commands.Bot is if you want prefix command support, which was the standard before slash commands
I know that
like some guys use it for like get his prefix when he is edit by the database
idk how to say it but it's a thing like that
Indeed, commands.Bot comes with a function you can override for custom prefixes
It's explained in the docs
class bot(commands.Bot):
...
async def set_prefix(self):
pref= db.execute("...").fetchone()
if pref:
Bot.prefix = pref[0]
else:
Bot.prefix = "+"
please make your classses uppercase, and variables lowercase
you are like going directly against convention
like Bot ? or all characters need to be uppercase ?
in python it's standard for variables and functions to be lowercase, while class names start with a capital letter; e.g. ```py
some_var = True
class Bot(commands.Bot):
...```this ISN'T required by any means, people break conventions all the time, it's just what you normally see
class names are PascalCase, methods and variables are snakecase
my friend said it's for clean code
breaking conventions isn't clean code
you're free to use whatever casing you want, but if anything, its not "clean code"
your friend is blatantly wrong, but ultimately this is relatively unimportant; just do whatever style you prefer
(i.e. your friend prefers doing it that way, and that's perfectly fine)
it gets important if you wanna share your code
im not here to preach about what style to use
because i would've assumed that with Bot.prefix, you are addressing the bot class, not an object
Is it possible to use the following decorator for a command function in a slash command group that's in a cog?
@discord.default_permissions(manage_channels=True)
Like...
admin = discord.SlashCommandGroup("admin", "Admin commands")
@admin.command(name = "kick", description="Kicks member")
@discord.default_permissions(manage_channels=True)
async def kick(self, ctx):
# Do stuff
I ask because last time I tried this (like almost a year ago now), there were no errors, but the decorator was ignored and anyone could run the command. I'm just double checking if there have been any improvements to allow preventing (and hiding) commands in cogs to users who do not have permission to run them.
can't apply discord permissions to subcommands
Oh that's right, now I remember. But they can be applied to groups, right?
you have to pass it to the entire group py admin = discord.SlashCommandGroup("admin", "Admin commands", default_member_permissions=discord.Permissions(manage_channels=True))
Ahhhhh! That's what I was forgetting... Makes sense. Tyvm for the quick response โค๏ธ
you'll know if it's correct if you check settings > integrations and select the group
will have some message about permissions
Oh! Very cool! Didn't know about this!
mhm, admins can adjust command permissions
why did u not using has_permissions in commands class ?
has_permissions should not be used with slash commands
why sad?
it was made for prefix commands
naturally it doesnt meet what a slash command needs
Use this
keep in mind that this can be overwrite by the admin of each guild
That's more of a good feature imo
i guess they might be some case where u dont want the thing to be overwrite
...again, this is wrong. has_permissions is perfectly fine if you want full control of your permissions from the bot's end
while default_permissions is superior if you're fine with admins overriding it
i know
but i find the result very hacky-looking
it's the same implementation and same error handling as anything else
yet lacks the possibility to hide commands which is what most people actually want
i personally like to respond with a view button to a yt vid if someone fails a perm check
can't really do anything about that
It might be interesting to add default_permissions(force:bool) or something similar maybe... Just an idea
prefer to show each command too
i guess, but then it'd just fall back on has_permissions
force?
That would basically also apply has_permissions
Idk
Just an idea
that makes no sense lol
Yeah the more I say it the more I feel like it indeed doesn't
is this the correct way to get a user from their ID? it doesn't seem to be working for me.
player1 = await discord.Bot.fetch_user(queue[n][1])
queue[n][1] being the ID
never call the raw class from discord
you've initialized Bot in your main file as a variable, so you refer to that
if you're in a cog, this is typically self.bot
(also, make sure your id is an integer)
File "D:\GitHub\fractal-rhomb\fractalrhomb.py", line 148, in change_status_command
activity = discord.Activity(type=discord.ActivityType.custom, state=content, emoji=emoji)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\GitHub\fractal-rhomb\.venv\Lib\site-packages\discord\activity.py", line 250, in __init__
PartialEmoji.from_dict(emoji) if emoji is not None else None
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\GitHub\fractal-rhomb\.venv\Lib\site-packages\discord\partial_emoji.py", line 114, in from_dict
animated=data.get("animated", False),
^^^^^^^^
AttributeError: 'PartialEmoji' object has no attribute 'get'
```what
it says emoji is supposed to be a PartialEmoji, but gives an error when i give it one
this is a little silly, but you can fix by changing it to emoji=emoji.to_dict()
thanks
though it doesn't seem like you can even add an emoji to a custom status
eh... you should be able to...?
for customstatus, use the CustomActivity class instead
(though, reading through docs PRs, apparently emoji actually straight up isn't supported?)
I did start using that when i found out that it exists
the docs for discord.Activity don't mention it like they do for discord.Game and discord.Streaming
or if they do i didn't notice it
and yea, i "can" add an emoji
but it just doesn't do anything
uhh that canโt be right?
^
for that you would have to check for it
1 sec.
i need cooldown button
I know, 1 sec xd
ok
from discord.ext import commands
cd_mapping = commands.CooldownMapping.from_cooldown(1, 60, commands.BucketType.user)
bucket = cd_mapping.get_bucket(interaction.message)
retry_after: float = bucket.update_rate_limit()
@deft kestrel
thanks
How to create a command with a space like
/start here
Use groups
Your group would be called start
And the command here
Oh okay, thank you!
Here's the slash cog groups example.
async def snowflake(ctx : commands.Context, message : discord.Message): -> discord.Message -> discord.utils.snowflake_time ?
I mean discord.Message return an discord.utils.snowflake_time or no ?
what are you trying to do
how to respond to an interaction without sending any message? i use interaction.response.pong but interaction failed?
if it's a component, just defer
I'm not entirely sure what pong is for but it does not work for responding to normal interactions. You can also edit a message or send a ephemeral message
๐ญ hmmmm a guy here said all discord class are transform in parameter
so that's why I asked this question
well, kinda?
it depends on which
if you typehint an option as discord.Message, then it will use the MessageConverter to attempt to retrieve it
because discord doesn't natively support that
discord will natively provide ints, floats, users/members, channels, roles, and attachments, anything else the library will attempt to handle or just read as string
gotcha, thanks
When I give a role to someone, can I put a reason?
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 ...
the docs have it all
I just knew I was gonna catch flack for this
i mean you COULD do that but you're hurting yourself
for thingy in queue[n]:
players.append(await self.bot.fetch_user(thingy))
should work unless im missing smth
they're starting at 1 instead of 0, i guess?
oh yea
it's pulling from a database, and there is something else in col 1
then just offset n
well then skip the first ig
id just add a bool switch
or use range(1, 9) instead
firstcolumn = True
for thingy in queue[n]:
if firstcolumn:
firstcolumn = False
continue
players.append(await self.bot.fetch_user(thingy))
This is probably really ugly but it does the trick
how
i never use stuff like that
...you've never used for i in range?
nop
open the schools....
should I just save the @mention paramter directly to my database instead of pulling the user ID and then doing .mention?
I would have to save both
I see
oh no, shame on me, i dont know a single built in function
3373% faster love to see it
it's one of the first python concepts you'd ever learn 
not knowing for i in range is like not knowing how to walk
well how would it be used to skip the first index here
for i in range (1, 9) does exactly that
because it skips 0
no messing with bools or whatever
ah
very useful, used it many times for school projcets to go through csv's and such
bruh
see, i see it like this
my code is just so good that i never needed for i in range
toothy i'm revoking your helper priveledges
you sprinted ahead while abandoning the roots, for shame
mods, subject him to a month long codeacademy course
this guy just got demoted live
-w-
view.add_item(discord.ui.Button(label="Test Button, Does Nothing", row=1))``` how do i await an interaction response with this?
which part
there's a couple examples i'd refer to
these both show slightly different approaches to using and responding to buttons
are those related to ext.pages?
not particularly? but ext.pages does make use of views
Is there a better way to search for a message on the Discord server to make as few API requests as possible and thus not run the risk of running into a rate limit if I want to do this on many servers at the same time?
message = bot.get_message(message_id)
if message is None:
channel = bot.get_channel(channel_id)
if channel is None:
channel = await bot.fetch_channel(channel_id)
if channel is None:
raise discord.NotFound
message = await channel.fetch_message(message_id)
if message is None:
raise discord.NotFound
else:
message = await channel.fetch_message(message_id)
if message is None:
raise discord.NotFound```
your code has some issue in it
.tag partial-objects
Partial Objects
These can be used to make API calls when you have channel id and/or message id, and you don't want to rely on the cache to have their objects.
Methods which can be used on them are
Example Usage:
async def star_message(channel_id: int, message_id: int):
# Get Partial Messageable object
partial_channel = bot.get_partial_messageable(channel_id)
# Get Partial Message
partial_message = partial_channel.get_partial_message(message_id)
# Add a reaction
await partial_message.add_reaction(":star:")
for example:
channel = await bot.fetch_channel(channel_id)
if channel is None:
raise discord.NotFound
cant work since if fetch fail it trigger an error
That means if I can't find the channel and message via get_channel and get_message and then work with partial_channel and partial_message, will these objects be in the bot's cache the next time and can be found via get_channel and get_message?
you can directly work with partial
depending on what u want to do with the message object
The message is an embed that I would like to update.
However, since the whole thing happens on many servers at the same time, I currently always run into rate limits
so you can use partial
So I don't get any rate limits?
if i understood partial does not do api call
Then I can just simplify the whole thing without getting into rate limits?
partial_channel = bot.get_partial_messageable(channel_id)
partial_message = partial_channel.get_partial_message(message_id)
await partial_message.edit(embed=embed)```
i think so
Do I still get discord.NotFound errors if it cannot be found?
not in the get_partial_message ig because it does not do any api call
but in the edit thing yes
I have an error counter to reset the whole thing if there are too many errors on the server.
Will this continue to work without any problems?
try:
partial_channel = bot.get_partial_messageable(channel_id)
partial_message = partial_channel.get_partial_message(message_id)
await partial_message.edit(embed=embed)
except discord.NotFound:
handle_not_found_error(guild_id)
except discord.Forbidden as e:
handle_forbidden_error(guild_id, e)
except discord.errors.DiscordServerError as e:
# Log the error and handle the retry logic
await asyncio.sleep(10)
def handle_not_found_error(guild_id):
logger.warning(f"Message not found in guild {guild_id}")
error_count[guild_id] += 1
reset_if_necessary(guild_id)
def handle_forbidden_error(guild_id, e):
logger.warning(f"Missing access on guild {guild_id}: {e}")
error_count[guild_id] += 1
reset_if_necessary(guild_id)```
why do you have an error count for each guild ?
there is maybe a better way to handle that
than a try except for each thing
maybe using the event on_command_error if its inside a command
If the message was not found 3 times on the Guild, the Guild should be removed so that the Guild is no longer processed during the next run.
why the message would be found after ?
like if the first time it was notFound
why suddently it will not raise a notfound ?
That's a good question ๐
what you can maybe do is
Then I don't need a counter but throw the Guild out directly when I get NotFound for the first time ๐
partial_channel = bot.get_partial_messageable(channel_id)
partial_message = partial_channel.get_partial_message(message_id)
try:
await partial_message.edit(embed=embed)
except discord.NotFound:
remove from list
except Exception as e:
logger.warning(f"Error during ...
: {e}")
maybe something like so would be more convenient
Thank you!
can I make it so that a link in an embed triggers a slash command?
Hey there, i started to working on a feature in my bot and i thought about using the tasks extension although i have some questions. The feature should allow a user to start a monitor that sends a request every X seconds to an api endpoint till X parameter is true. With tasks how would i go about starting a task that is linked to a user?
you should be able to mention a command, yes
Hi, Why?
Ignoring exception in modal <cogs.dev.xenority.verify1 object at 0x7eff5c75c6a0>:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ui/modal.py", line 341, in dispatch
await value.callback(interaction)
File "/home/container/cogs/dev/xenority.py", line 135, in callback
channel = self.bot.get_channel(log_channel)
TypeError: Client.get_channel() missing 1 required positional argument: 'id'```'
log_channel = SERVER_SYSTEM["log_channel"]
print(f"Log: {log_channel}")
channel = self.bot.get_channel(log_channel)
try get_channel(id=log_channel)
Ignoring exception in modal <cogs.dev.xenority.verify1 object at 0x7fad7a574940>:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ui/modal.py", line 341, in dispatch
await value.callback(interaction)
File "/home/container/cogs/dev/xenority.py", line 135, in callback
channel = self.bot.get_channel(id=log_channel)
TypeError: Client.get_channel() got some positional-only arguments passed as keyword arguments: 'id'```
this is my codee
def __init__(self, bot: discord.Bot, *args, **kwargs) -> None:
self.bot = bot
super().__init__(*args, **kwargs)
global code
code = ""
zeichen = "QAYXSWEDCVFRTGBNHZMJUIKLOP1234567890"
long = int("10")
for _ in range(long):
code = code + secrets.choice(zeichen)
self.add_item(discord.ui.InputText(label=f"GEBE HIER DEN FOLGENDEN CODE EIN: {code}", placeholder=f"{code}"))
async def callback(self, interaction: discord.Interaction):
user = interaction.user
if self.children[0].value == code:
role = interaction.guild.get_role(SERVER_SYSTEM["verify_role_id"])
remove_role = interaction.guild.get_role(SERVER_SYSTEM["join_role_id"])
await user.add_roles(role)
await user.remove_roles(remove_role)
await interaction.response.send_message(f":tada: Du bist verifiziert!", ephemeral=True)
log_channel = SERVER_SYSTEM["log_channel"]
print(f"Log: {log_channel}")
channel = self.bot.get_channel(id=log_channel)
embed = discord.Embed(title="Verifizierung", description=f"{user.mention} hat sich Erfolgreich Verifiziert", color=int(get_config("colors")["green"], 16))
embed.timestamp = datetime.utcnow()
embed.set_footer(text=f"ID: {user.id} ")
await channel.send(embed=embed)
else:
await interaction.response.send_message(f":x: Du hast einen falschen Code eingegeben!", ephemeral=True)
log_channel = SERVER_SYSTEM["log_channel"]
print(f"Log: {log_channel}")
channel = self.bot.get_channel(id=log_channel)
embed = discord.Embed(title="Verifizierung", description=f"{user.mention} hat einen falschen Code eingegeben", color=int(get_config("colors")["red"], 16))
embed.add_field(name="Falscher Code / Code", value=f"{self.children[0].value}")
embed.add_field(name="Richtiger Code", value=f"{code}")
embed.timestamp = datetime.utcnow()
embed.set_footer(text=f"ID: {user.id} ")
await channel.send(embed=embed)
class RoleButton(discord.ui.Button):
def __init__(self):
super().__init__(
label="Verifiziere dich hier!", # Text auf dem Button!
style=discord.enums.ButtonStyle.blurple, # Button-Fabre!
custom_id="interaction:RoleButton",
emoji=":greentickincircle_xenority:"
)
async def callback(self, interaction: discord.Interaction):
verify = random.randint(1, 2)
user = interaction.user
role = interaction.guild.get_role(SERVER_SYSTEM["verify_role_id"])
if role is None:
return
if role not in user.roles:
modal = verify1(Bot, title="Xenority")
if verify == "1":
modal = verify1(Bot, title="Xenority")
if verify == "2":
...
await interaction.response.send_modal(modal)
else:
await interaction.response.send_message(f":x: Du bist bereits verifiziert!", ephemeral=True)
.install
1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.
Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
i only have one
aiofiles==24.1.0
aiohttp==3.9.5
aiomysql==0.2.0
aiosignal==1.3.1
annotated-types==0.7.0
anyio==4.4.0
asyncio==3.4.3
attrs==23.2.0
beautifulsoup4==4.12.3
better-ipc==2.0.3
certifi==2024.7.4
cffi==1.16.0
charset-normalizer==3.3.2
chat_exporter==2.8.0
click==8.1.7
colorama==0.4.6
contourpy==1.2.1
croniter==2.0.7
cycler==0.12.1
dnspython==2.6.1
email_validator==2.2.0
emoji==2.12.1
fastapi==0.111.1
fastapi-cli==0.0.4
feedparser==6.0.11
fonttools==4.53.1
frozenlist==1.4.1
grapheme==0.6.0
h11==0.14.0
httpcore==1.0.5
httptools==0.6.1
httpx==0.27.0
idna==3.7
Jinja2==3.1.4
kiwisolver==1.4.5
lxml==5.3.0
markdown-it-py==3.0.0
MarkupSafe==2.1.5
matplotlib==3.9.1
mdurl==0.1.2
multidict==6.0.5
NBT==1.5.1
numpy==2.0.1
orjson==3.10.6
packaging==24.1
pillow==10.4.0
py-cord==2.6.0
pycparser==2.22
pydantic==2.8.2
pydantic_core==2.20.1
Pygments==2.18.0
PyMySQL==1.1.1
PyNaCl==1.5.0
pyngrok==7.1.6
pyparsing==3.1.2
python-dateutil==2.9.0.post0
python-dotenv==1.0.1
python-multipart==0.0.9
pytube==15.0.0
pytz==2024.1
PyYAML==6.0.1
requests==2.32.3
rich==13.7.1
scrapetube==2.5.1
sgmllib3k==1.0.0
shellingham==1.5.4
six==1.16.0
sniffio==1.3.1
soupsieve==2.5
starlette==0.37.2
twitchAPI==4.2.1
typer==0.12.3
typing_extensions==4.12.2
tzdata==2024.1
tzlocal==5.2
urllib3==2.2.2
uvicorn==0.30.3
watchfiles==0.22.0
websockets==12.0
xmltodict==0.13.0
yarl==1.9.4
ytnoti==1.1.2```
then can you please reinstall py-cord?
also use a venv if you aren't doing so.
i use a pterodactyl container for htis and i do a reinstall
can you check your code is updated? This code should work.
Maybe add an additional print, another one, and see if when deployed it prints it as well or not.
what you mean by that?
add another print statement and see if it prints it in pterodactyl
Where should I do this? because it prints log
at the same palce where you print log_channel
Test 123
Ignoring exception in modal <cogs.dev.xenority.verify1 object at 0x7fcac4a76380>:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ui/modal.py", line 341, in dispatch
await value.callback(interaction)
File "/home/container/cogs/dev/xenority.py", line 138, in callback
channel = self.bot.get_channel(id=log_channel)
TypeError: Client.get_channel() got some positional-only arguments passed as keyword arguments: 'id'```
print(f"Log: {log_channel}")
print("Test 123")
channel = self.bot.get_channel(id=log_channel)```
No that's not the issue
very clearly is right now
Here
i dont think bot is initialised properly then
show more of your code
especially where bot is assigned
this is the section
well first of all remove the id=, its wrong
and then, show where you call the modal in your code
def __init__(self):
super().__init__(
label="Verifiziere dich hier!", # Text auf dem Button!
style=discord.enums.ButtonStyle.blurple, # Button-Fabre!
custom_id="interaction:RoleButton",
emoji=":greentickincircle_xenority:"
)
async def callback(self, interaction: discord.Interaction):
verify = random.randint(1, 2)
user = interaction.user
role = interaction.guild.get_role(SERVER_SYSTEM["verify_role_id"])
if role is None:
return
if role not in user.roles:
modal = verify1(Bot, title="Xenority")
if verify == "1":
modal = verify1(Bot, title="Xenority")
if verify == "2":
modal = verify2(Bot, title="Xenority")
await interaction.response.send_modal(modal)
else:
await interaction.response.send_message(f":x: Du bist bereits verifiziert!", ephemeral=True)
The Bot object is a import
from bot import Bot
the bot.py
import datetime
import asyncio
import os
from discord.ext import commands
from discord import InteractionContextType, IntegrationType
from colorama import *
from utils.funcs import get_database_tables
class Bot(commands.Bot):
def __init__(self):
intents = discord.Intents.all()
command_prefix = commands.when_mentioned_or("-")
default_command_context={InteractionContextType.guild}
default_command_integration_types={IntegrationType.guild_install}
super().__init__(command_prefix=command_prefix, intents=intents, default_command_context=default_command_context, default_command_integration_types=default_command_integration_types)
async def on_ready(self):
total_members = sum([len(guild.members) for guild in self.guilds])
average_members = total_members / len(self.guilds)
bot_infos = f"| Bot Name --> {self.user} (ID: {self.user.id})"
bot_commands = f"| Commands --> {len(self.application_commands)}"
bot_stats = f"| Guilds --> {len(self.guilds)} mit {total_members} Usern, Durchschnitt: {average_members:.2f}"
length_bot_infos = len(f"| Bot Name --> {self.user} (ID: {self.user.id})")
length_bot_commands = len(f"| Commands --> {len(self.application_commands)}")
length_bot_stats = len(f"| Guilds --> {len(self.guilds)} mit {total_members} Usern, Durchschnitt: {average_members:.2f}")
max_string = max(length_bot_infos, length_bot_commands, length_bot_stats)
line = "|" + "=" * max_string + "|"
print(Fore.BLUE + line)
print(f"| {self.user} ist Online |")
print(line)
print("| ____ _ _ |")
print("| / ___| ___ _ __ ___ ___ | |_ ___ __| | |")
print("| | | / _ \\ | '_ \\ / _ \\ / __| | __| / _ \\ / _` | |")
print("| | |___ | (_) | | | | | | __/ | (__ | |_ | __/ | (_| | |")
print("| \\____| \\___/ |_| |_| \\___| \\___| \\__| \\___| \\__,_| |")
print("| |")
print(line)
print(bot_infos)
print(bot_commands)
print(bot_stats)
print(line)
database_tables = len(get_database_tables())
print(f"| {database_tables} Databases Loaded")
print(line)
for cog in self.cogs:
print(f"| --> {cog}")
print(line + Style.RESET_ALL)```
