#Basic Pycord Help (Quick Questions Only)

1 messages Β· Page 60 of 1

calm plume
#

so i have to make a seperated table for reactions?

#

and have like columns

#

"vote_or_downvote" "user_id" ?

proud mason
calm plume
#

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

meager mica
#

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

silver moat
#

show code?

calm plume
#

will it keep ip with the spam

#

or nah?

proud mason
proud mason
#

Sqlite is powerful

calm plume
#

hmm ok

proud mason
#

Yea you can try and implement, pretty sure it would have a noticeable speed difference

meager mica
# silver moat show code?

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

proud mason
#

Do you have multiple instances running?

meager mica
#

i dont see any ill reset token just incase

#

reset token same issue

#

112 ms bot.ws.latency

silver moat
#

do other commands work?

meager mica
#

nope

#

they all get unknown interaction

silver moat
#

do you have an on_interaction event?

meager mica
#

i do not

#

i got on ready event and on message event

proud mason
meager mica
#

this bot i very simple on its own 2 slash commands

#

ill comment out everything and just respond and see what it does

blissful hazel
#

Can you put slash commands in a subclass?

silver moat
#

yes

proud mason
meager mica
#

nope

blissful hazel
meager mica
#

the error comes about 3 seconds after command

#

but it takes too long to defer it or somthing like that

proud mason
#

Hmm

silver moat
meager mica
#

so i removed defer

#

and it works with simple bot but when i have defer it dont work

proud mason
#

Wow that's weird. Can you confirm you are on py-cord 2.4.0 ?

silver moat
#

"contact your are"

proud mason
proud mason
blissful hazel
#

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?

proud mason
#

Uhh, are you trying to add the commands inside the bot class?

blissful hazel
#

Yes...

proud mason
#

Hmm

#

I wonder if you can do that

silver moat
#

nope

proud mason
#

Try @self.slash_command, but ig you would need to do this inside the init

#

Not sure if that could work tho

silver moat
#

this wouldn't work because it is not added to the bot

proud mason
#

πŸ‘€

limber urchin
#

Yeah, that's not something you can do

silver moat
#

You should use cogs to add them or the functional interface.

blissful hazel
#

Okay, thank you!

proud mason
#

Functional interphase πŸ’€ (what even is that)

limber urchin
#

Putting everything in the same class isn't really a good design choice either imo

silver moat
proud mason
#

Hmm

#

So the normal route

meager mica
#

im checking responding then editing

#

and see if it works

blissful hazel
#

How do you send colored code blocks?

meager mica
#

```lang
code
```

blissful hazel
#
print("Hello, world!")
#

thank you! πŸ˜„

copper knot
#

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?

silver moat
#

code your own

meager mica
copper knot
silver moat
errant craneBOT
#

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```
copper knot
proud mason
copper knot
#

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

proud mason
river dove
#

AttributeError: 'Bot' object has no attribute 'bridge_command'. Did you mean: 'message_command'?

#

does anyone know why im getting this error

limber urchin
#

Show your code

proud mason
#

?tag client

obtuse juncoBOT
#
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)
fervent cradle
#

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?
grizzled sentinel
#

Make sure you only have 1 bot running with that token at the same time

#

otherwise they will fight over what gets registered

fervent cradle
#

oh, i have it hosted and at the same time i am running a local instance

limber urchin
#

You should use a different bot for development testing, otherwise you'll run into all sorts of issues and conflicts.

fervent cradle
#

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

grizzled sentinel
#

what are you trying to do with the cog? Is hfd = discord? Shouldn't command_attrs={"hidden": True} be a argument in the __init__

fervent cradle
grizzled sentinel
#

And there is no test_group.callback or test_group._callback in your code

fervent cradle
limber urchin
#

What is hfd?

grizzled sentinel
#

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 have command_attrs, or at least dict(hidden=True)

#

it must treat the group as a command. It might be a bug

calm plume
#

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

copper knot
proud mason
#

Use it like a normal async for block of code

proud mason
calm plume
#

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

proud mason
#

Yea so, Iterate and break if user.id is equals msg author id. At least that's what I would do for this code ^

calm plume
#

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
proud mason
#

Do you use the count of user reactions?

calm plume
#

well i don't and the reason being is why

proud mason
#

I understood you only check if msg.author is in list of reaction users

calm plume
#

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

proud mason
copper knot
proud mason
# copper knot ?

Well you can add it to the library. Would be cool.
That would make it on_error(event_name, error, *args, **kwargs) right

calm plume
#

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

grizzled sentinel
#

What exactly are you trying to do?

calm plume
#

if the user reacted then -1, if not it remains as it is

thorny kindle
#

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.

calm plume
#

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

proud mason
calm plume
#

im confused rn

proud mason
#

Alr so you wanna do smth like this

proud mason
#
async for user in reaction.users():
    if user.id == author.id:
        break
    else: 
        return # returns if not broken
thorny kindle
errant craneBOT
#

Here's the slash options example.

calm plume
proud mason
#

😭 πŸ‘

grizzled sentinel
# thorny kindle cog?

That example will help you get the channel. In the command. If you still are a bit confused take a look at the guide

proud mason
#

Alr I'm heading to sleep now

grizzled sentinel
#

.guide

winter condorBOT
thorny kindle
#

Alr, Thanks

devout anvil
#

What will this return if the user has no nickname

#

Class: discord.Member.nick

proud mason
devout anvil
grizzled sentinel
#

@sage bear

#

?tag install

obtuse juncoBOT
#
  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

grizzled sentinel
#

You only need pycord. Pycord uses discord name

sage bear
sage bear
# grizzled sentinel You only need pycord. Pycord uses discord name

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```
young bone
#

