#Basic Pycord Help (Quick Questions Only)
1 messages Β· Page 60 of 1
Looks right
it sounds a little complex and not as performance efficient
like it will only have over 0.2 seconds difference or something
if things turn out to well be performant
then il keep it
so even when i have await ctx.response.defer() I get Unknown interaction
and it says application didnt respond is there a way to fix this or is it problem with host
the node is located in germany
show code?
btw what happens if people spam it
will it keep ip with the spam
or nah?
Not really. Getting data from local db should be easily less than 25ms, while getting reactions from discord could be as high as 600-700ms
hmm ok
Yea you can try and implement, pretty sure it would have a noticeable speed difference
it works hwen i host on my pc fine but the client.ws.latency is like 108ms is that too long for even defering to work
heres main part of code
async def play(ctx: discord.ApplicationContext, level="medium"):
await ctx.response.defer()
embed = discord.Embed(title="Send a 5 letter word to guess", color=0x009afc)
if level == "easy":
word = random.choice(easy_words)
embed.description = "Easy mode"
amount = 1
elif level == "medium":
embed.description = "Medium mode"
amount = 2
word = random.choice(easy_words)
else:
embed.description = "Hard mode"
amount = 5
word = random.choice(hard_words)
game = wordlelib.Wordle(word = word, real_words = False)
print(ctx.user.name, word)
message = await ctx.followup.send(f"<@{ctx.user.id}>", embed=embed)```
them functions should be too time consuming
Do you have multiple instances running?
i dont see any ill reset token just incase
reset token same issue
112 ms bot.ws.latency
do other commands work?
do you have an on_interaction event?
Can you reproduce this error with a basic bot (on ready event and only 1 Slash cmd)? On same bot token and different bots token
this bot i very simple on its own 2 slash commands
ill comment out everything and just respond and see what it does
Can you put slash commands in a subclass?
yes
Oh btw do they take longer than 15 mins?
nope
Ah google is misleading...
What decorator do i need to use?
the error comes about 3 seconds after command
but it takes too long to defer it or somthing like that
Hmm
Subclassing is a popular way of creating Discord Bots. Explore how you can create a Discord bot by subclassing.
Wow that's weird. Can you confirm you are on py-cord 2.4.0 ?
"contact your are"
My mobile keyboard is borked 
Did you by any chance mean subclass Slash command?
I've got something like this
class MyBot(discord.Bot):
@discord.application_command(guild_ids=[guild_id])
async def test(ctx: discord.ApplicationContext):
print('test worked!')
The command does not register?
Uhh, are you trying to add the commands inside the bot class?
Yes...
nope
Try @self.slash_command, but ig you would need to do this inside the init
Not sure if that could work tho
this wouldn't work because it is not added to the bot
π
Yeah, that's not something you can do
You should use cogs to add them or the functional interface.
Okay, thank you!
Functional interphase π (what even is that)
Putting everything in the same class isn't really a good design choice either imo
@bot.slash_command()
async def skull(ctx):
await ctx.respond(":skull:")
yes
im checking responding then editing
and see if it works
How do you send colored code blocks?
```lang
code
```
is there a way to override the default commands.Cog.listener() error handling so i can make it not be printed and instead sent to a channel?
code your own
i moved to another node and it works apparently the hosting just sucks
then i need to figure out where in the code the errors are printed do you know where
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/cog.py at master Β· Pycord-Development/pycord
discord/cog.py lines 380 to 423
@classmethod
def listener(cls, name: str = MISSING) -> Callable[[FuncT], FuncT]:
"""A decorator that marks a function as a listener.
This is the cog equivalent of :meth:`β.Bot.listen`β.
Parameters
----------
name: :class:`βstr`β
The name of the event being listened to. If not provided, it
defaults to the function's name.
Raises
------
TypeError
The function is not a coroutine function or a string was not passed as
the name.
"""
if name is not MISSING and not isinstance(name, str):
raise TypeError(
"Cog.listener expected str but received"
f" {name.__class__.__name__!r} instead."
)
def decorator(func: FuncT) -> FuncT:
actual = func
if isinstance(actual, staticmethod):
actual = actual.__func__
if not inspect.iscoroutinefunction(actual):
raise TypeError("Listener function must be a coroutine function.")
actual.__cog_listener__ = True
to_assign = name or actual.__name__
try:
actual.__cog_listener_names__.append(to_assign)
except AttributeError:
actual.__cog_listener_names__ = [to_assign]
# we have to return `βfunc`β instead of `βactual`β because
# we need the type to be `βstaticmethod`β for the metaclass
# to pick it up but the metaclass unfurls the function and
# thus the assignments need to be on the actual function
return func
return decorator```
i mean just normal exceptions
(i forgot to call it lol)
there is a on_error event that is dispatched for errors arising from event handlers, but using it isnt very easy
yeah i just found it
i see why it would be difficult to use
i see how you could make this work better by just adding an as error after the except Exception and passing that error into on_error
wait i can just override that
lel
yea lol. no need to rely on on_error event then