what is letters?

topaz quartz
#

Hello, can't import pycord even though it shows up on pip show py-cord. I've tried reinstalling discord.py

novel jay
#

also remove discord.py because it'll cause naming problems

topaz quartz
#

ok so its a straight up replacement

novel jay
#

yes

topaz quartz
#

would it break any existing code if i replace discord.py or is it just an extension

novel jay
#

its a fork of discord.py, V3 will be more of its own thing

novel jay
topaz quartz
#

aight ty

topaz quartz
#

@bot.user_command or slash commands

novel jay
#

that should still exist

topaz quartz
novel jay
#

works for me

#

can you share your pip list?

#

pip freeze

copper knot
#

i looked at the docs source and it looks like it autogenerates

obtuse juncoBOT
#
  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

copper knot
cyan quail
#

the documentation is for the most part autogenerated, but in many cases you still need to update the original .rst to include the function

copper knot
young bone
copper knot
young bone
#

?

copper knot
cyan quail
copper knot
#

in a different file

#

okay ive completed the checklist

young flint
#
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

young bone
silver moat
cyan quail
#

no... ##1907 broke it because no one tests their damn prs anymore

errant craneBOT
young flint
#

since when ? why?

young flint
young bone
#

^

cyan quail
#

how do you remove an entire variable and not check for any references

young bone
#

VS code has an Deeple extension?

cyan quail
#

that's github.dev

young bone
#

oh

cyan quail
#

just

#

use 2.4.0

young flint
#

yea

silver moat
#

Is a fix PR'ed yet?

cyan quail
#

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

silver moat
#

I'm sure they tested the events tho

cyan quail
#

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

silver moat
#

vim

cyan quail
#

die

young flint
silver moat
#

CI doesn't have 100% test coverage

young flint
#

I mean just manual testing yourself

cyan quail
#

im pretty sure regular event registration was fine

young flint
#

yea it is

cyan quail
#

but both on_command_error and unload_cog would be broken

young flint
#

i think more people would have noticed if it wasnt

cyan quail
#

well it's only master so

#

merged like a few days ago

young flint
#

yea

cyan quail
#

or... 12 hours ago

young flint
#

its an easy fix

cyan quail
#

at least you noticed that fast, thanks

young flint
#

lmao no problem

#

ive spent far too long away from pycord

thorny pasture
#

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()

young bone
#

from discord.command import slash_command?

#

?tag client

obtuse juncoBOT
#
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)
silver moat
#

it would be @discord.slash_command

#

@thorny pasture

thorny pasture
#

Alright lemme try

#

Thx in advance

#

Imports would just be. Import discord. Right

silver moat
#

yea

thorny pasture
#

Alright. How do i check if person running slash_command has a certain permission?

#

Wasnt that like discord.has_permission or something?

young bone
#

the same like a prefix one

#

and discord.default_permissions

thorny pasture
#

Ah alright.

thorny pasture
#

Thanks alot. That is exactly what i meant.

thorny pasture
#

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*

silver moat
#

discord.Member is a misnomer. In reality, it can just be any user.

thorny pasture
#

So could you just enter id or something?

#

Or just name and discrminator

#

Would that work as that input type?

silver moat
#

you can <@id>, too

cyan quail
#

the raw ID works in discord input types

#

but just name#discrim won't work if the bot doesn't know the user

thorny pasture
#

Alright thanks.

#

Appreciate the help.

thorny pasture
#

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.

silver moat
#

?tag botvar

obtuse juncoBOT
#

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

silver moat
#

your db can be a botvar

thorny pasture
#

Perfect thx.

true panther
#

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

young bone
true panther
#

Yeah, but I'd like to have a variable with a list of roles. I guess unpacking it will work.

proud mason
tired goblet
#

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

proud mason
#

Followed by msg.edit(view=view)

proud mason
tired goblet
#

thank you

calm plume
#

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?

calm plume
#

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

limber urchin
#

Why are you using threading?

calm plume
#

while testing

#

and coming up with random ideas

#

that might have worked on the long run

tired goblet
#

it says that message isn't defined

calm plume
#

although it didn't really do it

#

i believe its capable of speeding things up

proud mason
proud mason
calm plume
#

hmmm ok

proud mason
#

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

tired goblet
#

am i doing it wrong here?

proud mason
#

(in python at least)

proud mason
tired goblet
#

ah

proud mason
#

Check if the correct message is edited, else you might need to use interaction.message.edit(view=self)

tired goblet
calm plume
#

um how do i type it exactly

proud mason
#

And pass this loop to the function

#

And wtf is threading.Thread.__init__

#

super().__init__ already does that

calm plume
#

o

#

k

calm plume
#
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]
proud mason
tired goblet
#

it was editing the wrong message

calm plume
#

the IDE displays this as a wanring

tired goblet
#

so i tried the other one

proud mason
#

Ah yea i thought so

calm plume
#

but here since i run

#

RuntimeWarning: Enable tracemalloc to get the object allocation traceback

proud mason
#

Interaction.message.edit is good too

calm plume
#

RuntimeWarning: coroutine '_AsyncIterator.flatten' was never awaited

proud mason
#

Hm

calm plume
#

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

proud mason
#

||you really spent hours trying to implement this but wouldn't implement a db based setup blobpain ||

proud mason
#

Idk how to solve your error lol, wait for someone else. It would be a great idea to create a post in #969574202413838426

calm plume
#

imma ask chatgpt if it can come up with stuff

proud mason
calm plume
#

yes

#

yup impossible to do threading

#

with asyncio

#

time to read docs of asyncio

#

if nothing works

#

then docs will work

young bone
calm plume
#

im kinda lazy to implement it now

#

like im really losing hope

#

ok yknow what im opening a help form]

silent meadow
#

hi, can anyone guide me for str type Options in slash commands?

proud mason
silent meadow
#
@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

young bone
#

choices requires a list

silent meadow
#

one sec

silent meadow
#
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 ☝️

proud mason
#

You need a list of strings iirc

#

Or of optionchoice

silent meadow
zenith verge
#

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

fervent cradle
#

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?

proud mason
proud mason
fervent cradle
proud mason
#

Smth like

my_str = ""
for perm, value in permissions:
    a += f"..."
#

.rtfm permissions

proud mason
#

perm should be the attribute name iirc

frank thistle
dry echo
#

is it possible to hide user_commands for user which have not a specific role or permission?

zenith verge
#

return didn't work either

grizzled sentinel
# zenith verge `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

fervent cradle
#

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

fossil mulch
#

Does anybody here uses Tortoise Orm for his Bot?

grizzled sentinel
#

@prime sundial

#

?tag install

obtuse juncoBOT
#
  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

prime sundial
#

import discord
ModuleNotFoundError: No module named 'discord'

grizzled sentinel
#

You do not need git if you are installing the base version

prime sundial
#

i installed git