AttributeError: 'Bot' object has no attribute 'bridge_command'. Did you mean: 'message_command'?
does anyone know why im getting this error
Show your code
?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)
can you show the pip list
hey after debugging a slash command i got ,
discord.errors.HTTPException: 400 Bad Request (error code: 30034): Max number of daily application command creates has been reached (200)```
eventhough i have in the command guild_ids=[my_guild_id], why did i get rate limited? and is there a way to continue implementing my command without being rate limited in the future?
Make sure you only have 1 bot running with that token at the same time
otherwise they will fight over what gets registered
oh, i have it hosted and at the same time i am running a local instance
You should use a different bot for development testing, otherwise you'll run into all sorts of issues and conflicts.
yea i was just about to ask that, if i should make another bot for local testing
Hello everyone, i've got some stupid error:
File "/Volumes/Danya disk/Coding/Py-cord/HFD-zebra/venv/lib/python3.10/site-packages/discord/cog.py", line 774, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/Volumes/Danya disk/Coding/Py-cord/HFD-zebra/cogs/test.py", line 4, in <module>
class Test(hfd.Cog, command_attrs={"hidden": True}):
File "/Volumes/Danya disk/Coding/Py-cord/HFD-zebra/venv/lib/python3.10/site-packages/discord/cog.py", line 233, in __new__
new_cls.__cog_commands__ = tuple(c._update_copy(cmd_attrs) if not hasattr(c, "add_to") else c for c in new_cls.__cog_commands__) # type: ignore
File "/Volumes/Danya disk/Coding/Py-cord/HFD-zebra/venv/lib/python3.10/site-packages/discord/cog.py", line 233, in <genexpr>
new_cls.__cog_commands__ = tuple(c._update_copy(cmd_attrs) if not hasattr(c, "add_to") else c for c in new_cls.__cog_commands__) # type: ignore
File "/Volumes/Danya disk/Coding/Py-cord/HFD-zebra/venv/lib/python3.10/site-packages/discord/commands/core.py", line 1370, in _update_copy
copy = self.__class__(self.callback, **kw)
File "/Volumes/Danya disk/Coding/Py-cord/HFD-zebra/venv/lib/python3.10/site-packages/discord/commands/core.py", line 261, in callback
return self._callback
AttributeError: 'SlashCommandGroup' object has no attribute '_callback'
class Test(hfd.Cog, command_attrs={"hidden": True}):
def __init__(self, bot):
self.bot = bot
test_group = discord.SlashCommandGroup(name="test", description="Π§ΡΠΎ-ΡΠΎ ΡΠ΅ΡΡΠΈΡΡΡ", guild_only=True, guild_ids=[1004612600623005768])
@test_group.command()
async def say(self, ctx, text: discord.Option(str, description='ΠΠ²Π΅Π΄ΠΈΡΠ΅ ΡΠ΅ΠΊΡΡ', required=True)):
"""message"""
#code here```
and i can't see any callbacks for `SlashCommandGroup`
and there are slash command groups in another cogs, but they work correctly
what are you trying to do with the cog? Is hfd = discord? Shouldn't command_attrs={"hidden": True} be a argument in the __init__
i've just put it there by mistake
And there is no test_group.callback or test_group._callback in your code
yes, and i don't understand why py-cord said about it
What is hfd?
another person solved it by removing command_attrs from the class
So, my problem was
class Tickets(Cog, command_attrs=dict(hidden=True)):can't havecommand_attrs, or at leastdict(hidden=True)
it must treat the group as a command. It might be a bug
ok question
i didn't use the reactions thing Om nom said
bc i didn't feel nesscarry
but how can i improve this line
it took 0.59s to update theme reactions
votes = [user.id async for user in msg.reactions[0].users()]
downvotes = [user.id async for user in msg.reactions[1].users()]
if theme_author_id in votes: votes.pop()
if theme_author_id in downvotes : downvotes.pop()
which is purely unacceptable
if i manage to make it take like almost 0 seconds
from 1.1 seconds it will go to 0.7
i was talking about py async def _run_event( self, coro: Callable[..., Coroutine[Any, Any, Any]], event_name: str, *args: Any, **kwargs: Any, ) -> None: try: await coro(*args, **kwargs) except asyncio.CancelledError: pass except Exception: try: await self.on_error(event_name, *args, **kwargs) except asyncio.CancelledError: pass in discord.Client btw
Don't use async for in a list comprehension 
Use it like a normal async for block of code
This is the same as using flatten
but i mean i need user id
and yeh i need for the program to be as time efficient as possible
idc if the code isn't too readable
but don't overdo it on readability
Yea so, Iterate and break if user.id is equals msg author id. At least that's what I would do for this code ^
this doesn't make sense
what happens if the structure is this
User
The Target
User
User
it won't take account the other 2 last users
and its not the same thing as
User
User
User
The Target
Do you use the count of user reactions?
well i don't and the reason being is why
I understood you only check if msg.author is in list of reaction users
also theme_author_id is a ID
not to be confused with a actual author object
and is selected from the database
i think i got an idea
well i had it
but never thought it will really work
Oh yea make a pr
?
Well you can add it to the library. Would be cool.
That would make it on_error(event_name, error, *args, **kwargs) right
i knew it this was pathetic
author = bot.get_user(int(theme_author_id[0]))
if author is None: author = await most_used["guild"].fetch_member(int(theme_author_id[0]))
results = await asyncio.gather(msg.reactions[0].users().flatten(), msg.reactions[0].users().flatten(), return_exceptions = True)
if author in results[0]: results[0].remove(author)
if author in results[1]: results[1].remove(author)
highest is 0.72 seconds while lowest is 0.55 seconds
What exactly are you trying to do?
i wanna get all users, compare if one of the users is in the reaction, then count based on condition
if the user reacted then -1, if not it remains as it is
Hi, Ive got a command in mind however im not sure on what to search in the pycord docs, The command is supposed to repeat what you say in the message into a channel you must select. Im just not sure about how to add the channel and get the bot to notice what i want it to repeat and repeat it in that channel.
simplest thing in the world
u take a argument channel id
u look if the channel id is valid(if its string or int, if the channel exists itself)
oh wait, i forgot its much more simple
How does using a normal async for loop not make sense then
im confused rn
Alr so you wanna do smth like this
Is it in a cog?
async for user in reaction.users():
if user.id == author.id:
break
else:
return # returns if not broken
cog?
Here's the slash options example.
i don't think u understood what i am trying to do
π π
That example will help you get the channel. In the command. If you still are a bit confused take a look at the guide
Alr I'm heading to sleep now
.guide
Alr, Thanks
None type
π ty
- 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
You only need pycord. Pycord uses discord name
i fixed it now but ty anyway :p
i have this error now:m
File "/Users/emlynphoenix/clothing.py", line 1, in <module>
import discord
File "/opt/homebrew/lib/python3.11/site-packages/discord/__init__.py", line 22, in <module>
from ._version import *
File "/opt/homebrew/lib/python3.11/site-packages/discord/_version.py", line 30, in <module>
from importlib.metadata import PackageNotFoundError, version
File "/opt/homebrew/Cellar/[email protected]/3.11.2_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/metadata/__init__.py", line 17, in <module>
from . import _adapters, _meta
File "/opt/homebrew/Cellar/[email protected]/3.11.2_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/metadata/_adapters.py", line 3, in <module>
import email.message
File "/opt/homebrew/Cellar/[email protected]/3.11.2_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/email/message.py", line 15, in <module>
from email import utils
File "/opt/homebrew/Cellar/[email protected]/3.11.2_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/email/utils.py", line 28, in <module>
import random
File "/Users/emlynphoenix/random.py", line 6, in <module>
print(''.join(letters))
^^^^^^^^^^^^^^^^
TypeError: sequence item 0: expected str instance, int found```
i dont hvave a file called random.py
Hello, can't import pycord even though it shows up on pip show py-cord. I've tried reinstalling discord.py
You don't import pycord, you import discord
also remove discord.py because it'll cause naming problems
ok so its a straight up replacement
yes
would it break any existing code if i replace discord.py or is it just an extension
its a fork of discord.py, V3 will be more of its own thing
Nothing should break instantly, but do testing and minor changes may be needed
aight ty
from discord.ext import commands is gone, I'm assuming I'll have to replace it with the new ones?
@bot.user_command or slash commands
that should still exist
okay but idk how to update the documentation
i looked at the docs source and it looks like it autogenerates
?tag install
- 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
@cyan quail you contribute often, can you help?
docs for what specifically
the documentation is for the most part autogenerated, but in many cases you still need to update the original .rst to include the function
discord.Client
do you only use discord.Client?
i only am updating discord.Client
?
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - Comparing Pycord-Development:master...mariohero24:patch-1 Β· Pycord-Development/pycord
doesnt say anywhere
then add the docstring to the original method
oh i found it
in a different file
okay ive completed the checklist
Traceback (most recent call last):
File "C:\Users\Ghoul\documents\teammai\mai\mai.py", line 253, in cog_watcher_task
self.unload_extension(extension_name)
File "C:\Users\Ghoul\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\cog.py", line 1068, in unload_extension
self._remove_module_references(lib.__name__)
File "C:\Users\Ghoul\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\cog.py", line 738, in _remove_module_references
for event_list in self.extra_events.copy().values():
^^^^^^^^^^^^^^^^^
AttributeError: 'Mai' object has no attribute 'extra_events'
``` huh?
my automatic cog reloader spits this error out every time
1 of 1
You cannot really reload the cogs without a restart...
isn't that the point of cogs?
wtf ?
no... ##1907 broke it because no one tests their damn prs anymore
since when ? why?
what the fuck
^
how do you remove an entire variable and not check for any references
VS code has an Deeple extension?
that's github.dev
oh
yea
Is a fix PR'ed yet?
no, but i suspect you need to rename extra_events to _event_handlers
tbf it's only 2 lines but man it's impressive how that wasn't tested at all
I'm sure they tested the events tho
yeah but if you're removing a variable, maybe check that it isn't being referenced in two major files?
like every IDE even does that for you
vim
die
im not even sure how they got passed testing
CI doesn't have 100% test coverage
I mean just manual testing yourself
im pretty sure regular event registration was fine
yea it is
but both on_command_error and unload_cog would be broken
i think more people would have noticed if it wasnt
yea
or... 12 hours ago
its an easy fix
at least you noticed that fast, thanks
Quick Question
How do i use slash commands in Cogs?
In my Main file is just use bot.slash_command()
Bot being an commands.Bot()
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)
yea
Alright. How do i check if person running slash_command has a certain permission?
Wasnt that like discord.has_permission or something?
Ah alright.
Thanks alot. That is exactly what i meant.
Btw when using slash commands. You have discord.Member right as a type for context. But is there also one for just any discord user even if they have never joined?
joined the guild*
discord.Member is a misnomer. In reality, it can just be any user.
So could you just enter id or something?
Or just name and discrminator
Would that work as that input type?
you can <@id>, too
the raw ID works in discord input types
but just name#discrim won't work if the bot doesn't know the user
Is it possible to pass something other than just the bot object to a cog.
For example a database connection?
So i could use it in the cog.
?tag botvar
Need to keep track of a variable between functions? No problem!
β οΈ Careful what you name it though, else you might overwrite something β οΈ
Just add it to your commands.Bot or discord.Client instance like so:
bot = commands.Bot(...)
bot.my_variable = 0
async def foo():
bot.my_variable += 1
# In a cog
@commands.command()
async def counter(self,ctx):
await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))
This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance
your db can be a botvar
Perfect thx.
Docs say @command.has_any_role() accepts list as input but it seems like it doesn't?
It doesn't throw any errors but instead behaves like no roles were passed in
you have to Enter just the id or name
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...
Yeah, but I'd like to have a variable with a list of roles. I guess unpacking it will work.
Yea if you update the python function, and the docstring, the docs will be updated too
okay
hi, how can i disable buttons in a view after they have been used?
actually not when they have been used, but upon some other specific trigger
view.disable_all_items
Followed by msg.edit(view=view)
(there are multiple ways to do this)
let me explain a bit more detailed of what the issue is
so i want to get a list of users discluding only one user. All of the rest shall be in the list no matter on their position. Then i want to get the count of them and i do this process for 2 reactions
Understandable?
ok im in to very good stuff
class CustomThread (threading.Thread) :
def __init__ ( self, msg_reactions, theme_author_id) :
super().__init__()
threading.Thread.__init__ ( self )
self.msg_reactions = asyncio.run(msg_reactions.users().flatten())
self.theme_author_id = theme_author_id
self.value = None
def run (self) :
user_list = [user.id for user in msg_reactions if user.id != self.theme_author_id]
self.value = len(user_list)
but i need to run async task thing
into the thread and lets say i get errors when trying
RuntimeError: asyncio.run() cannot be called from a running event loop
so how do i run it?
as well as RuntimeWarning: coroutine '_AsyncIterator.flatten' was never awaited
Why are you using threading?
bc i saw some improvement
while testing
and coming up with random ideas
that might have worked on the long run
should i do this in the button callback?
it says that message isn't defined
like i kind saw 0.01 seconds the operation doing instead of β 0.6 seconds
although it didn't really do it
i believe its capable of speeding things up
Try interaction.edit_original_response
You need to use asyncio.run_coroutine_threadsafe
hmmm ok
If threading consistently gives you better performance than asyncio then you are doing asyncio wrong
Because asyncio is just programmer controlled threading rather than system randomised threading
am i doing it wrong here?
(in python at least)
view=self
ah
Check if the correct message is edited, else you might need to use interaction.message.edit(view=self)
actually this one sounds more proofed
requires loop
um how do i type it exactly
Pass bot.loop to the thread
And pass this loop to the function
And wtf is threading.Thread.__init__
super().__init__ already does that
works perfectly, thank you
now says
Replace this expression with an iterable object.
in
result = asyncio.run_coroutine_threadsafe(self.msg_reactions.users().flatten(), loop = self.loop)
user_list = [user.id for user in result if user.id != self.theme_author_id]
Well discord prefers interaction.edit_original_response iirc. Not sure
Uhh full error?
it was editing the wrong message
the IDE displays this as a wanring
so i tried the other one
Ah yea i thought so
but here since i run
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Interaction.message.edit is good too
RuntimeWarning: coroutine '_AsyncIterator.flatten' was never awaited
Hm
in this
class CustomThread (threading.Thread) :
def __init__ ( self, msg_reactions, theme_author_id, loop) :
super().__init__()
self.msg_reactions = msg_reactions.users().flatten()
self.theme_author_id = theme_author_id
self.loop = loop
self.value = None
def run (self) :
result = asyncio.run_coroutine_threadsafe(self.msg_reactions.users().flatten(), loop = self.loop)
user_list = [user.id for user in result if user.id != self.theme_author_id]
self.value = len(user_list)
oh wait
it returns now RuntimeError: There is no current event loop in thread 'Thread-6'.
same with thread-5
aka the 2 threads for the 2 reactions
||you really spent hours trying to implement this but wouldn't implement a db based setup
||
yeh
i don't want to tbh
Idk how to solve your error lol, wait for someone else. It would be a great idea to create a post in #969574202413838426
imma ask chatgpt if it can come up with stuff
Try to include as much info as possible. Including your previous attempts
yes
yup impossible to do threading
with asyncio
time to read docs of asyncio
if nothing works
then docs will work
wasn't it asyncio.to_thread?
im kinda lazy to implement it now
like im really losing hope
ok yknow what im opening a help form]
hi, can anyone guide me for str type Options in slash commands?
asyncio.to_thread allows you to run blocking functions asynchronously
asyncio.run_coroutine_threadsafe allows you to run coroutines from a different thread
@discord.slash_command(name="rps", description="Play rock-paper-scissors against the bot!")
async def rps(self, ctx, choice:Option(str, description = 'Choose your weapon', choices)):
this was my max intuition... choices is a list
choices requires a list
choices = [{"name": "Rock", "value": "rock"},
{"name": "Paper", "value": "paper"},
{"name": "Scissors", "value": "scissors"}]
choices = [{"name": "Rock", "value": "rock"},
{"name": "Paper", "value": "paper"},
{"name": "Scissors", "value": "scissors"}]
@discord.slash_command(name="rps", description="Play rock-paper-scissors against the bot!")
async def rps(self, ctx, choice:Option(str, description = 'Choose your weapon', choices)):
# Define the possible outcomes of the game
outcomes = {"rock": {"win": "scissors", "lose": "paper"},
"paper": {"win": "rock", "lose": "scissors"},
"scissors": {"win": "paper", "lose": "rock"}}
# Generate a random choice for the bot
bot_choice = random.choice(["rock", "paper", "scissors"])
# Determine the winner of the game
if choice == bot_choice:
result = "It's a tie!"
elif bot_choice == outcomes[choice]["win"]:
result = "You win!"
else:
result = "You lose!"
# Send a message with the result of the game
await ctx.send(f"You chose {choice}, I chose {bot_choice}. {result}")
the full code βοΈ
ok done made a thread
That's a list of dictionaries
You need a list of strings iirc
Or of optionchoice
ohh
How to make a modal callback work again after failing(did not satisfy a condition)? It seems not to be called again after an error in the same modal
A public bot seems to do this but I can't figure it out
How do you convert a discord.Permissions value into something readable that can be sent to the user to tell them which permissions are missing without manually mapping every permission to a name?
Wdym? Do you want to send a modal as a response to another modal?
Iterate over the permissions object and add to a string?
Any examples? Im failing to understand since the object has no attributes which arent numbers that I can see. I just end up with generator objects
Uhh iterating should give you a tuple of permission and value
Smth like
my_str = ""
for perm, value in permissions:
a += f"..."
.rtfm permissions
discord.Permissions
discord.Permissions.DEFAULT_VALUE
discord.Permissions.VALID_FLAGS
discord.Permissions.add_reactions
discord.Permissions.administrator
discord.Permissions.advanced
discord.Permissions.all
discord.Permissions.all_channel
discord.Permissions.attach_files
discord.Permissions.ban_members
discord.Permissions.change_nickname
discord.Permissions.connect
discord.Permissions.create_instant_invite
discord.Permissions.create_private_threads
discord.Permissions.create_public_threads
discord.Permissions.deafen_members
discord.Permissions.embed_links
discord.Permissions.external_emojis
discord.Permissions.external_stickers
discord.Permissions.general
perm should be the attribute name iirc
Hmm, i was trying to iterate over discord.Permissions, should it have been discord.permissions?
is it possible to hide user_commands for user which have not a specific role or permission?
I put a if statement to filter the input in a modal, and once the input didn't satisfy it, the callback method doesn't seem to be called again after that
(I checked it several times)
return didn't work either
Discord allows a minimum and maximum length if that is not met it will not submit the model. Other wise you have to do the checking and send a new modal.
What I did is if a value does not meet my criteria. It would set it to a defualt value and send a message saying
"Some values were set to defualt becouse there input was incorrect." Than offer the modal again
Hey is there anyway to do something like this?
message_name = await bot.wait_for('message' from profile_id)
Since anyones message gets read and saved, when i only want the author of the command messages to be saved
Does anybody here uses Tortoise Orm for his Bot?
- 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
import discord
ModuleNotFoundError: No module named 'discord'
You do not need git if you are installing the base version
you iterate over the object
i installed git
Did you also uninstall d.py?
yes
please show pip list
yes
how?
Same way that you installed pycord type python -m pip list
Ok, I'm relatively new to the whole database stuff, is there any place I could send you my snippets and you can tell me if I'm doing it completely wrong?
You could open your own thread :)
Or do you maybe have your bot on GitHub so I can have a look there?
i dont, but i can send you my models file
Didn't knew if an Thread about Tortoise would be appropriate on this server so i started here
But I can open one, for sure - thanks
Its fine, as long as it somehow relates to a discord bot we will help.
You somehow installed pycord V3 you want to use pycord V2.4 (latest)]
V3 is still in development
how?
i used to use replit
im now on vsc
python -m pip uninstall py-cord
python -m pip install -U py-cord
ooooh ok, I was just wondering how other bots could do it in the same modal
not quitting and generating another modal
Yup, as of now discord only supports length as a restriction of models. They offer a bit more like number and channel/user in slash commands
tysm man, its been a few years last time i programmed
im coming back to discord.py again tysm
Pycord is different than discord.py. But if you meant just bot dev in general: π
tysm, this worked too haha
π wait are you sending a modal as a direct response to another modal (without resending button) and it works?
As another warning discord does not allow you to respond to a modal with another modal. I think it is kinda dumb but nothing we can do. I have been waiting for a modal update for some months now.
What most people do is send a button that says click to continue.
Can i paste my code to pastebin or something like this?
strange
Post Limit is reached =D
?
the same modal class, but yes
any recommendations, i saw on some servers pastebin for example is banned
I can still create posts?
?tag paste
Character limit, I'm sorry
ahh
waa im gonna test this
I think that would error in runtime
ah lol
done btw - once again, I already appreciate the supportive community here
Traceback (most recent call last):
File "/opt/venv/lib/python3.10/site-packages/discord/client.py", line 377, in _run_event
await coro(*args, **kwargs)
File "/opt/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 162, in on_command_error
if self.extra_events.get("on_command_error", None):
AttributeError: 'AutoShardedBot' object has no attribute 'extra_events'
Ignoring exception in on_command_error
Traceback (most recent call last):
File "/opt/venv/lib/python3.10/site-packages/discord/client.py", line 377, in _run_event
await coro(*args, **kwargs)
File "/opt/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 162, in on_command_error
if self.extra_events.get("on_command_error", None):
AttributeError: 'AutoShardedBot' object has no attribute 'extra_events'``` Bot is crashing due to this error.
AutoShardedBot' object has no attribute 'extra_events
Oh gotcha.
how to add cooldown to a button
no library built in way to do it
you would need to handle it yourself
you could use CooldownMapping classes which the library uses internally for cmd cooldown, but it will be overkill for this
Something you could do depending on how long the cooldown is have a Time To Live Cache (TIL) and is the user is in the cache dont trigger the button code.
button_cooldowns = []
async def cooldown_remove(userid: int):
if userid in button_cooldowns:
await asyncio.sleep(10)
button_cooldowns.remove(userid)
class TestView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label='Test', style=discord.ButtonStyle.blurple, custom_id='persistent_view')
async def Test(self, button: discord.ui.Button, interaction: discord.Interaction):
if interaction.user.id in button_cooldowns:
return .......
else:
reply
button_cooldowns.add(interaction.user.id)
something like this should also work
π that is basically a TIL cache

Ok, one quick here - maybe somebody else knows this / had this before - I'm using Tortoise ORM and getting this Error
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: ConfigurationError: default_connection for the model <class 'mako.db.models.Guild'> cannot be None
Anybody knows how to fix?
do I have to necessarily make subclasses of button to use callback
I keep getting parameter errors when I use default Button and do like button1.callback = someMethod
this should work, but the function only takes interaction as the parameter
e.g. py button = discord.ui.Button(...) async def c(interaction): button.disabled = True await interaction.response.edit_message(...) button.callback = c
Is there like a discord.has_role()?
So i only need to import discord.
Since thats basicly the only library i use in cogs.
Yes but i meant like when defining a slash command
So whether a server has a certain role
Like discord.default_permissions() for permissions.
No just if a user has a certain role with a certain id.
well then
this is correct
just put Interaction as a parm in the command
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/button_roles.py at e44164180158f62fac99460bb3cf782d86ec23c7 Β· Pycord-Development/pycord
Alrighty
Hi, Im still having problems with a command im trying to make, I cant figure out how i would make my bot send a message in a channel i select, Ive managed to get the bot to let you select a channel and the bot can identify that in a message, But idk how i would make it send the message in a different channel
# say command
@bot.slash_command(description='Say something')
@commands.has_guild_permissions(kick_members=True)
@option(
"Channel",
Union[discord.TextChannel]
)
async def say(
ctx: discord.ApplicationContext,
channel: Union[discord.TextChannel],
message
):
await ctx.respond(f'{channel.mention} test')
So far this is my command. I also need help making the bot copy the message part of the command and repeating that in the selected channel
for 1 remove the Union[ ] part since it's not valid syntax anymore
that aside, use channel.send
The union seems to be working fine for me right now. and where would i put the channel.send part? Just replace it for the ctx.send?
pretty much
note in slash commands you HAVE to have at least one ctx.respond
so you both need to respond to the command and then send to the channel
So i could have it like
await ctx.respond(':+1:')
await channel.send('test')
something like that
Hello guys, how can I make a select option default, if a user has a specific role?
mhm
also note that you can make the respond ephemeral=True so only you can see it
Ok.
check user.get_role(id) and if it exists, set default?
but how can i set it default? (In a subclassed view)
Ok, So now 1/2 of the command works, How would i get the bot to send the message i say in the message part of the command?
pass the member object through to the subclass and perform the check inside __init__
or just do the check beforehand and pass the result through
well message is just a variable so...
What would i use to make it into an actual message? Something like ```message=message.content
but how can i get it there?
no, your message option is a string so you don't have to do anything
add another argument to def __init__
Oh ok, So i would just add it as f'{message}'
mhm
e.g. in the dropdown example, they add a bot argument so they can use it within the class
https://github.com/Pycord-Development/pycord/blob/master/examples/views/dropdown.py
like that:
def __init__(self, guild):
super().__init__(timeout=None)
member = guild.members
news_role = discord.utils.get(guild.roles, id=int(internal_config['news_role_id']))
changelog_role = discord.utils.get(guild.roles, id=int(internal_config['changelog_role_id']))
status_role = discord.utils.get(guild.roles, id=int(internal_config['status_role_id']))
giveaway_role = discord.utils.get(guild.roles, id=int(internal_config['giveaway_role_id']))
@discord.ui.select(
custom_id="view_14",
placeholder="Choose your notifications!",
min_values=0,
max_values=4,
options=[
discord.SelectOption(
label="News",
description="Get news about the server!",
if news_role in member.roles:
default = True
),```
nearly
for 1, guild.members is a list of every member
instead, i recommend doing def __init__(self, member): to pass the member in, then you can do guild = member.guild
second, in decorators you can't access the original variables so you need a different approach
because that select menu is defined before __init__ runs, you can do some sneaky stuff inside __init__ like accessing self.function_name.options py def __init__(self, member): ... if news_role in member.roles: self.select_callback.options[0].default = True
if you need to do several of these checks, consider making it another function and then calling it inside __init__
does select_callback need to be the name of my callback?
well that's just whatever you called it
ok
but how can I get the member now?
here is my persistinent view, the guild getter needs to be there
self.bot.add_view(RoleView(self.bot.get_guild(int(config['guild_id']))))```
well, do you already know the member id?
it should be for every member on the guild
ah your idea here might not work then
ah
are you trying to use default so every member would see their existing roles on the selector?
yes
default is attached to the select so it's global to all clients
unless you create a new select every time, every member will see the same default
ah, but is there any way to pre select it for every member specific?
well not really
ok
if this is a single persistent view (e.g. a role selection channel) then they'll all see the same thing until they make their selection
and regardless, the selection will reset back to the default when they refresh
Is there any other way to interact with databases than using cursor.execute?
It seems kind of annoying to me, is it possible to have like subclasses for tables?
You might be looking for ORMs like Tortoise ORM
Thank you so much!
Np lol
Just so yk, they need a bit of basic learning before you can use them
Like a high walled garden
I am trying to add a emoji to the button label of the persistant role example of pycord
ThatΒ΄s my code
ThatΒ΄s the error message.
Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\xxx\Python\Python310\lib\site-packages\discord\client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "C:\xxx\Python310\WiP\cogs\buttons.py", line 387, in on_ready
view.add_item(RoleButton(emoji_id, role))
File "C:\xxx\Python310\WiP\cogs\buttons.py", line 308, in __init__
label=f"{emoji} {role.name}",
AttributeError: 'int' object has no attribute 'name'
I understandt that the role.name does not match as integer. but i donΒ΄t know how to change it
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
you need a role object. you can get the role object using guild.get_role
I did this with
for emoji_id, role_id in role_ids.items():
role = ctx.guild.get_role(role_id)
view.add_item(RoleButton(emoji_id, role))
hmm
should be role.name, no?
your role parameter is before emoji parameter
in the init

you passed them the other way round while creating the button
also
*** @ Line 15 ***
- def __init__(self, role: discord.Role, emoji=discord.Emoji):
+ def __init__(self, role: discord.Role, emoji: discord.Emoji):
on line 15
nice use of diff lol
had to google the syntax
hmmm
Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\xxx\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "C:\xxx\Python310\WiP\cogs\buttons.py", line 387, in on_ready
view.add_item(RoleButton(role, emoji_id))
File "C:\xxx\Python310\WiP\cogs\buttons.py", line 308, in __init__
label=f"{role.name} {emoji}",
AttributeError: 'NoneType' object has no attribute 'name'
the role ID could be wrong
class RoleButton(discord.ui.Button):
def __init__(self, role: discord.Role, emoji: discord.Emoji):
"""A button for one role. `custom_id` is needed for persistent views."""
super().__init__(
label=f"{role.name} {emoji}",
style=discord.ButtonStyle.primary,
custom_id=str(role.id),
)
yes
it is wrong, because its the emoji id π
π
i change my dict π
looks very well
but there is one problem π
first is the role, second is a emoji id or a emoji itself. So now there is the emoji or the id
looks funny π
fetch/get the emoji too I suppose
ig use bot.get_emoji
why not use the emoji parameter of the button?
it accepts an emoji string
good question π
iΒ΄ll give it a try
If I defined my bot this way, can I use a prefix command instead of a slash command?
bot = discord.Bot(
intents=intents,
debug_guilds=None,
status = status,
activity = activity
)```
with a bridge.Bot you can use both
?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)
bridge.bot is only useful if you want a single command to be both, app cmd and prefix cmd
I want to use some commands as slashcommand and some as prefixcommand. But no command should be both.
yea command.Bot is the one you want
Okay thanks!
Hey guys just a quick question concerning best practices / performances:
When working with databases, is it recommended to do what I do in this method (i.e creating a connection each time the method is called and closing it at the end), or should I have only 1 connection opened when the bot boots up (but in this case idk where to "store" this connection object)
Thanks if someone takes the time to answer π
you would use a context manager for open/closing
Context manager ?
The with ... as ... syntax ?
yes
Ok thanks a lot ! So my approach is the good one then ? (i.e each time the method is called, I do it)
(and maybe stupid question: does context manager work with coroutines ?)
async with?
async with await database.init_bd() as conn: Raises: RuntimeError: threads can only be started once (and without the await it's not happy either)
pardon, I don't use sqlite or any sql lib.
and with await database.init_bd() as conn: raises: AttributeError: __enter__
but shouldn't it just be
async with database.init_bd() as conn:
```?
No problem thanks for taking the time to answer, I think I know what's the problem:
It's because i use the open method in database.init_bd() (so it complains about starting twice)
k
hmmm command is not updated
@discord.commands.option(name = "skill", description="Pick a Skill You Are Good At", choices = list(roles.keys()))
@bot.command(name="skill_control", description="Add Or Remove Skill Based On If You Have It Or Not")
async def _skill_control(ctx: discord.ApplicationContext, skill: str):
roles is a dict
the problem is the argument skill doesn't display the options nor the description
the option should follow the command decorator, not before it
How can I access the extra button to add a function there?
@commands.command(name="showspot", help="Zeigt alle Spots an")
async def page(self, ctx):
SPOTS_PER_PAGE = 6
data = await dab.get_all_spots()
pages = []
.
.
.
embed.add_field(name=name, value=fish_text + spot_text, inline=False)
pages.append(embed)
# Erstelle den Paginator und fΓΌge den neuen Button hinzu
paginator = Paginator(pages=pages, timeout=None)
paginator.add_button(PaginatorButton("Spotdetails abrufen", style=discord.ButtonStyle.gray, row=1, custom_id="spotdetails"))
await paginator.send(ctx)```
Subclass the button instead?...
Where can i find a basic format for a embed? When i searched it on the pycord docs it went on about something instead of the embed.
embed = discord.Embed()?
did you send it with embed=embed?
Ive not tried it yet lol. Im not sure how to make one yet, The docs are confusing me.
Can I call the class like this?
I always get the error "SpotDetails object has no attribute 'style'".
paginator.add_button(SpotDetails(self.bot))
class SpotDetails(discord.ui.View):
def __init__(self, bot):
super().__init__(timeout=None)
self.bot = bot
@discord.ui.button(label='Spotdetails abrufen', style=discord.ButtonStyle.gray, custom_id="spotdetails", row=1)
async def spotdetails(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message("Test")```
I'm on the fence right now and don't know what solution you want to push me towards π¬
paginator.add_button(SpotDetails(self.bot))
class SpotDetails(discord.ui.Button):
def __init__(self, bot):
super().__init__(label="Spotdetails abrufen", style=discord.ButtonStyle.gray, custom_id="spotdetails", row=1)
self.bot = bot
async def callback(self, interaction: discord.Interaction):
await interaction.response.send_message("Test")```
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'SpotDetails' object has no attribute 'loop_label'
π€ π
Hello, where do I get the code that is placed at the end of the codes, press Enter to close the tool
What
No idea
You need to make a pagnater button. just a simple fix plus a few extra kwargs
Can you explain further? Show an image of what you want? Show what code you have currently?
How do I do that with the button_type ?
Because it is an extra button and has nothing to do with the Navigarion of the Paginator?
Ah I see, you issue is you are using add_button this only add pagnater buttons. Use the normal subclass of button with add_item
Do you mean like this?
paginator.add_item(SpotDetails(self.bot))
class SpotDetails(discord.ui.Button):
def __init__(self, bot):
super().__init__(label="Spotdetails abrufen", style=discord.ButtonStyle.gray, custom_id="spotdetails", row=1)
self.bot = bot
async def callback(self, interaction):
await interaction.response.send_message("Test")```
I think so, thb I have never used paginator. But thats how it looks like it would be done by the docs
So I don't get an error but the button is also not displayed -.-
how to send message in a specific channel
.rtfm TextChannel.send
thanks π
Ah here is the solution βπ»
view = discord.ui.View(SpotDetails(self.bot),)
paginator = Paginator(pages=pages, timeout=None, custom_view=view)```
Yo ice wolf, may you have a quick look into my orm thread - ive tried to run my bot in vscode instead of pycharm and its failing - do you know why? I cant really get behind the error message
Ive just literally opened my project folder in vsc instead of pycharm and get this error
Same btw when i try to manually run main.py in terminal
are there any known bugs for
await interaction.guild.create_tect_channel()
it works fine in my test server but returns no id in the main server where its going to be running
Ignoring exception in view <MedbayWelcomPageButtons timeout=None children=3> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='NFFC' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "c:\Users\philc\Desktop\Artemis-2.0\bot\src\cogs\medbayV2.py", line 109, in nffc_callback
nffcticket = await guild.create_text_channel(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\guild.py", line 1261, in create_text_channel
data = await self._create_channel(
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\guild.py", line 1142, in _create_channel
"id": target.id,
^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'id'
nffcticket = await guild.create_text_channel(
name=f'NFFC-{interaction.user.name}',
category=NFFC_category,
overwrites=overwrites
)
await nffcticket.send(embed=embed, view=MedbaySubmitButtons())
await interaction.response.send_message(f"Your ticket has been created.\n<#{nffcticket.id}>", ephemeral=True)
class AddJob(Modal):
def __init__(self, title, bot: discord.Bot, ctx: discord.ApplicationContext):
super().__init__(title=title)
self.ctx=ctx
self.bot=bot
self.add_item(
InputText(
label='Job title and short intro*',
placeholder="Frontend engineer at Sphinx.co",
required=True,
max_length=80,
custom_id='about',
style=discord.InputTextStyle.short,
))
self.add_item(
InputText(
label='Description about the job*',
placeholder='About...',
required=True,
max_length=1000,
custom_id='description',
style=discord.InputTextStyle.long,
))
async def callback(self, interaction: discord.Interaction):
v = DropdownView(self.bot)
await self.ctx.send(view=v)
command:
@commands.slash_command(description='Add a job/opportunity')
async def add_opportunity(self, ctx: discord.ApplicationContext):
a = AddJob('Submit job/opprtunity',self.bot,ctx)
await ctx.send_modal(a)
how do i make it such that the dropdown comes only after the modal is submitted?
Right now, the dropdown view comes in while the modal is being filled
The IDE I am using PyCharm is looking for a discord module and not pycord
@grizzled sentinel
It has something to do with your overwrites. Can you send the code for that.
Dont use auto install for py-cord. Install like shown below and resart pycharm
?tag install
- 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
overwrites= {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
interaction.user: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_messages=True),
#SL: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_messages=True),
#SNCO: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_messages=True),
PCO_role: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_messages=True),
PXO_role: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_messages=True),
PNCO_role: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_messages=True),
}```
Thanks
In the future please dont ping me. The code looks right. It would make more sense to respond to the modal instead of passing ctx and sending. But even then
v = DropdownView(self.bot)
await self.ctx.send(view=v)
This should only run after submit is clicked
there was a naming issue with one of the roles, but it doesnt make the channel in the cattegory provided
If you have the category object just use https://docs.pycord.dev/en/stable/api/models.html#discord.CategoryChannel.create_text_channel
it is retuning none for the category
NFFC_category = discord.utils.get(guild.categories, name="NFFC")
print(NFFC_category)
guild = interaction.guild
get only returns if it is in the cache. You will need to https://docs.pycord.dev/en/stable/api/models.html#discord.Guild.fetch_channels
thanks for the help, although i had to use this :
async def callback(self, interaction: discord.Interaction):
await interaction.response.send_message('message')
v = DropdownView(self.bot)
await self.ctx.send(view=v)
If you send the view instead of message it will work to
fixed, thanks for the help :)
How do I make it were my bot does not close it self after someone tried to use a command that does not exist
That should be built into pycord. Can you show the code and error
sure. Put it in the past bin and make sure you dont show your token
?tag paste
I made it in a .env so it should not show the code
This is the error
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "gggg" is not found
So that does not crash the bot. It just displys the error and keeps going. There is a way to handel it though.
One sec
Can you show pip list
Package Version
aiohttp 3.8.4
aiosignal 1.3.1
async-timeout 4.0.2
attrs 22.2.0
charset-normalizer 3.0.1
frozenlist 1.3.3
idna 3.4
multidict 6.0.4
pip 21.1.2
py-cord 2.4.0
setuptools 57.0.0
typing-extensions 4.5.0
wheel 0.36.2
yarl 1.8.2
Ok
You would need to use on_error as the event and commands.CommandNotFound in the isinstance.
I will try that
I just tested the slash commands and it works but discord says "The application did not respond" after the command worked
Did you respond with ctx.respond
No
There's your issue
I will try that
The error literally tells you what's wrong
It's telling me of an empty message but I am sending a normal message then using await ctx.respond() to stop the application did not respawn error
That is not how it works
You use ctx.respond instead of ctx.send when working with application commands
It's not just a magic function that stops errors from happening
Ok I will try to fix the code
is there anyway currently to check if a reaction is a super reaction
No
I keep encountering this error every time I try to start my bot. Its formatting is different as I implemented a custom logging system, but it should get the point across:
INFO:classes:Done initializing database
WARNING:discord.client:PyNaCl is not installed, voice will NOT be supported
ERROR:__main__:Uncaught exception in event "on_connect"! Event information:
args: !!python/tuple []
kwargs: {}
Traceback (most recent call last):
File "C:\Python311\Lib\site-packages\discord\client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "C:\Python311\Lib\site-packages\discord\bot.py", line 1164, in on_connect
await self.sync_commands()
File "C:\Python311\Lib\site-packages\discord\bot.py", line 738, in sync_commands
app_cmds = await self.register_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python311\Lib\site-packages\discord\bot.py", line 531, in register_commands
prefetched_commands = await self._bot.http.get_guild_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python311\Lib\site-packages\discord\http.py", line 365, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access```
I have tried:
- Resetting my bot's token (and putting the new token into my config file)
- Kicking and re-adding the bot to my testing server with `bot applications.commands` scopes and Administrator permissions
- Making sure the guild/channel IDs in my config file are correct.
Google fails me, please help...
That means your bot is trying to register commands in a guild it's not in
but the guild id in my config file is correct...
And how are you using that id?
hol' up, wait a minute...
I literally just re-copied the ID into my file.
it turns out i messed up the guild id. might have accidentally backspaced a digit or something.
i placed it after the bot.command
and now the choices don't show
this is tranformed into a list of strings btw list(roles.keys())
nvm
i found it
how do I add callbacks to buttons added by add_item?
Subclass the button instead and then pass the instance to add_item
I have a button. When I press it, the view with the select menu is created. Now when I select something there, I want to add the message to the existing view and have it under the select menu. But the selection in the select menu should also still be displayed.
How do I do this correctly?
class SpotDetails(discord.ui.Button):
def __init__(self, bot):
super().__init__(label="Spotdetails abrufen", style=discord.ButtonStyle.gray, custom_id="spotdetails", row=1)
self.bot = bot
async def callback(self, interaction):
await interaction.response.send_message(view=GewaesserView(self.bot), ephemeral=True)
class GewaesserView(discord.ui.View):
def __init__(self, bot: discord.Bot):
self.bot = bot
super().__init__(Gewaesser(self.bot), timeout=None)
class Gewaesser(discord.ui.Select):
def __init__(self, bot: discord.Bot):
self.bot = bot
options = [discord.SelectOption(label=water) for water in bot.waters]
super().__init__(
placeholder="WΓ€hle das GewΓ€sser aus",
min_values=1,
max_values=1,
options=options,
)
async def callback(self, interaction: discord.Interaction):
view = GewaesserView(self.bot)
message = await interaction.response.send_message(f"Spots fΓΌr {self.values[0]}", ephemeral=True)
view.add_item(message)```
I get this error TypeError: object BanIterator can't be used in 'await' expression'.
When using this code
bans = await ctx.guild.bans()
if member in bans:
await ctx.respond(f'{member.mention} is banned from the server!')
else:
await ctx.respond(f'{member.mention} is not banned from the server!')
member being a discord.Member.
Try removing the await before ctx.guild.bans()
bans = ctx.guild.bans()
you have to use await for that
what is bans returning?
Oh right mb
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 ...
Can I send a select menu with a pre-selection?
How would i be able to keep this as 8ball? When i have it like this it doesnt let the bot start,
Ive tried adding "" to it but that didnt work too.
I want to add another select menu to the view but I want to keep the previous selection in the first select menu.
Can I do this somehow or can I just work with 2 different views without editing the message?
async def callback(self, interaction: discord.Interaction):
view = GewaesserView(self.bot, self.messageid)
view.add_item(SpotAuswahl(self.bot))
await self.messageid[0]['gewaesser'].edit_original_response(view=view)```
It doesnt return anything. It crashes on that line "bans = await ctx.guild.bans()"
With this error: Application Command raised an exception: TypeError: object BanIterator can't be used in 'await' expression'
_8ball and add (name="8ball")
Ok.
did you click at the link?
https://docs.pycord.dev/en/master/api/ui_kit.html#discord.ui.Select.values
I think if you set the values of the select menu it should stay. I'm surprised it does not do this by default
The library has helpers to help create component-based UIs. Shortcut decorators: Objects: Attributes children, disable_on_timeout, message, timeout. Methods cls View.from_message, def add_item, def...
If I have sent an interaction.response it is only active for 15 minutes.
I send a message as an ephemeral message.
Can I still delete the message after the 15 minutes if I have saved the interaction or is that no longer possible?
Empherial messages cannot be deleted after 15 min. Sometimes they cannot be deleted sooner than that.
Ex: if the user clears the message manually or refreshes their client
Yes the selection is displayed. But when I made a selection, I want to add another select menu to the view and this is how I solved it now:
async def callback(self, interaction: discord.Interaction):
view = GewaesserView(self.bot, self.messageid)
view.add_item(SpotAuswahl(self.bot))
await self.messageid[0]['gewaesser'].edit_original_response(view=view)```
And so yes the message is edited and resent and so the selection in the first select menu is no longer active.
No i did not. It seems i missed the link. But that fixed the problem i had. Thank you π
Okay then I would have to include a query that automatically deletes these messages after 15 minutes if they are still there.
Yeah it should be simple with a try/except
Oh yes right, good idea thanks π
Can I somehow solve this better with the two select menu?
I think it would just be self.add_item(select) than edit the original response
What's the event name/rtfm link to the event which triggers when an audit log entry is passed in the guild
.rtfm on_audit_log
Target not found, try again and make sure to check your spelling.
.rtfm on_audit
Target not found, try again and make sure to check your spelling.
.rtfm on_
discord.on_presence_update
discord.on_reaction_remove
discord.on_shard_disconnect
discord.on_raw_message_edit
discord.on_raw_reaction_add
discord.on_socket_event_type
discord.on_guild_role_create
discord.on_guild_role_update
discord.on_raw_thread_delete
discord.on_socket_raw_receive
discord.on_integration_create
discord.on_integration_update
discord.on_voice_state_update
discord.on_raw_message_delete
discord.on_raw_reaction_clear
discord.on_thread_member_join
discord.UserCommand.is_on_cooldown
discord.Permissions.mention_everyone
discord.Permissions.use_application_commands
discord.on_application_command
This section outlines the different types of events listened by Client. There are 4 ways to register an event, the first way is through the use of Client.event(). The second way is through subclass...
What do you mean exactly?
class Gewaesser(discord.ui.Select):
def __init__(self, bot: discord.Bot, messageid):
self.bot = bot
self.messageid = messageid
options = [discord.SelectOption(label=water) for water in bot.waters]
super().__init__(
placeholder="WΓ€hle das GewΓ€sser aus",
min_values=1,
max_values=1,
options=options,
)
async def callback(self, interaction: discord.Interaction):
view = GewaesserView(self.bot, self.messageid)
view.add_item(SpotAuswahl(self.bot)))
await self.messageid[0]['gewaesser'].edit_original_response(view=view)```
If you edit the original view instead of creating a new one. You can get the view in the select callback by using self.view
You can remove the existing select menu and add the next one?
They want the old one to stay
I want to keep the old select menu with the selected choice and then just add a new select menu under there.
So the second select menu is added but the selection from the first select menu is also gone...
class Gewaesser(discord.ui.Select):
def __init__(self, bot: discord.Bot, messageid):
self.bot = bot
self.messageid = messageid
options = [discord.SelectOption(label=water) for water in bot.waters]
super().__init__(
placeholder="WΓ€hle das GewΓ€sser aus",
min_values=1,
max_values=1,
options=options,
)
async def callback(self, interaction: discord.Interaction):
self.view.add_item(SpotAuswahl(self.bot))
await self.messageid[1]['gewaesser'].edit_original_response(view=self.view)```
oh
I have now solved it differently π
Is this list self.massageid created separately for each user who clicks on the button?
class SpotDetails(discord.ui.Button):
def __init__(self, bot):
super().__init__(label="Spotdetails abrufen", style=discord.ButtonStyle.gray, custom_id="spotdetails", row=1)
self.bot = bot
self.messageid = []
async def callback(self, interaction):
self.messageid.append({'buttoncheck': 'False'})
self.messageid.append({'buttoninteraction': message_interaction})```
it will be created separately for each time SpotDetails button is created
And if 2 users click the button within a very short time?
Does the function then still work or do the lists then overwrite each other?
I have now changed it so, then a separate list should be created for each user who presses the button, or am I seeing it wrong?
class SpotDetails(discord.ui.Button):
def __init__(self, bot):
super().__init__(label="Spotdetails abrufen", style=discord.ButtonStyle.gray, custom_id="spotdetails", row=1)
self.bot = bot
async def callback(self, interaction):
message_details = []
message_details.append({'buttoncheck': 'False'})
message_details.append({'buttoninteraction': message_interaction})```
nope wont overwrite
thats some basic OOP
yea there isnt any issue with the previous way
it depends on your UI flow
Is it better to create the list in the init or in the callback?
^
when do you create SpotDetails ?
do you create the button inside a command?
if you do, do you want the states to persist if a user uses the command multiple times, or not?
I press a button and then SpotDetails is created with a view. There are 3 buttons in here. When I click a button there, a new view is created.
Here a select menu is created, after I have selected something in the select menu, the view is edited, the select menu is replaced by a new one. After selection in the 2 select menu the views are deleted.
No it should not be persist but always only when the button is pressed for 1x
ah
so this whole structure should only be contained inside 1 button press and not conflict with others right
then yes, init is a good way
Exactly. But the button can also be pressed by different users at the same time.
yes but since you are creating a fresh view for every time the button is pressed, a new list is created every time
Ok nice π
Do I have to delete the list at the end or will it be deleted automatically?
i believe it should be deleted automatically by python garbage collection, once the view is deleted
Okay I'll give it a try otherwise I can just set a command at the end that deletes the list
When I edit a respons, does it count new 15 minutes or does the previous time remain?
I'm executing this in the main.py file, so what I should put in the self argument?
do I need to create a class to actually run it fine?
nvm I think I will just do a normal print on that, I think this is_ready works better when dealing with cogs
Events don't work like that
.guide
oof, its been a while since my last touch on my bot, now when I came back I forgot almost everything
I thought it worked as well as the cog.listener function
so I searched thru is_ready similar functions in the docs
thanks!
There is no possibility to extend the interaction.respons time or?
defer
?tag defer
No tag defer found.
I mean those 15 minutes after which the respons is no longer available.
nope
Okay too bad then I still do not know how to implement my idea π
ephemeral messages are only possible in a response or?
yeah they are only possible in a response to an interaction
what?
Okay because I actually need a message that only the user can see but can be edited and deleted etc. for longer than 15 minutes.
you can to respond it, but you can edit it later
But if there is a button in the respons, for example, it will only work for 15 minutes right?
if you put like 3600, then the button would time out in an hour.
I was talking about how I came with the idea of using the @commands.bot.is_ready function
but he solved my problem guiding me to the page that show the "creating your first bot" basics
That means I can send an ephemeral message as respons to a user and this message contains a button that has a timeout=None, then the button still works after the 15 minutes and I can delete the message even after the 15 minutes?
how much a message object can be kept?
like lets hypothetically say i have some sort of way to keep a pycord message object
which i could use for editing, deletion.... yadi yadi yadi
the question lies in on how long i can keep it without having to fetch a new one
As long as the bot doesn't restart
fetch_message then stores the message in the cache.
As long as the bot doesn't restart and clear the cache, you're all good
As long as you maintain a strong reference to it (dict, list, some variable etc) you can use it
If you just want to edit delete etc, it might be safer to use partial objects
.partial
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 -
- Partial Messageable (analogus to a Channel) : https://docs.pycord.dev/en/stable/api/models.html#discord.PartialMessageable
- Partial Message (analogous to a Message): https://docs.pycord.dev/en/stable/api/data_classes.html#discord.PartialMessage
Example Usage:
async def star_message(channel_id: int, message_id: int):
# Get Partial Messageable object. Docs-
# https://docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.Bot.get_partial_messageable
partial_channel = bot.get_partial_messageable(channel_id)
# Get Partial Message. Docs-
# https://docs.pycord.dev/en/stable/api/models.html#discord.PartialMessageable.get_partial_message
partial_message = partial_channel.get_partial_message(message_id)
# Add a reaction
await partial_message.add_reaction(":star:")
are they faster and have 0 rate limits?
what?
like what kind of benifit do they give me i don't understand
They don't behave any differently than normal message or channel objects regarding that. The only difference is how they are created and stored in python. They are created using only ids. If you only need to perform api functions on the messages or channels without needing any attributes, then you can store these instead of the actual objects as this will consume lesser memory
It is also the only way to not rely on cache for api calls
Really useful if you store channel or message ids in a db
so wait IDs change?
oh ok
if only there was a reliable way to store messages that last forever without having to make a bunch of requests to the API
Assume you have a channel id in your db and you want to send a message in it. Normally what you would do is bot.get_channel followed by channel.send
This however relies on the bots cache. And it is possible especially on larger bots that the cache doesn't have the channel object.
You could do bot.fetch_channel.
But for simply sending a message, you only really need a channel id, and not all the other stuff fetch_channel gives you.
Here enters partial channel. You can create it using only an id. This saves you the api call of fetch_message. You can directly send a message using this. And since api calls are not quick at all, this can save you a lot of time
Wow that's a big writeup π
If you need the attributes and stuff, just store the message object somewhere on the bot? Like a dict botvar?
I have created a button in my ephemeral message with a view and added a timeout=None to it. After 15 minutes I tried to press this button but it does not work...
What am I doing wrong that the button still works after the 15 minutes?
class GewaesserView(discord.ui.View):
def __init__(self, bot: discord.Bot, message_details):
self.bot = bot
self.message_details = message_details
super().__init__(Gewaesser(self.bot, message_details), timeout=None)```
probably the bot might get rebooted
like restarted, try to make a on_ready event with a print to print when the bot goes online
then do the command with the button... etc
then wait 15 minutes, if there are 2 messages without u rebooting
how do I change the activity of the bot?
i think
thats how u do it bot.change_presence
No no the bot is online all the time
thanks
np
i say if the bot gets restarted
like it may seem online all the time but is there a sudden close for small time and then goes online back
No for the 15 minutes a respons is active everything works but after the 15 minutes it doesn't work anymore. And earlier someone said if I set the timeout higher then it should still work after the 15 minutes.
so probably there is a discord limit
Yes respons are only active for 15 minutes at a time.
is the message one or multiple with the buttons
It is an ephemeral message that contains a button. And ephemeral messages can only be sent as respons.
And I want to maintain the function of the button after the 15 minutes of the response time are up.
How customizable are linked roles? Does anyone have created their own requirements yet?
can i get some examples of working with embeds
Hey guys I have a quick question:
Is it possible to have a mix of Cog and SlashCommandGroup ?
I was using SlashCommandGroup but I want to switch to Cogs and keep the grouping (or prefixing idk how to call it) feature, is it possible ? If yes how ?
And also what's the point of the description on the SlashCommandGroup constructor because it doesn't seem to be shown anywhere
Thanks a lot π
things that dont work after 15 mins are- anything related to interaction.response and interaction.followup
you can still use interaction.message though. you can also save interaction.response.original_response before hand on some variable, so you can edit delete, etc later
you can also pass activity to the bot constructor and save yourself an api call
More features to make your bot cool and snazzy.
are you trying to say about slash groups in cogs?
yes thats possible
Here's the slash cog groups example.
like this
Yes i think (for example achieve this with cogs https://guide.pycord.dev/interactions/application-commands/slash-commands#subcommand-groups)
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
thanks a lot I'll look into it π
Oh ok that's the same lmao, but I don't understand how would I use this alongside Cog ?
In here for example:
Gives this (without the prefix or group before the name of the command)
I have this on my bot subclass (you can see the old version which was using the 2nd part of what you sent)
Then how can I make it work in an ephemeral one button after the 15 minutes?
nvm found out
thx tho
hey, i'm having a hard time trying to catch a time out via on_member_update event (intents.members set), any hint on where to look for?
Ok I think I fixed it
Error? Code? What's not working?
just not receiving an event when timeouting a user
I guess I'm not doing it right
@commands.Cog.listener()
async def on_member_update(self, before: discord.Member, after: discord.Member):
# check if time out
LOG.info("member update received!")
@commands.Cog.listener()
async def on_member_update(self, before: discord.Member, after: discord.Member):
# check if time out
LOG.info("member update received!")
Well you didn't create a Slash command group
Thonk
Pretty sure that's a discord limitation
I was confusing stuff sorry I'm tired ^^ I do it like that now
Pass it to the constructor like so
bot = commands.Bot(..., activity=Activity(...))
Uhh
Wot..
Okay so I have no option. Then I would have to delete the respons and send it again so that new 15 minutes expire right?
Do you happen to know how I can put a Paginator in a subclass? I can't find any example or tutorial how to do that.
π
Oh wait are you trying to have an app cmd in an extension without having it in a cog?
Is that what you are trying?
You could send it without ephemeral or in dm ig
Paginator in a subclass?
Subclass of what?
View?
any ideas?
tysm
Yes, exactly. I want to send a view that contains a paginator.
No i'm using an extension because that was shown in the Cog part of the documentation
I have a bunch of related commands that I wanted to group, so I used a cog
But it doesn't group them like SlashCommandGroup (i.e with the Cog the actual command is /<cmd name>, whereas with SlashCommandsGroup it's /<grp name> <cmd name>
Does the bot have mod perms?
Yea i showed you how to add groups inside cogs
Here's the slash cog groups example.
See that
does it need to have to catch events?
Paginator is a view subclass already. Do you want to send the paginator as a response to an interaction from a view?
Are there any examples how a subclassed callback would look?
Not sure but as a normal user, you need mod perms to see if a member is timeout. So i figured it could be similar for bots
(I don't know how to start)
Here's the button roles example.
I want to call a view in the callback function after selecting something in the select menu, which sends a paginator with corresponding content, depending on the selection in the select menu.
@graceful mason does something similar. Check it out
I saw but I do I use it inside a cog then ?
Let's say I have
class MyCog(discord.ext.commands.Cog):
def __init__(self, bot):
# init
@discord.slash_commands(params...)
async def foo(self, ctx):
# do stuff
How do I add the slashcommandgroup with it ?
Thanks
Oh, I see now
Like this iirc
class MyCog(Cog):
# init
my_group = SlashCommandGroup(...)
@my_group.command()
async def foo(...):
...
The example tells you how to do it
Did you read it?
So you want to send a view or the paginator after selecting something in the menu?
I did try this but it doesn't work (my_group is not defined), if I put it above as a global variable maybe, I'll try
The Paginator
Is it like this
select menu -> paginator
Or
select menu -> view (has a button -> paginator)
Ah so just use paginator.respond ?
You define the group inside the cog. It should work. How did you try?
I created my Paginator like this. But I don't know exactly how to call it in the callback of the select menu.
async def page(self, ctx):
SPOTS_PER_PAGE = 6
data = await dab.get_all_spots()
pages = []
# Erstelle fΓΌr jedes sechste Element eine neue Seite
for i in range(0, len(data), SPOTS_PER_PAGE):
page_data = data[i:i+SPOTS_PER_PAGE]
embed = discord.Embed(title="SpotΓΌbersicht")
for entry in page_data:
name, fish, spot = entry
if fish is None and spot is None:
fish_text = "Keine EintrΓ€ge vorhanden"
spot_text = ""
else:
fish_list = []
spot_list = []
fish_text = ""
spot_text = ""
if fish:
fish_list = fish.split(",")
if spot:
spot_list = spot.split(",")
if len(fish_list) == len(spot_list):
for i in range(len(fish_list)):
fish_text += f"{fish_list[i]} - Spot: {spot_list[i]}\n"
else:
fish_text = fish
spot_text = f" - Spot: {spot}"
embed.add_field(name=name, value=fish_text + spot_text, inline=False)
pages.append(embed)
# Erstelle den Paginator und fΓΌge den neuen Button hinzu
view = discord.ui.View(SpotDetails(self.bot))
paginator = Paginator(pages=pages, timeout=None, custom_view=view)
await paginator.send(ctx)```
'ArgoBot' object has no attribute 'expandtabs' (ArgoBot is just a subclass of the bot)
did it like this
Is there some type of Member/Server builder? Like I want to get the icon of a server that my bot is not in, how do I "build" the server as an object and get its properties
build with the ID
I think I've made this before with member
change ctx to smth like ctx_or_interaction in your parameters
Then at the end, check if that is instance of context or isinstance of interaction
If context then use paginator.send
Else paginator.respond
but what I really want is with guild
Full error?
And how did you load the cog?
Can I also send the Paginator to a specific channel using a Channel ID?
Hmm not sure
Traceback (most recent call last):
File "/home/mathis/.local/lib/python3.10/site-packages/discord/cog.py", line 786, in _load_from_module_spec
setup(self)
File "/home/mathis/Programmation/Projets/ArgoBot/argobot/cogs/infos_plongeur.py", line 162, in setup
bot.add_cog(ArgoBot(bot))
File "/home/mathis/Programmation/Projets/ArgoBot/argobot/bot_class.py", line 10, in __init__
super().__init__(description, *args, **options)
File "/home/mathis/.local/lib/python3.10/site-packages/discord/bot.py", line 1140, in __init__
self.description = inspect.cleandoc(description) if description else ""
File "/usr/lib/python3.10/inspect.py", line 750, in cleandoc
lines = doc.expandtabs().split('\n')
AttributeError: 'ArgoBot' object has no attribute 'expandtabs'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/mathis/Programmation/Projets/ArgoBot/argobot/main.py", line 28, in <module>
argobot = ArgoBot()
File "/home/mathis/Programmation/Projets/ArgoBot/argobot/bot_class.py", line 14, in __init__
self.load_extension('cogs.infos_plongeur')
File "/home/mathis/.local/lib/python3.10/site-packages/discord/cog.py", line 910, in load_extension
self._load_from_module_spec(spec, name)
File "/home/mathis/.local/lib/python3.10/site-packages/discord/cog.py", line 791, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.infos_plongeur' raised an error: AttributeError: 'ArgoBot' object has no attribute 'expandtabs'
And is that the name of your cog 
omg
lmao thanks
Np lol
I don't think you can get properties of a guild your bot is not in
thanks a lot it works (can't believe i'm so stupid lmao)
There isn't a member/guild builder because these are objects provided by data from discord and not to be built by the user
Try if bot.fetch_guild works
Yes you can send to a different channel. Get the channel from bot.get_channel and pass it. Or pass a partial channel
.partial
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 -
- Partial Messageable (analogus to a Channel) : https://docs.pycord.dev/en/stable/api/models.html#discord.PartialMessageable
- Partial Message (analogous to a Message): https://docs.pycord.dev/en/stable/api/data_classes.html#discord.PartialMessage
Example Usage:
async def star_message(channel_id: int, message_id: int):
# Get Partial Messageable object. Docs-
# https://docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.Bot.get_partial_messageable
partial_channel = bot.get_partial_messageable(channel_id)
# Get Partial Message. Docs-
# https://docs.pycord.dev/en/stable/api/models.html#discord.PartialMessageable.get_partial_message
partial_message = partial_channel.get_partial_message(message_id)
# Add a reaction
await partial_message.add_reaction(":star:")
the member "build" I was talking about was actually Guild.get_member π
How do I add a role to a member object by using the role id?
paginator.respond
How can I include the channel ID here then?
Like this?
await channel.respond(paginator)
- How do I add a role to a member object by using the role id?