grizzled sentinel
grizzled sentinel
prime sundial
prime sundial
grizzled sentinel
#

Same way that you installed pycord type python -m pip list

fossil mulch
# proud mason yes

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?

grizzled sentinel
#

You could open your own thread :)

fossil mulch
#

Or do you maybe have your bot on GitHub so I can have a look there?

prime sundial
proud mason
#

i dont, but i can send you my models file

fossil mulch
#

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

grizzled sentinel
#

Its fine, as long as it somehow relates to a discord bot we will help.

grizzled sentinel
# prime sundial

You somehow installed pycord V3 you want to use pycord V2.4 (latest)]

#

V3 is still in development

prime sundial
#

i used to use replit

#

im now on vsc

grizzled sentinel
#

python -m pip uninstall py-cord
python -m pip install -U py-cord

zenith verge
#

not quitting and generating another modal

prime sundial
#

now imma try

#

WAYYYYYYYYYYYYYYYYYYYY

grizzled sentinel
prime sundial
#

tysm man, its been a few years last time i programmed

grizzled sentinel
proud mason
grizzled sentinel
# zenith verge tysm, this worked too haha

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.

zenith verge
#

uh wait

#

how does it work yeah

fossil mulch
#

Can i paste my code to pastebin or something like this?

zenith verge
#

strange

fossil mulch
#

Post Limit is reached =D

grizzled sentinel
#

?

fossil mulch
#

any recommendations, i saw on some servers pastebin for example is banned

zenith verge
grizzled sentinel
obtuse juncoBOT
fossil mulch
#

Character limit, I'm sorry

grizzled sentinel
#

ahh

proud mason
grizzled sentinel
zenith verge
#

lmao yes I just found out

#

should not use that

proud mason
#

ah lol

fossil mulch
hardy python
#
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

cyan quail
#

downgrade to 2.4.0

#

though i did just PR that fix

#

not merged though

hardy python
#

Oh gotcha.

wind jay
#

how to add cooldown to a button

proud mason
#

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

grizzled sentinel
wind jay
# grizzled sentinel Something you could do depending on how long the cooldown is have a Time To Live...
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

grizzled sentinel
#

πŸ‘ that is basically a TIL cache

fossil mulch
#

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?

zenith verge
#

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

cyan quail
#

e.g. py button = discord.ui.Button(...) async def c(interaction): button.disabled = True await interaction.response.edit_message(...) button.callback = c

zenith verge
#

Ah ok

#

I put self in the param I guess that was the problem

thorny pasture
#

Is there like a discord.has_role()?

#

So i only need to import discord.

#

Since thats basicly the only library i use in cogs.

zenith verge
#

user being Interaction.user

#

oh wait nvm

thorny pasture
#

Yes but i meant like when defining a slash command

zenith verge
#

So whether a server has a certain role

thorny pasture
#

Like discord.default_permissions() for permissions.

thorny pasture
zenith verge
#

well then

#

this is correct

#

just put Interaction as a parm in the command

thorny pasture
#

Alrighty

thorny kindle
#

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

cyan quail
thorny kindle
cyan quail
#

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

thorny kindle
#

So i could have it like

await ctx.respond(':+1:')
await channel.send('test')
#

something like that

lost lodge
#

Hello guys, how can I make a select option default, if a user has a specific role?

cyan quail
#

also note that you can make the respond ephemeral=True so only you can see it

thorny kindle
#

Ok.

cyan quail
lost lodge
thorny kindle
#

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?

cyan quail
#

or just do the check beforehand and pass the result through

cyan quail
thorny kindle
#

What would i use to make it into an actual message? Something like ```message=message.content

cyan quail
cyan quail
thorny kindle
#

Oh ok, So i would just add it as f'{message}'

cyan quail
#

mhm

cyan quail
lost lodge
# cyan quail add another argument to `def __init__`

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
            ),```
cyan quail
#

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__

lost lodge
#

does select_callback need to be the name of my callback?

cyan quail
#

well that's just whatever you called it

lost lodge
#

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']))))```
cyan quail
#

well, do you already know the member id?

lost lodge
#

it should be for every member on the guild

cyan quail
#

ah your idea here might not work then

lost lodge
#

ah

cyan quail
#

are you trying to use default so every member would see their existing roles on the selector?

lost lodge
#

yes

cyan quail
#

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

lost lodge
cyan quail
#

well not really

lost lodge
#

ok

cyan quail
#

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

blissful hazel
#

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?

proud mason
blissful hazel
proud mason
#

Just so yk, they need a bit of basic learning before you can use them

#

Like a high walled garden

still helm
#

I am trying to add a emoji to the button label of the persistant role example of pycord

ThatΒ΄s my code

https://pastebin.com/khCtd3D5

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

errant craneBOT
proud mason
still helm
proud mason
#

hmm

silver moat
#

should be role.name, no?

still helm
#

where?

proud mason
#

in the init

#

you passed them the other way round while creating the button

silver moat
#

also

*** @ Line 15 ***
-     def __init__(self, role: discord.Role, emoji=discord.Emoji):
+     def __init__(self, role: discord.Role, emoji: discord.Emoji):
#

on line 15

still helm
#

one sec πŸ™‚

#

i try it

silver moat
#

had to google the syntax

still helm
#

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'
silver moat
#

the role ID could be wrong

still helm
#
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 πŸ˜•

proud mason
#

πŸ‘€

still helm
#

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 πŸ˜„

silver moat
#

fetch/get the emoji too I suppose

proud mason
#

ig use bot.get_emoji

#

why not use the emoji parameter of the button?

#

it accepts an emoji string

still helm
#

iΒ΄ll give it a try

green hinge
#

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
)```
silver moat
#

yeah just change to commands.Bot

#

and add the prefix aspect of it

still helm
proud mason
#

?tag client

obtuse juncoBOT
#
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)
proud mason
green hinge
#

I want to use some commands as slashcommand and some as prefixcommand. But no command should be both.

proud mason
green hinge
mossy holly
#

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 πŸ˜„

silver moat
#

you would use a context manager for open/closing

mossy holly
silver moat
#

yes

mossy holly
#

Ok thanks a lot ! So my approach is the good one then ? (i.e each time the method is called, I do it)

mossy holly
# silver moat yes

(and maybe stupid question: does context manager work with coroutines ?)

mossy holly
# silver moat `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)

silver moat
#

pardon, I don't use sqlite or any sql lib.

mossy holly
#

and with await database.init_bd() as conn: raises: AttributeError: __enter__

silver moat
#

but shouldn't it just be

async with database.init_bd() as conn:
```?
mossy holly
silver moat
#

k

calm plume
#

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

silver moat
#

the option should follow the command decorator, not before it

green hinge
#

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)```
full basin
#

Subclass the button instead?...

thorny kindle
#

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.

thorny kindle
#

Nah, it went on about self.<thing>

#

It doesnt really have a format it seems.

young bone
#

did you send it with embed=embed?

thorny kindle
#

Ive not tried it yet lol. Im not sure how to make one yet, The docs are confusing me.

green hinge
# full basin Subclass the button instead?...

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")```
full basin
#

Subclass the button

#

Paginator.add_button takes a button

#

Kinda obvious it does

green hinge
#

I'm on the fence right now and don't know what solution you want to push me towards 😬

full basin
#

Subclass
The
Button

#

Not a view

green hinge
# full basin Subclass The Button
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'

πŸ€” πŸ™„
sour tapir
#

Hello, where do I get the code that is placed at the end of the codes, press Enter to close the tool

full basin
#

What

grizzled sentinel
green hinge
#

Because it is an extra button and has nothing to do with the Navigarion of the Paginator?

grizzled sentinel
#

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

green hinge
grizzled sentinel
#

I think so, thb I have never used paginator. But thats how it looks like it would be done by the docs

green hinge
finite flame
#

how to send message in a specific channel

grizzled sentinel
#

.rtfm TextChannel.send

winter condorBOT
finite flame
#

thanks πŸ‘

green hinge
#

Ah here is the solution ☝🏻

view = discord.ui.View(SpotDetails(self.bot),)
        paginator = Paginator(pages=pages, timeout=None, custom_view=view)```
fossil mulch
#

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

fallen cove
#

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)
finite flame
#
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

ebon drift
#

The IDE I am using PyCharm is looking for a discord module and not pycord

grizzled sentinel
grizzled sentinel
#

?tag install

obtuse juncoBOT
#
  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

fallen cove
# grizzled sentinel It has something to do with your overwrites. Can you send the code for that.
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),
        }```
grizzled sentinel
fallen cove
fallen cove
#
NFFC_category = discord.utils.get(guild.categories, name="NFFC")
print(NFFC_category)
#

guild = interaction.guild

grizzled sentinel
finite flame
grizzled sentinel
#

If you send the view instead of message it will work to

ebon drift
#

How do I make it were my bot does not close it self after someone tried to use a command that does not exist

grizzled sentinel
#

That should be built into pycord. Can you show the code and error

ebon drift
#

Yes one sec

#

Do you want me to send all of my code

grizzled sentinel
#

sure. Put it in the past bin and make sure you dont show your token

#

?tag paste

obtuse juncoBOT
ebon drift
#

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

grizzled sentinel
#

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

ebon drift
grizzled sentinel
#

Can you show pip list

ebon drift
#

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

grizzled sentinel
# ebon drift

Check out this section of the guide and this persons example

ebon drift
#

Ok

grizzled sentinel
grizzled sentinel
# ebon drift Ok

You would need to use on_error as the event and commands.CommandNotFound in the isinstance.

ebon drift
#

I will try that

ebon drift
#

I just tested the slash commands and it works but discord says "The application did not respond" after the command worked

full basin
#

Did you respond with ctx.respond

ebon drift
#

No

full basin
#

There's your issue

ebon drift
#

I will try that

ebon drift
#

I tried that but it's giving me errors

limber urchin
#

The error literally tells you what's wrong

ebon drift
#

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

limber urchin
#

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

ebon drift
#

Ok I will try to fix the code

dusk burrow
#

is there anyway currently to check if a reaction is a super reaction

limber urchin
#

No

frank lava
#

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...
limber urchin
#

That means your bot is trying to register commands in a guild it's not in

frank lava
#

but the guild id in my config file is correct...

limber urchin
#

And how are you using that id?

frank lava
#

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.

calm plume
#

and now the choices don't show

#

this is tranformed into a list of strings btw list(roles.keys())

#

nvm

#

i found it

graceful mason
#

how do I add callbacks to buttons added by add_item?

full basin
green hinge
#

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)```
thorny pasture
#

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.

blissful hazel
blissful hazel
young bone
green hinge
#

Can I send a select menu with a pre-selection?

thorny kindle
#

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.

green hinge
#

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)```
thorny pasture
#

With this error: Application Command raised an exception: TypeError: object BanIterator can't be used in 'await' expression'

thorny kindle
#

Ok.

grizzled sentinel
# green hinge I want to add another select menu to the view but I want to keep the previous se...

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

green hinge
#

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?

grizzled sentinel
#

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

green hinge
# grizzled sentinel https://docs.pycord.dev/en/master/api/ui_kit.html#discord.ui.Select.values I thi...

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.
thorny pasture
green hinge
grizzled sentinel
#

Yeah it should be simple with a try/except

green hinge
green hinge
grizzled sentinel
#

I think it would just be self.add_item(select) than edit the original response

stark walrus
#

What's the event name/rtfm link to the event which triggers when an audit log entry is passed in the guild

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

grizzled sentinel
#

.rtfm on_audit

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

grizzled sentinel
#

.rtfm on_

grizzled sentinel
green hinge
# grizzled sentinel I think it would just be `self.add_item(select)` than edit the original response

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)```
grizzled sentinel
#

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

proud mason
#

You can remove the existing select menu and add the next one?

grizzled sentinel
#

They want the old one to stay

green hinge
#

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)```
proud mason
green hinge
# proud mason 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})```
proud mason
green hinge
green hinge
# proud mason it will be created separately for each time `SpotDetails` button is created

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})```
proud mason
#

thats some basic OOP

proud mason
#

it depends on your UI flow

green hinge
proud mason
#

when do you create SpotDetails ?

#

do you create the button inside a command?

proud mason
green hinge
# proud mason when do you create `SpotDetails` ?

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.

green hinge
proud mason
#

ah

proud mason
#

then yes, init is a good way

green hinge
proud mason
green hinge
proud mason
#

i believe it should be deleted automatically by python garbage collection, once the view is deleted

green hinge
green hinge
#

When I edit a respons, does it count new 15 minutes or does the previous time remain?

worldly schooner
#

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

proud mason
#

.guide

winter condorBOT
proud mason
#

See the creating your first bot part

#

That does you how to listen to events

worldly schooner
#

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!

green hinge
#

There is no possibility to extend the interaction.respons time or?

obtuse juncoBOT
#

dynoError No tag defer found.

green hinge
green hinge
green hinge
silver moat
green hinge
silver moat
green hinge
silver moat
#

if you put like 3600, then the button would time out in an hour.

worldly schooner
# silver moat what?

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

green hinge
calm plume
#

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

full basin
#

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

proud mason
proud mason
#

.partial

winter condorBOT
#

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. 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:")
calm plume
young bone
#

what?

calm plume
#

like what kind of benifit do they give me i don't understand

proud mason
# calm plume are they faster and have 0 rate limits?

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

calm plume
#

so just a decrease in memory?

#

with the cost of no attributes

proud mason
#

Really useful if you store channel or message ids in a db

calm plume
proud mason
#

That's not what I meant

calm plume
#

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

proud mason
# proud mason Really useful if you store channel or message ids in a db

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 πŸ’€

proud mason
calm plume
#

ok

#

thanks i understood

green hinge
# green hinge That means I can send an ephemeral message as respons to a user and this message...

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)```
calm plume
#

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

worldly schooner
#

how do I change the activity of the bot?

calm plume
#

i think

calm plume
green hinge
worldly schooner
calm plume
calm plume
#

like it may seem online all the time but is there a sudden close for small time and then goes online back

green hinge
# calm plume i say if the bot gets restarted

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.

calm plume
green hinge
calm plume
green hinge
wintry cosmos
#

How customizable are linked roles? Does anyone have created their own requirements yet?

finite flame
#

can i get some examples of working with embeds

mossy holly
#

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 πŸ˜„

proud mason
proud mason
proud mason
#

yes thats possible

errant craneBOT
#

Here's the slash cog groups example.

proud mason
#

like this

mossy holly
mossy holly
#

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)

green hinge
worldly schooner
#

nvm found out

reef ore
#

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?

full basin
reef ore
#

just not receiving an event when timeouting a user

worldly schooner
#

I guess I'm not doing it right

reef ore
#

@commands.Cog.listener()
async def on_member_update(self, before: discord.Member, after: discord.Member):
# check if time out
LOG.info("member update received!")

reef ore
full basin
#

Show where you defined the intents

#

Are any other listeners not triggering

reef ore
#

everything is triggering

#

and this one too, just not on timeout

proud mason
full basin
#

Thonk

proud mason
mossy holly
proud mason
green hinge
# proud mason Pretty sure that's a discord limitation

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.

proud mason
#

πŸ’€

proud mason
#

Is that what you are trying?

proud mason
#

Paginator in a subclass?

#

Subclass of what?

#

View?

reef ore
green hinge
mossy holly
proud mason
proud mason
errant craneBOT
#

Here's the slash cog groups example.

proud mason
#

See that

reef ore
proud mason
graceful mason
proud mason
graceful mason
#

(I don't know how to start)

errant craneBOT
#

Here's the button roles example.

green hinge
proud mason
mossy holly
# errant crane Here's the slash cog groups example.

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 ?

graceful mason
#

Oh, I see now

proud mason
#

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?

proud mason
mossy holly
#

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

proud mason
proud mason
proud mason
green hinge
# proud mason Ah so just use paginator.respond ?

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)```
mossy holly
#

did it like this

worldly schooner
#

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

proud mason
worldly schooner
#

but what I really want is with guild

proud mason
green hinge
mossy holly
# proud mason Full error?
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'
mossy holly
proud mason
proud mason
#

Np lol

proud mason
mossy holly
proud mason
#

Try if bot.fetch_guild works

proud mason
#

.partial

winter condorBOT
#

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. 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:")
worldly schooner
median ridge
#

How do I add a role to a member object by using the role id?

green hinge
green hinge
median ridge
#
- How do I add a role to a member object by using the role id?