#Basic Pycord Help (Quick Questions Only)

1 messages · Page 61 of 1

green hinge
#
role = ctx.guild.get_role(810264985258164255)
await user.add_roles(role)```
mossy holly
#

Quick question (again, hope this time it's really a quick one lmao), is default_member_permissions = discord.Permissions(administrator=True) supposed to make the command visible only by admins ?
Because a non-admin can see it and execute it

median ridge
green hinge
median ridge
worldly schooner
median ridge
#

why is it "remove_roles" in plural if you only remove one?

worldly schooner
#

ask God

green hinge
worldly schooner
#

It really doesnt make sense since you can only remove 1 role each (command) I think

green hinge
mossy holly
worldly schooner
#

Is there a way to add a emoji to a bot status?

#

like user status emojis

green hinge
mossy holly
#

ok it's discord.ext.commands, but if the user doesn't have the permission it outputs an error on the console (not to the user, he just sees that the app doesn't respond)

green hinge
mossy holly
#

I'll just handle it inside the function via ctx.author.guild_permissions.administrator it'll be easier

worldly schooner
median ridge
#

Why

Traceback (most recent call last):
  File "e:\Einar\Programming\Testing\chiz\Cheeese\src\main.py", line 9, in <module>
    from discord.ext import commands
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)   
graceful mason
#

How can I disable a button? I am trying self.children[-1].disabled = True but idk

green hinge
#

I send my Paginator to another channel, that works so far. But why do the buttons not work and I always get "interaction failed"?

    async def callback(self, interaction: discord.Interaction):
        Channel_ID = 1079779225847992411
        channel = self.bot.get_channel(Channel_ID)
        context = await self.bot.get_context(interaction.message, cls=commands.Context)
        context.channel = channel
        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(SpotDownvote(self.bot))
        view.add_item(SpotUpvote(self.bot))
        paginator = Paginator(pages=pages, timeout=None, custom_view=view)


        await paginator.send(context)```
graceful mason
#

How to silently respond to an interaction? Without any message displaying

green hinge
stuck kite
#

How do I enable application slash commands on other servers. I have application slash commands on one of my servers but the other two servers don’t show application slash commands. The bot has been active on the server for 15 hours.

green hinge
alpine kernel
#

Mmm i think application slash commands are on by default, are you sure the bot is connected to those servers? have you tried restarting discord or doing Ctrl+R?

#

enabling 'slash commands' in the dev portal permissions is to allow bots to USE slash commands i believe

#

Now for my question: Isn't there a way to hide application slash commands from showing up on the autocomplete if they dont meet checks? I thought I saw that in the documentation but cant find it now =T

silver moat
stuck kite
silver moat
ebon drift
#

How do I make bot owner only commands

silver moat
ebon drift
#

I will take a look at it

ebon drift
# silver moat https://docs.pycord.dev/en/master/ext/commands/api.html#discord.ext.commands.is_...

I tried it and gotten this error
Ignoring exception in command ctl:
Traceback (most recent call last):
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\core.py", line 942, in invoke
await self.prepare(ctx)
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\core.py", line 858, in prepare
raise CheckFailure(
discord.ext.commands.errors.CheckFailure: The check functions for command ctl failed.

lethal hare
#

Is there still no way to set a custom bot status/presence ?

limber urchin
#

If you mean fully custom, no

silver moat
lethal hare
silver moat
#

.rtfm bot.change

silver moat
#

those

lethal hare
#

Yeah so, Im doing that

#
activity = discord.Activity(type=discord.ActivityType.custom, state=f"{numBolts}/{totalBolts} bolts collected")
bot = discord.Bot(intent=intents, activity=activity, status=discord.Status.online)
limber urchin
#

Bots can't use the custom activity type

lethal hare
#

Thats what I was asking about originally

#

I dont want "Listening to" or "Watching"

#

etc

limber urchin
#

Well you have to

#

No workaround

silver moat
#

You can use Playing

lethal hare
#

That was included in the etc but it might be my best bet I guess

silver moat
waxen whale
#

🤣

ebon drift
#

I am trying to make code that prints out the user's name that uses the owner-only commands but I get this error instead
Ignoring exception in command restart:
Traceback (most recent call last):
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\core.py", line 942, in invoke
await self.prepare(ctx)
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\core.py", line 858, in prepare
raise CheckFailure(
discord.ext.commands.errors.CheckFailure: The check functions for command restart failed.
My code is in the txt

silver moat
#

The await isn't necessary

ebon drift
#

Oh ok

silver moat
#

wait nvm I'm dumb

ebon drift
#

So I still need it

silver moat
#

what's wrong with just using ```py
@commands.is_owner()

ebon drift
#

I had no clue why my code did not work so I did not try that

stuck kite
young bone
ebon drift
#

Yes

young bone
#

why do you have a member event without member intents?

ebon drift
#

🤦

silver moat
young bone
#

ok

waxen whale
silver moat
ebon drift
young bone
#

on_guild_member_remove that is not an event? I cannot see anything like that at the docs

silver moat
waxen whale
#

Just try and see lol

young bone
#

^

ebon drift
#

I just now found this it has to be defined in the module, not the code it self

young bone
#

if you use "is_owner" it will be already an owner command...

silver moat
#

if you want to just keep it simple, then just hardcode your ID in.

ebon drift
#

Does it work under
bot = bridge.Bot(command_prefix='*', intents=intents, help_command=commands.DefaultHelpCommand(), owner_id=668445956001234944)

young bone
#

if you use commands.is_owner yes

ebon drift
#

Ok

young bone
ebon drift
#

I did but I think I read the wrong part

ebon drift
#

I think I miss looked at this part in the docs
def is_owner():
async def predicate(ctx):
return ctx.author.id == 316026178463072268
return commands.check(predicate)

@bot.command(name='eval')
@is_owner()
async def _eval(ctx, *, code):
"""A bad example of an eval command"""
await ctx.send(eval(code))

#

Thinking I could change the is_owner part

young bone
#

py-cord is already doing that for you...

#

I found that one in 10 seconds

silver moat
ebon drift
#

Is there a way to make it use the print function to say who used the command instead of
Ignoring exception in command restart:
Traceback (most recent call last):
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\core.py", line 942, in invoke
await self.prepare(ctx)
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\core.py", line 857, in prepare
if not await self.can_run(ctx):
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\core.py", line 1198, in can_run
return await discord.utils.async_all(predicate(ctx) for predicate in predicates) # type: ignore
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\utils.py", line 701, in async_all
elem = await elem
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\core.py", line 2285, in predicate
raise NotOwner("You do not own this bot.")
discord.ext.commands.errors.NotOwner: You do not own this bot.

silver moat
ebon drift
#

Will that stop it from showing the whole error

silver moat
lime lichen
#

hey im getting 404 errors for 3 - 5 seconds of command send to reply sent time, is this just because the interaction times out?

cyan quail
#

defer

lime lichen
#

i should have specified, its a response, not a reply. i defer with all my commands first, sometimes my pc just lags

#

so it is the defer that is the initial response and therefore the source of the error

cyan quail
#

ah so it's taking you 3+ seconds to defer?

lime lichen
#

defer is the 6th line of code for every command

#

first others are for logging purposes, local only

#

they access an SQL database so i seriously doubt it takes so long to defer, thats why i think its just my pc lagging

cyan quail
#

just in case, could you make the defer first anyway?

lime lichen
#

but i just want to know if an interaction actually times out in 3 - 5 seconds

cyan quail
#

it does yes

#

which is why you have to defer in those first 3 seconds

lime lichen
cyan quail
#

can't do much else then, unless you're running blocking code/libraries elsewhere in the bot

lime lichen
#

darn alright, my pc has one of those plugin-recivers for wifi so ill try to figure something out for that

#

thanks for your help kind fellow

silver moat
#

is your SQL database in any chance non-async?

limber urchin
#

If you're hosting your database on your local machine, WiFi has nothing to do with that.

proud mason
#

See the partial channel example 2 message above your message.
You would do paginator.send(bot.get_partial_messageable(id))

get_channel works too

proud mason
graceful mason
#

Hi I have a question, does the persistent view works if I add buttons dynamically? (they're not defined using @ syntax)

#

If not, how can I make it work?

silver moat
graceful mason
#

Thanks

graceful mason
#

uh but it says I have to add it on on_ready: bot.add_view(MyView()) and I can't do that, because my view needs arguments passed to its constructor, what to do?

limber urchin
#

Pass the arguments to the constructor then

graceful mason
#

But I can't do that on bot initialization, they are arguments that have input from the player, when he uses the command

limber urchin
#

How are you going to have a persistent view if the view requires user input??

graceful mason
#

I am saving input in a database

#

Only need the buttons active

limber urchin
#

Then read it from the database?

graceful mason
#

oh well, technically

#

thanks

gleaming falcon
#

Gah. How can I work around "circular references"? I have a Cog that calls a View and want to split out my related View classes into another file.

So the Cog has

# commands/mycog.py
from views.MyView import TransactionConfirmationView

And I'm typehinting my referenced cog passed into the View constructor so it can access other parts of the bot

# views/MyView.py
from commands.mycog import MyCog

.... python does not like this. How should I structure my imports so that everything plays nice ?

proud mason
#

this is the standard way to avoid circular imports arising from type hinting

#

even py-cord does it in almost every file

green hinge
# proud mason See the partial channel example 2 message above your message. You would do `pag...

When I try like this:

await paginator.send(self.bot.get_partial_messageable(Channel_ID))```
I receive this error message:

Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/ui/view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "/home/Bot/Bot/cogs/showspot.py", line 266, in callback
await paginator.send(self.bot.get_partial_messageable(Channel_ID))
File "/usr/local/lib/python3.8/dist-packages/discord/ext/pages/pagination.py", line 973, in send
raise TypeError(f"expected Context not {ctx.class!r}")
TypeError: expected Context not <class 'discord.channel.PartialMessageable'>

proud mason
#

i think i can make a fix

#

oh well not sure now

#

as for now, you need to pass context and a target

green hinge
green hinge
# proud mason as for now, you need to pass context and a target

I have tried it this way, the paginator is also sent to the channel but the buttons do not work then.

    async def callback(self, interaction: discord.Interaction):
        Channel_ID = 1079779225847992411
        channel = self.bot.get_channel(Channel_ID)
        context = await self.bot.get_context(interaction.message, cls=commands.Context)
        context.channel = channel
        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(SpotDownvote(self.bot))
        view.add_item(SpotUpvote(self.bot))
        paginator = Paginator(pages=pages, timeout=None, custom_view=view)


        await paginator.send(context)```
proud mason
#

rather than setting ctx.channel , pass it to target

green hinge
proud mason
green hinge
proud mason
#

unless you set author_check to False

proud mason
green hinge
#

Okay that solved my problem

author_check=False```
green hinge
# proud mason yes do this ^

Can I also put the whole thing in a class so I can edit it via edit_original_response(view=view)?

 async def callback(self, interaction: discord.Interaction):
        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
        new_view = SpotVoteButtonsView(self.bot, self.message_details)
        paginator = Paginator(pages=pages, timeout=899 ,custom_view=new_view, author_check=False)
        await paginator.respond(interaction, ephemeral=True)```
green hinge
# proud mason wdym?

I have a Custom_View with 2 buttons.
When I click one of these two buttons, both buttons should deactivate.
For this I wanted to edit the Respons and decide with the if query accordingly whether the buttons are enabled or disabled.

class SpotVoteButtonsView(discord.ui.View):   
    def __init__(self, bot: discord.Bot, message_details):
        self.bot = bot
        self.message_details = message_details
        super().__init__(timeout=None)
    

        if self.message_details[0]['votebuttoncheck'] == 'False':
            self.add_item(SpotUpvoteButton(self.bot, self.message_details, disabled=False))
        else:
           self.add_item(SpotUpvoteButton(self.bot, self.message_details, disabled=True))
        if self.message_details[0]['votebuttoncheck'] == 'False':
           self.add_item(SpotDownvoteButton(self.bot, self.message_details, disabled=False))
        else:
            self.add_item(SpotDownvoteButton(self.bot, self.message_details, disabled=True)) ```
#

So the two buttons and the Custom_View have been added to the Paginator:

new_view = SpotVoteButtonsView(self.bot, self.message_details)
paginator = Paginator(pages=pages, timeout=899 ,custom_view=new_view, author_check=False)```
#

Can I edit only the view of the 2 buttons or do I have to edit the whole respons with the whole paginator?

#

Count the number of members

ctx.guild.members```
#

Try and see

green hinge
# proud mason wdym?

Okay just edit the view from the buttons doesn't work so I have to edit the whole message with the paginator .
How can I write the paginator now in a subclass, so that I can call and create it in the callback function and edit it in the callback function via edit_original_response?

#

I have imagined a class like the buttons only for the Paginator

class Button(discord.ui.Button):```
cyan quail
green hinge
cyan quail
#

more or less yeah

green hinge
# cyan quail more or less yeah

If I create the class like this, how can I put my paginator in there?

class PaginatorView(discord.ui.View):   
    def __init__(self, bot: discord.Bot):
        self.bot = bot
        super().__init__()```
cyan quail
#

wait no

#

don't inherit from View, inherit from Paginator

green hinge
# cyan quail wait no

How do I do it?

class Paginator():   
    def __init__(self, bot: discord.Bot):
        self.bot = bot
        super().__init__()

         #Code for Pages

        view = discord.ui.View(TestView(self.bot))
        paginator = Paginator(pages=pages, timeout=None, custom_view=view, author_check=False)


        await paginator.send(ctx)
cyan quail
#

no...

#

Paginator is already a view, so you inherit from Paginator instead of discord.ui.View

#

when you do that, self would be your paginator variable and you would put your arguments like pages, custom_view etc. into super().init__(...)

green hinge
# cyan quail when you do that, `self` would be your `paginator` variable and you would put yo...

Okay but I can't just paste the whole thing into the super().init__(...)?

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

man...

#

think about it like this

#
paginator = Paginator(pages=pages, timeout=None, custom_view=view, author_check=False)```would be the same as```py
class PaginatorView(discord.ui.View):   
    def __init__(self):
        super().__init__(pages=pages, timeout=None, custom_view=view, author_check=False)

paginator = PaginatorView()
#

but the 2nd example is incomplete; pages and view aren't actually defined yet

#

there are two ways to approach this:

  • define them inside __init__ using some functions to create them```py
    class PaginatorView(discord.ui.View):
    def init(self):
    pages = self.generate_pages()
    view = discord.ui.View(...)
    super().init(pages=pages, timeout=None, custom_view=view, author_check=False)

    def generate_pages(self):
    pages = [...]
    return pages

paginator = PaginatorView()

- add arguments to `__init__` and pass them in```py
class PaginatorView(discord.ui.View):   
    def __init__(self, pages, custom_view):
        super().__init__(pages=pages, timeout=None, custom_view=view, author_check=False)

pages = [...]
view = discord.ui.View(...)
paginator = PaginatorView(pages, view)
green hinge
#

Okay I try to understand

green hinge
# cyan quail there are two ways to approach this: - define them inside `__init__` using some ...

Did I understand that correctly?

class PaginatorView(discord.ui.View):   
    def __init__(self):
        pages = self.generate_pages()
        view = discord.ui.View(...)
        super().__init__(pages=pages, timeout=None, custom_view=view, author_check=False)

    async def generate_pages(self):
        SPOTS_PER_PAGE = 6
        data = await dab.get_all_spots()
        pages = []
        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)
        return pages
    
    async def generate_view(self):
        view = SpotVoteButtonsView(self.bot, self.message_details)
        return view```
And so I can then call it up somewhere else?
```py
paginator = PaginatorView()
await paginator.respond(interaction, ephemeral=True)```
cyan quail
green hinge
cyan quail
#

yeah that'd be fine

#

oh though

#

if you want self.bot, you need to add the bot argument to your Paginator class and define it

#

just like you have in any other classes with bot

worldly schooner
#

How does the bot emoji reacts with a custom emoji?

green hinge
# cyan quail yeah that'd be fine

Do I need to make the init async so I can use await there right?

pages = self.generate_pages()```

TypeError: init() got an unexpected keyword argument 'pages'
/usr/local/lib/python3.8/dist-packages/discord/ui/view.py:416: RuntimeWarning: coroutine 'PaginatorView.generate_pages' was never awaited
return await self.on_error(e, item, interaction)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
/usr/local/lib/python3.8/dist-packages/discord/ui/view.py:416: RuntimeWarning: coroutine 'PaginatorView.generate_view' was never awaited
return await self.on_error(e, item, interaction)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

worldly schooner
#

like does it need the name of the emoji (with id)? or just the emoji id

cyan quail
cyan quail
green hinge
cyan quail
#

hmm

#

kinda jank but you could generate it before and pass it through __init__

green hinge
# cyan quail kinda jank but you could generate it before and pass it through `__init__`

Why?
TypeError: init() got an unexpected keyword argument 'custom_view'

class PaginatorView(discord.ui.View):   
    async def __new__(cls, *args, **kwargs):
        obj = super().__new__(cls)
        await obj.__init__(*args, **kwargs)
        return obj
    
    async def __init__(self, bot: discord.Bot, message_details):
        self.bot = bot
        self.message_details = message_details
        pages = await self.generate_pages()
        view = await self.generate_view()
        super().__init__(pages, custom_view=view, timeout=None, author_check=False)```
cyan quail
worldly schooner
cyan quail
# worldly schooner

seems to be working fine for me, are you sure the bot has access to the emoji and that's the exact name?

green hinge
cyan quail
#
from discord.ext.pages import Paginator
class PaginatorView(Paginator):
worldly schooner
graceful mason
#

Hii, persistent views are sometimes randomly not working for me. Is it possible to just manually create the views and reattach them to messages?

green hinge
worldly schooner
#

the bot is in the server with the emoji yes

cyan quail
#

what's your issue

graceful mason
#

sometimes after 5th restart, sometimes after 1st etc

cyan quail
#

are you sure you're re-adding it correctly on startup

graceful mason
#

I think so, but I'll check

graceful mason
green hinge
# cyan quail ```py from discord.ext.pages import Paginator class PaginatorView(Paginator): ``...

Now if I want to cache the paginator and then edit it. How can I do that?

paginator = await PaginatorView(self.bot, self.message_details)
        spotdetails = await paginator.respond(interaction, ephemeral=True)
        self.message_details[1]['spotdetails'] = spotdetails```
Is that how it works?
```py
await self.message_details[1]['spotdetails'].edit_original_response(view=await PaginatorView(self.bot, self.message_details))```
green hinge
# cyan quail give it a go i guess?

Hmm

  File "/usr/local/lib/python3.8/dist-packages/discord/ui/view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "/home/Bot/Bot/cogs/showspot.py", line 94, in callback
    await self.message_details[1]['spotdetails'].edit_original_response(view=await PaginatorView(self.bot, self.message_details))
AttributeError: 'InteractionMessage' object has no attribute 'edit_original_response'```
green hinge
cyan quail
#

maybe work the other way

#

there should be paginator.edit

green hinge
worldly schooner
#

strange

graceful mason
cyan quail
graceful mason
cyan quail
#

and you can optionally pass in a message object (which could be a PartialMessage to limit it there)

#

recieve interaction > find matching custom id > run

graceful mason
#

hm I see, thanks

#

now I know how to replicate it (since the builtin doesn't work for me)

green hinge
# cyan quail there should be `paginator.edit`

If I try it this way then the embed from the paginator is still shown, the two extra buttons (vote buttons) are also edited and disabled but the buttons from the paginator itself to browse are still gone 🤔

await self.message_details[1]['spotdetails'].edit(view=SpotVoteButtonsView(self.bot, self.message_details))```
cyan quail
green hinge
# cyan quail what specifically are you trying to edit on the message

I have the Paginator. This has yes the 5 standard buttons to change page etc..
Below that I have 2 extra buttons that I add via the custom_view.
If I now press one of these two buttons I want the custom buttons to disable themselves.
So only the buttons have to be edited or updated.

cyan quail
#

and these buttons have callbacks?

#

hmmm

green hinge
# cyan quail and these buttons have callbacks?

Yes

class SpotUpvoteButton(discord.ui.Button):
    def __init__(self, bot: discord.Bot, message_details, disabled):
        self.bot = bot
        self.message_details = message_details
        super().__init__(
            label='Spot Upvote',
            style=discord.ButtonStyle.green,
            custom_id='spotupvote',
            disabled=disabled,
        )

    async def callback(self, interaction: discord.Interaction):
        self.message_details[0]['votebuttoncheck'] = 'True'
        await interaction.response.send_message('Super', ephemeral=True)
        await self.message_details[1]['spotdetails'].edit(view=SpotVoteButtonsView(self.bot, self.message_details))```
#

This is the view of the buttons

class SpotVoteButtonsView(discord.ui.View):   
    def __init__(self, bot: discord.Bot, message_details):
        self.bot = bot
        self.message_details = message_details
        super().__init__(timeout=None)

        if self.message_details[0]['votebuttoncheck'] == 'False':
            self.add_item(SpotUpvoteButton(self.bot, self.message_details, disabled=False))
        else:
           self.add_item(SpotUpvoteButton(self.bot, self.message_details, disabled=True))
        if self.message_details[0]['votebuttoncheck'] == 'False':
           self.add_item(SpotDownvoteButton(self.bot, self.message_details, disabled=False))
        else:
            self.add_item(SpotDownvoteButton(self.bot, self.message_details, disabled=True)) ```
cyan quail
#

so the moment you use custom_view, the original view is more or less irrelevant because the items from custom_view are transferred to the Paginator

#

honestly

#

hmmmm

#

wait

#

ehhhhh

cyan quail
green hinge
cyan quail
#

idk if it'd work but give it a try

#

actually

green hinge
# young bone For what do you need the bot?

I create a paginator that should have 2 vote buttons. When I click on a vote button I want to vote the page of the paginator.
The buttons should be disabled after they have been pressed so that you can not vote 5x.

cyan quail
#

this is incredibly scuffed, but you could assign paginator inside SpotUpvoteButton and go through that

green hinge
cyan quail
#

well it just looks stupid

#

let's see

#

actually it isn't that bad

#

inside Paginator we have generate_view; first, we assign the attribute herepy async def generate_view(self): view = SpotVoteButtonsView(self.bot, self.message_details) view.paginator = self return view

#

now every Item, including Button, has a view attribute to access the parent view

#

so inside your button callback you can access self.view.paginator

#

so to disable, you would go self.view.paginator.custom_view.disable_all_items()

proud mason
#

This Fabian person has the most complicated View setups ive seen lmao

cyan quail
#

probably

#

idfk paginator is so cursed

worldly schooner
#

@cyan quail I'm a complete dumbass

cyan quail
#

nice

worldly schooner
#

I was getting the MESSAGE ID

cyan quail
#

LOL

worldly schooner
#

instead of the emoji

cyan quail
#

you can always get the full emoji <name:id> with a backslash \

worldly schooner
#

yeah I forgot about that and I was getting with right click in the emoji

cyan quail
#

rip

worldly schooner
green hinge
cyan quail
#

well i meant from the button callback

#

if you're doing it inside paginator then it's just self.custom_view.disable_all_items()

green hinge
#

If I use it like this in the button callback, the buttons are taken out completely and the paginator still works.

self.view.custom_view.disable_all_items()
        await self.view.update()```
cyan quail
#

man

#

this is so painful

green hinge
#

I think this is good, the important thing is that the buttons can no longer be pressed. Whether they are now gone or only disabled is not so important

worldly schooner
#

is there a way to set a eternal interaction button?

errant craneBOT
#

Here's the persistent example.

worldly schooner
#

thx

green hinge
flat kite
#

How do I check if the message has been flagged my automod?

ornate current
#
msg = discord.utils.get(history, id=1080135333842272298)
button1 = discord.utils.get(msg.components[0].children, label="Claim Invite Rewards")
button1.callback = callbackfunction

says button does not have the attribute callback

young bone
#

where is the async function?

dry gazelle
#

Hey if you are around, I implemented the producer / consumer queue and it broke still :/

proud mason
#

how long did you wait for?

dry gazelle
#

0.5 second

dry gazelle
#

I am still getting the unknown interaction on the interaction.response.defer() call because the traffic is so high

#

we get like probably 200 people clicking the button in the span of 2 seconds and probably 400-1000 over the first 20 seconds

#

and then getting rate limited agian trying to send follow up messages

#

I even tried to rate limit my own button by using a counter that increments when an interaction happens, then respond and say traffic high wait 10 seconds, but even the response message is getting blocked for some reason too

ornate current
young bone
ornate current
#

Above

young bone
#

you have to set the button.callback under the async func

proud mason
gleaming falcon
proud mason
#

do you use those things at runtime? like create objects using the class? or it is only for ide typehinting?

gleaming falcon
uncut current
#

can I use one SlashCommandGroup in different files (cogs)?

cyan quail
uncut current
cyan quail
#

discord cache sucks

uncut current
#

ohh man, ty

#

ty, that should help me

lost hare
#

Which is the latest Python Version which works with Pycord?

full basin
#

3.11 iirc

grizzled sentinel
#

@fervent cradle
Yes but you can not have must customization so it is not recommended.

fervent cradle
#

ok!

lost lodge
#

Hello guys, is there anyway to run a command as the bot?

novel jay
#

what?

full basin
#

what

#

Bots can't use slash commands

lost lodge
#

and prefixed?

green hinge
#

How can I make my Paginator persistent?
Does it work the same way with Paginator?

class Base(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.persistent_views_added = False

    @commands.Cog.listener()
    async def on_ready(self):
        if not self.persistent_views_added:
            self.bot.add_view(PaginatorInfoView())
            self.persistent_views_added = True

    @commands.command(name="showspot", help="Zeigt alle Spots an")
    async def page(self, ctx):
        paginator = await PaginatorInfoView(self.bot)
        await paginator.send(ctx)

class PaginatorInfoView(Paginator):   
    async def __new__(cls, *args, **kwargs):
        obj = super().__new__(cls)
        await obj.__init__(*args, **kwargs)
        return obj
    
    async def __init__(self, bot: discord.Bot):
        self.bot = bot
        pages = await self.generate_pages()
        view = await self.generate_view()
        super().__init__(pages=pages, custom_view=view, timeout=899, author_check=False)

    async def generate_pages(self):
        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)
        return pages

    async def generate_view(self):
        view = SpotDetails(self.bot)
        return view```
lost lodge
#

Hello, I have the problem that when I want to get the top_role of a member, there are unnecessary roles in the way. How can I exclude these roles from top_role?

full basin
lost lodge
lost lodge
full basin
full basin
#

Show code

lost lodge
lost lodge
dry gazelle
full basin
green hinge
#

How can I check the interaction message if it is still available and if not an error should be displayed?
Unfortunately it does not work like this...

paginator_message = await paginator.respond(interaction, ephemeral=True)

try:
   await paginator_message.delete()
except Exception as e:
   print(e)```
gleaming falcon
# proud mason if it is only for the sake of typehinting, import it like so ```py from typing i...

Damn. I'm still having some trouble with this, if you don't mind me picking your brain more..

Failed to load extension commands.gnosis. Extension 'commands.gnosis' raised an error: NameError: name 'Gnosis' is not defined
# cogs/Gnosis.py
from views.Multisig import TransactionConfirmationView

class Gnosis(commands.Cog):
    ...
# views/Multisig.py
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from commands.gnosis import Gnosis

class TransactionConfirmationView(discord.ui.View):
    def __init__(self, cog: Gnosis, callback: callable, txn_data: BeefyTransferProposal, nonce_list: list[PendingTransaction]):
       ...

NameError: name 'Gnosis' is not defined

I don't get why the Cog was throwing the first error; it shouldn't need to care.

gleaming falcon
#

Because that was recommended to me to avoid circular references.

#

The View constructor accepts the Cog, and want to be able to autocomplete from within my view classes. But because the Cog references the View and the View references the Cog, python gets angry

gleaming falcon
#

My cog sends a View. I was hoping to have my View in a separate file
But as stated, my View accepts the Cog as a constructor argument so I can reference methods within (including the bot instance itself)

So the question is how to allow them to both reference each other for development purposes so that I can separate the view from the cog

gleaming falcon
#

Is this where you would use a string as the type? e.g.

def __init__(self, cog: "Gnosis"...)
fervent cradle
#

There was such a problem. I wrote a modal window, everything works, but I really don't like one thing. When I press the send button, the window should close, well, it doesn’t close, it says something happened, but everything works. Needed when clicking the submit button, the modal window was closing

#

Please help

lime lichen
#

anyone having problems with Pycord?

young bone
lime lichen
#

my bot wont start, package discord not found

young bone
lime lichen
#

tried uninstalling, reinstalling pycord

lime lichen
young bone
lime lichen
#

it just started working again Bruh

#

no idea what is going on

#

maybe a visual studio issue

#

sorry for the trouble

ebon drift
#

How do I make it where in bridge some commands are slash commands and others not

young bone
ebon drift
young bone
#

?tag client

ebon drift
#

So I remove the bridge_ part

#

from @bot.bridge_command

young bone
ebon drift
#

So would that make it into a prefix command

young bone
#

yes

ebon drift
#

Ok

young bone
#

basic prefix command

ebon drift
#

Will it mess with the bridge.Bot for setting up the bot settings

young bone
#

try and see

ebon drift
#

Ok

#

That worked

#

$restart

tough quiverBOT
ebon drift
#

Wrong server

proven mantle
#

I started developing on my old bot and used has_role() but it doesnt exists anymore. What can i use instead?

proven mantle
#

i get this

young bone
cyan quail
#

you're calling the wrong thing

proven mantle
#

oh alr. thx

spice jewel
#

How do I use add_role in buttons, I'm making a verification system with button

young bone
#

^

worldly schooner
#

Is there a way to put a event cooldown something like that?
e.g.: Whenever the people say a keyword my bot sends a message, but I dont want to people spam the keyword and the bot spam the response for the keyword, so I thought on creating an event function to have a certain cooldown, and only activates inside the on_message event if the keyword is said and the cooldown is gone.

ebon drift
#

Is there a way to make a custom help command or to over write the help command for making a custom one

silver moat
spice jewel
worldly schooner
#

lemme get an example

#

nvm

spice jewel
worldly schooner
spice jewel
#

then just create a custom help command

silver moat
young bone
silver moat
silver moat
worldly schooner
spice jewel
#

oh alright

worldly schooner
#

oh wait, i think I will just make one hardcoded

#

with a random number

silver moat
#

or something similar

worldly schooner
#

alr I will look on that

#

thx

silver moat
#

This would go somewhere in your event

bucket = bot.cd_mapping.get_bucket(message)
retry_after = bucket.update_rate_limit()
if retry_after:
    # ratelimited
else:
    # not ratelimited
ebon drift
#

I made an argument for a command to add a second part but how do I make it where it's not needed for every use

silver moat
ebon drift
#

It gave me an error for not using the second argument

silver moat
#

show current code.

ebon drift
#

The whole code or the code with the problem

silver moat
#

whatever code is related to this

ebon drift
young bone
#

:str = None

#

?

ebon drift
#

For action when using the start command it's not used

young bone
#

you can remove the line "file.close()"

silver moat
ebon drift
#

Also removing it there would make problems with python overwriting the file with Write+ permissions and Read permissions would not have anything to read

#

Here is the error it's giving me
Ignoring exception in command games:
Traceback (most recent call last):
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\core.py", line 942, in invoke
await self.prepare(ctx)
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\core.py", line 872, in prepare
await self._parse_arguments(ctx)
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\core.py", line 774, in _parse_arguments
transformed = await self.transform(ctx, param)
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\bridge\core.py", line 94, in transform
return await super().transform(ctx, param)
File "D:\Code\Python\DiaBot\venv\lib\site-packages\discord\ext\commands\core.py", line 601, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: action is a required argument that is missing.

silver moat
#

add another action: str = None

ebon drift
#

Ok

#

Like this?
async def games(ctx, startorplay : str, game : str, action : str = None):

young bone
#
file = open("file.txt", "r")
file.read()
file.close()

or

with open("file.txt", "r") as f:
  data = f.read()
ebon drift
#

Is there a way if the guessing game is played on different servers at the same time to have it were that server has it's own game running

#

Either with txt or databases

silver moat
ebon drift
#

with open('games/number.txt', 'r') as file:

#

Line 8

proud mason
proud mason
gleaming falcon
# proud mason Full error?

Pretty much the full error. But typehinting it as a literal seems to have helped; no more circular import at runtime and the IDE knows what class it is 🎉

raw reef
#

This might be silly. But what on earth is "speedup"? I saw it on the install and have tried to look for what it is but no dice.

silver moat
#

It doesn't actually do anything just by installing it

raw reef
proud mason
grizzled sentinel
#

I am using a bunch of persistent components. Eventually there IDs will start overlapping. How do you all overcome this. Do you add a prefix like moderate? moderate_d9fdgns7

limber urchin
#

Can't you just use a custom id that is unique?

graceful mason
#

what is the max length of a custom_id property?

limber urchin
#

100

graceful mason
#

ok thanks

grizzled sentinel
dry gazelle
proud mason
# limber urchin 100

wait does that means you can have 16^100 combinations of custom ids using only hexadecimal characters? 💀

#

wait even more because "0a" and "a" are different custom ids 💀

spice jewel
#

Quick question how do I fix this
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: View.to_components() missing 1 required positional argument: 'self'

proud mason
spice jewel
#
    @command()
    @has_permissions(administrator = True)
    async def releaseverification(self, ctx: ApplicationContext):
        n_b = Button(label = "verify", style = ButtonStyle.green, disabled = False)

        async def cb(interaction):
            role = discord.utils.get(msg.guild.roles, id=roleid)
            await interaction.user.add_roles(role)

        n_b.callback = cb

        view = View()
        view.add_item(n_b)

    e = Embed(description = "Welcome to Republic of Dreamers a group project jumpers!\nClick the verify button below to get verified.", color = con.clr)
        await ctx.send(embed = e, view = View)```
proud mason
proud mason
#

pass view V small

spice jewel
#

oh sorry

#

thanks lol

proud mason
#

np

proud mason
dry gazelle
proud mason
#

interaction.response getting blocked is a very unlikely scenario. if that happens you might want to ask in discord devs server

dry gazelle
#

Yeah I’m kind of stuck and don’t know where to go from here lol

proud mason
#

Although it usually not very favourable to not use gateway

#

those event are quite useful many times

#

unless you made a complicated system where you use gateway for events and http for interactions and somehow communicate between the two

dry gazelle
#

Hmmmm okay

#

I’m probably holding development this week and picking back up Sunday

proud mason
#

ouu alr

coarse crown
#

How do i give a slash command a description?

proud mason
proud mason
limber urchin
#

But it'd be something like 95^100, I don't know which characters they support

fallen cove
#

randomly started getting discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access on on_connect error. the code hasn't changed and has all the nesseccary permissions: Bot, applications.commands, administrator. any ideas?

limber urchin
#

How do you know your bot has administrator in all servers it is in?

grizzled sentinel
fallen cove
limber urchin
limber urchin
#

Send your full stack trace

fallen cove
#
Ignoring exception in on_connect
Traceback (most recent call last):
  File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\bot.py", line 1164, in on_connect  
    await self.sync_commands()
  File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\bot.py", line 738, in sync_commands
    app_cmds = await self.register_commands(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\bot.py", line 531, in register_commands
    prefetched_commands = await self._bot.http.get_guild_commands(
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\http.py", line 360, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
#

was fine last week when i was working on it, nothing had changed

limber urchin
#

That means your bot is trying to register commands in a guild it isn't in. So somewhere you have a guild id in a command that your bot is not in.

finite flame
#

how do I create <t:0> in pycord?

cyan quail
#

If you have a datetime object, use discord.utils.format_dt

finite flame
#

can a ephemeral message be deleted in some way?

silver moat
#

yes

finite flame
silver moat
finite flame
silver moat
finite flame
#

a ok, so I have to do it on the context 👍

finite flame
#

how do I "clense" a message off @ everyone, @ here and any role pings the command caster isn't supposed to ping?

silver moat
#

allowed_mentions

finite flame
# silver moat `allowed_mentions`

hm, that one only works on send if I understand correct?
I want to filter out any that were handed in and add that to a message that does need to still be able to do that though

silver moat
#

it also works on edit if that's what you're asking

finite flame
#

what I need:

  • user uses command and inserts text
  • remove all unallowed mentions from that
  • add this processed text to a text that is allowed to have these mentions
  • send that composition
finite flame
#

why is it saying that? 😦

young bone
grizzled sentinel
young bone
#

^

finite flame
#

aight

finite flame
marble nova
#

how can i register my default help command as a slash command?
I did Bot(help_command=MyHelp()) but that doesnt make it a slash command only a prefixed command

proud mason
#

you dont really need a help cmd in slash cmds because you have descriptions on the cmds and options. even discord says you dont need a help cmd for slash

woeful skiff
#

Getting these errors while hosting the bot. Code:

bot.event
async def on_message(ctx, message):
        ctn = message.content.lower()
        if „discord.gg“ in ctn:
                await message.delete
proud mason
#

there is message.reply

#

and message.channel.send

woeful skiff
#

Oh alr

young bone
woeful skiff
#

what’s tracemalloc

proud mason
#

Regarding 1st error, is the codeblock you sent the code?

proud mason
#

btw you can an ss on your macbook with cmd + shift + 5

woeful skiff
#

Ik i can but I’m to lazy to open discord

#

But does message.delete exists?

#

If you imported the message module

proud mason
proud mason
woeful skiff
#

But this is my code, and it doesn't work

young bone
woeful skiff
#

Yeah

#

I am even in a course for it lol

young bone
#

As a teacher or Student?

woeful skiff
#

Student

#

for like already a year

young bone
#

add () after the delete

#

Do you have intents?

woeful skiff
#

Oh ty

#

still doesn't work sadly

young bone
finite flame
#

is there a list of all available datatypes that can be received from a slash command?

woeful skiff
#

uh wait lemme check

#

i imported very much stuff

#

intents = discord.Intents().all()

woeful skiff
woeful skiff
young bone
#

Can the bot see the channel?

proud mason
#

discord.Intents.all()

proud mason
woeful skiff
#

i just pasted it in the bot fiel

#

file*

#

ok it worked

#

How can i do it like if cnt == "lol" it will only block "lol" but it will allow "hi lol". How can i allow it for the whole msg ?

#

@proud mason

still helm
#

but this blocks dcgfhsdfhdfloljdzsgfusdzfg too

woeful skiff
#

ok nice ty

woeful skiff
proud mason
blissful hazel
proud mason
#

or you can split the content at space

#

and check if "lol" is in the list of words

cyan quail
#

honestly if you want regex just use built in automod

gleaming falcon
#

Not a Pycord question, but is anyone relatively advanced with PyYAML? Want to run an approach by someone

worldly schooner
#

How do you make a task loop in a random period of time inside a range?
I mean to use like

@tasks.loop(seconds=randomSecond)
async def send_message(self):
  # do something
  randomSecond = random.randint(500, 50000) # New random second between 500 and 50k
#

but randomSecond is not accessible cuz it is out of the class

#

nvm it is accessible

#

but i dunno if it will work, i will try with short periods of time

#

ok its not even working with a persistent value

#

Am I using it wrong?

young bone
worldly schooner
#

I FORGOT

#

tysm

worldly schooner
#

Now I'm getting this error when I start the task

#

general declaration

worldly schooner
full basin
#

fetch_channel is a coroutine

worldly schooner
#

changed to get_channel and:

young bone
#

use fetch_channel

worldly schooner
young bone
#

do you know what we are talking about?

worldly schooner
#

I used fetch_channel

#

but it said I can't send non-None value to a just-started coroutine, so how could I handle that?

young bone
worldly schooner
fallen cove
#

what would be the best way to store variable values? e.g. if the bot needs to be restarted so the values are kept

silver moat
#

databases

fallen cove
mossy holly
# silver moat databases

I'll have the same question, storing simple settings values (like booleans but also maybe my tokens (for now it's in a .env file)), I was thinking of using a file.ini, is making a db a better choice (little bit overkill for just few values no ?)

silver moat
mossy holly
mossy holly
worldly schooner
#

or a dictionary for example

dusky sorrel
#

is there a way to quit (not reopen just quit) the bot's process with a command?

worldly schooner
dusky sorrel
#

mhm

worldly schooner
#

since I couldnt await it inside the init

hollow brook
#

with the audio recording features, is there any way to record all of the audio in the channel to a single file instead of every separate user?

#

I know i can use other libraries to merge the audio streams i was just wondering if there was a built-in way to do this

dusky sorrel
worldly schooner
#

or just a complete stop and a manual restart

dusky sorrel
worldly schooner
# dusky sorrel yeh
@bot.command()
@commands.is_owner()
async def shutdown(context):
    exit()```
#

found that in Stackoverflow

#

never tried out but might work

sick quest
#

when I call bot.close() does it shut down the bot, or only close the connection to discord?

worldly schooner
obtuse juncoBOT
#

Tag Credit: discord.py server
The only good way to restart your bot is to shut it down and have your process manager handle it. You can shutdown your bot by running Bot.close().

Do use:

  • run your bot in a process manager such as:
    • systemd
    • openrc (gentoo, devuan)
    • runit (void linux)
    • supervisord
    • upstart (old ubuntu)
    • docker
  • manually reboot it

Do not use:

  • a bash loop (it can eat your C-c by rapidly spawning python and if your bot fails it won't stop it from constantly failing)
  • subprocess.call (you will eat your memory up by not letting your old processes die)
  • os.exec*
sick quest
sick quest
dusky sorrel
#

i just made it have a random message

#

then proceeds to kill itself

flat reef
#

idk what could be wrong here, when I send the message with the prefix, doesnt work but the command is registered as a slash_command, code:

bot = discord.Bot(command_prefix="$", intents=Intents.default())

@bot.event
async def on_ready():
    print(f"{bot.user} is ready and online!")


@bot.command()
async def ping(ctx):
    await ctx.send("Pong")

bot.run(BOT_TOKEN)```
#

could anyone help?

young bone
flat reef
#

I dont want the "User used /command" part

#

thats why I didnt want to use slash command

young bone
#

you can even hide the slash commands

flat reef
#

it isnt possible to use command_prefix AND slash commands then?

errant craneBOT
#

Here's the bridge commands example.

flat reef
#

oh thats very useful, ty

flat reef
#

it is an even solution for what I want

errant craneBOT
#

Here's the slash perms example.

flat reef
#

ty again

#

ah this is about permissions, was looking for something like this:

flat reef
#

yeah but might need a specific parameter, I could see your /example for example

silver moat
#

?tag ephemeral

obtuse juncoBOT
#

An 'ephemeral' message is one that's only visible to the person who invoked a command. If you ever got a command error with a blue background, this is an example of one.

To do this, set ephemeral=True when you first use an ApplicationContext. (This includes .defer()ing it; the choice of whether a message is ephemeral or not must be made up front. If you .respond() to a deferred message, setting the ephemeral flag at that time will have no effect.)

This is the equivalent of hidden=True if you're coming from interactions.py

flat reef
#

"setting the ephemeral flag at that time will have no effect"

#

I'll delete it after running the command

#

this way wont show the slash command used

#

but ty all for the help!

#

neverming I just realized that I was using .defer() and so it wouldn't work

#

just fixed it, ty!

flat reef
#

even after the bot is fully up, no response at all

limber urchin
#

If you want them to work after a restart you need to use persistent views

#

The bot isn't just magically going to remember every view created

errant craneBOT
#

Here's the persistent example.

flat reef
#

ah I was doing the timeout=None and thought it was enough

limber urchin
#

No, that will just remove the timeout of the view

vapid pumice
#

Can a message be edited multiple times in one interaction?

I attempted to use

message = await interaction.response.edit_message(embed=embed)
await asyncio.sleep(1.5)
await interaction.message.edit(message.id, embed=new_embed)``` 

This didn't work because `message` returns NoneType
proud mason
#

also your method could work, but dont pass message.id to it

proud mason
flat reef
#

Is there a way to deselect the option after clicking at the Select menu (dropdown options)?

I've tried doing something like this at the callback:

select.row = None
select.refresh_state(interaction)
#

I've also seen this message:
#general message

#

idk if it is already implemented

vapid pumice
proud mason
flat reef
#

ah I just searched for "deselect" on the server haahahah

proud mason
proud mason
vapid pumice
proud mason
#

btw message components right

vapid pumice
#

It's because I'm editing an ephemeral message in the original interaction response, so there is no ID to be traced I guess?

proud mason
#

you can delete an ephemeral message, so you should be able to edit it too

#

at least thats what i think

#

try interaction.delete_original_response and see if that works

vapid pumice
vapid pumice
#

ehh..AttributeError: 'Webhook' object has no attribute 'delete_original_response'

proud mason
vapid pumice
cyan quail
#

yes

proud mason
#

hmm

vapid pumice
#

Will send this:

if select.values[0] == "Pokeflute":
            for interaction_name, interaction_coord in interactions.items():
                if interaction_coord["x"][0] <= select.profiles[interaction.user.id]["user_position"][0] <= interaction_coord["x"][1] and interaction_coord["y"][0] <= select.profiles[interaction.user.id]["user_position"][1] <= interaction_coord["y"][1]:
                    if interaction_name == "snorlax":
                        embed = discord.Embed(description="*ZZZ... Snoring* \n**The Snorlax woke up!**")
                        file = discord.File(encounter_animation(select.profiles[interaction.user.id]), filename="encounter.gif")
                        embed.set_image(url="attachment://encounter.gif")

                        message = await interaction.response.edit_message(embed=embed, file=file)

                        await asyncio.sleep(1.5)
                        new_embed = discord.Embed(description="")
                        snorlaxencounter = discord.File("Media\snorlaxencounter.jpg", filename="snorlaxencounter.jpg")
                        new_embed.set_image(url="attachment://snorlaxencounter.jpg")
                        await interaction.message.edit(embed=embed)
                        return
proud mason
#

.idw

winter condorBOT
#

Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.

proud mason
#

if you are having cache issues, use partial objects

#

.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:")
cyan quail
#

yeah interaction.edit_original_response is exactly what you want there

#

only after using interaction.response.edit_message

#

show your code

#

don't await

#

and where's channel_id defined

vapid pumice
cyan quail
#

fair enough

#

get_channel

cyan quail
#

what's your full callback

vapid pumice
# cyan quail what's your full callback
async def callback(select, interaction):

        if select.values[0] == "Pokeflute":
            for interaction_name, interaction_coord in interactions.items():
                if interaction_coord["x"][0] <= select.profiles[interaction.user.id]["user_position"][0] <= interaction_coord["x"][1] and interaction_coord["y"][0] <= select.profiles[interaction.user.id]["user_position"][1] <= interaction_coord["y"][1]:
                    if interaction_name == "snorlax":
                        embed = discord.Embed(description="*ZZZ... Snoring* \n**The Snorlax woke up!**")
                        file = discord.File(encounter_animation(select.profiles[interaction.user.id]), filename="encounter.gif")
                        embed.set_image(url="attachment://encounter.gif")

                        message = await interaction.response.edit_message(embed=embed, file=file)

                        await asyncio.sleep(1.5)
                        new_embed = discord.Embed(description="")
                        snorlaxencounter = discord.File("Media\snorlaxencounter.jpg", filename="snorlaxencounter.jpg")
                        new_embed.set_image(url="attachment://snorlaxencounter.jpg")
                        await interaction.followup.edit_original_response(embed=embed)
                        return
            else:
                embed = discord.Embed(title = "Nothing happened...")
                file = discord.File(update_map_image(select.profiles[interaction.user.id]), filename="map_image.jpeg")
                embed.set_image(url="attachment://map_image.jpeg")
                await interaction.response.edit_message(embed=embed, file=file)
cyan quail
#

.

proud mason
#

not interaction.followup.edit_original_response

cyan quail
#

^

#

it's interaction.edit_original_response

proud mason
#

?tag intents

obtuse juncoBOT
#

https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents

import discord
from discord.ext import commands

# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True  # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content 
intents = discord.Intents.default()

# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True  # Required for prefix commands >= 2.0.0b5

# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()

# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
vapid pumice
cyan quail
#

upgrade

proud mason
#

update

vapid pumice
#

mmmmmmmmmmmmmm

#

tyty

#

wait

#

But if I update...it goes to v2 yea?

cyan quail
#

wth version are you on

proud mason
#

well are you not on v2 💀

vapid pumice
#

No xD

cyan quail
#

interactions were added in v2

proud mason
cyan quail
#

so if you aren't on v2 already then this is the wrong server

vapid pumice
#

whhhaaaa

proud mason
#

dont use 3rd party libs. they are really messy

vapid pumice
#

Okay I must be confused lol

cyan quail
#

i mean you can, but if you are then we can't really help since the code's different

vapid pumice
#

I'm not using a third party lib

proud mason
#

wait what

vapid pumice
#

I think I'm confused lol

I'll update

cyan quail
#

are you using the component extension lib or something

vapid pumice
#

noooo

cyan quail
#

eh...

vapid pumice
#

I'm using Pycord

cyan quail
#

print discord.__version__

vapid pumice
#

2.0.1

proud mason
#

oh wait i think you are on an old dpy version where interactions were added but other breaking changes werent

vapid pumice
#

Yea, I'm trippin

proud mason
#

aah

cyan quail
#

so you're on v2...

#

but yeah we're on 2.4.0 now

vapid pumice
#

Okay, lemme fix that ahahahha

#

GGz <3

#

Holy shit I have to change all kinds of stuff to migrate to 2.4 0-0

cyan quail
#

there shouldn't be that much? a lot of additions but i can't recall us removing anything major

vapid pumice
#

It looks like import options from discord changed alongside slash_commands too? I might need to go read up on the changelog or something to figure out how to adjust my code for this.

cyan quail
#

no..? it's been the same throughout v2

#

what's not working

vapid pumice
#

After updating, I get this

Traceback (most recent call last):
  File "d:\!coding\EtherGame\ethergame copy 4.py", line 7, in <module>
    from discord import option
ImportError: cannot import name 'option' from 'discord' (C:\Users\Drew\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\__init__.py)
PS D:\!coding\EtherGame> 
#

And if I remove that line I get even more wacky errors

cyan quail
#

works fine on my end... this seems more like an venv error

vapid pumice
#

hmmm

#

I mean, I upgraded with pip, this is de wei, right?

cyan quail
#

what did you install

vapid pumice
#

pip install --upgrade discord

cyan quail
#

.

#

uninstall that

#

and install py-cord with upgrade

vapid pumice
#

Sorry, I'm still so new to this development journey. Doing my best to take it all as it comes

#

But man, I appreciate this place so fucking much

cyan quail
#

well as long as you have fun i guess

#

allgood

mossy holly
worldly schooner
# mossy holly Yeah I see but I assume there's a module that makes the transformation ini -> di...

depends on where you are hosting it, you can just export the json with json.dump with the same name of the file you are loading it from, but since I started using MongoDB this turned out deprecated to me, and I had trouble cuz I was using this method when hosting with a github repo, since the host loaded the info from github I would have to make a backup from the host and commit manually to github if I wanted to persist the information in the next execution

proud mason
# proud mason not built in

you would need to start some sort of a buffer when you start recording, and write each users data to it as you receive it

#

ig smth like pydub can make this work

grizzled sentinel
#

Discord does not send silent frames of audio. So the timings of people talking would be off.

#

Unless you fill them in yourself, by having a timer between frames and if it is over X amount of time add X amount of silence.

grizzled sentinel
#

Ah ok.

glacial galleon
#

can i ignore this

proud mason
glacial galleon
#

alr thanks

green hinge
#

I want to add an image from my PC to my embed in Paginator instead of from a URL.
How can I pass the file of the page so that the image is displayed?

embed = discord.Embed(title=f"Informationen für {self.message_details[2]['spot']} ({self.message_details[2]['gewaesser']})", color=0x00ff00)
file = discord.File("./Fische/Rotauge.png",filename="Rotauge.png") embed.set_image(url='attachment://Rotauge.png')
for key, value in info.items():
                if key not in ['ID', 'GuildID', 'UserID']:
                    new_key = word_dict.get(key, key)
                    embed.add_field(name=new_key, value=value, inline=True)
            pages.append(embed)
        return pages```
Paginator call:
```py
paginator = await PaginatorDetailsView(self.bot, self.message_details)
        await paginator.respond(interaction, ephemeral=True)```
hollow brook
green hinge
cyan quail
#

if you read the docs page i linked, Page can contain both embeds and files

green hinge
cyan quail
#

...eh those are confusing actually

#

literally just call it normally py from discord.ext.pages import Page page = Page(embeds=[discord.Embed(...)], files=[discord.File(...)])

#

and then pass a list of these Pages into Paginator instead of using embeds directly

green hinge
cyan quail
#

mhm

green hinge
#

Okay I have tested it and it works

hollow brook
woeful skiff
#

this isn't working for me, the first one is working but the elifs aren't:

@bot.event
async def on_message(message):
  msg = message.content.lower()
  if "word" in msg:
    await message.reply("Hi")
  elif "anotherword" in msg:
    await message.reply("How's it going")
proud mason
#

i did once try to theorise how it could work but never came up with a concrete solution

#

you could do smth like create a dict of timestamp and packet and then try to do some magic on it

woeful skiff
#

but also if i do it like this:

@bot.event
async def on_message(message):
  msg = message.content.lower()
  if "word" in msg:
    await message.reply("Hi")

@bot.event
async def on_message(message):
  msg = message.content.lower()
  if "anotherword" in msg:
    await message.reply("How's it going")

it's not working

proud mason
#

because if anotherword is part of msg, that means word is also part of msg, because word is part of anotherword. so "word" in msg would resolve to True, and will skip thee 2nd check

unless "word" and "anotherword" are replaced by some real words 💀

woeful skiff
#

can't i do it like that?

proud mason
woeful skiff
#

oh easy

proud mason
#

yea

woeful skiff
#

tysm

icy zodiac
#

does someone know why it dont work ?

proud mason
#

?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

proud mason
#

also dont expose your bots token. reset it blobpain

icy zodiac
#

i reset it

icy zodiac
proud mason
#

do you have the correct environment activated?

icy zodiac
#

do you mean folder ?

#

or witch environment do you mean

young bone
icy zodiac
#

i dont now what do you mean with environment

young bone
#

do you know basic python?

proud mason
# icy zodiac i dont now what do you mean with environment

i dont use pycharm but check this https://www.youtube.com/watch?v=2P30W3TN4nI

Learn to use virtual environments in PyCharm within 10 Minutes!

🔍 PyCharm Tutorial Playlist: https://www.youtube.com/playlist?list=PL30AETbxgR-dKTR0wBfkQw9mywvkCi3q_

⌚ Timestamps ⌚
00:00 | Two Methods of Creating a Virtual Environment (venv)
00:16 | Method 1: New Project with a Virtual Environment
01:34 | Method 2: Adding a Virtual Environmen...

▶ Play video
icy zodiac
#

thanks

silk spindle
#

hello, is there a way to send multiple message to a member without referencing the original message ?

echo egret
glacial galleon
#

replit moment, it works on my ide (but code stops when i close computer ofc)
any way to fix? basically i cant download the pycord package

lost lodge
#

Hey guys!

Do you guys know if there is any way to respond to a ctx without responding to it? (so that you don't have to send a message)

full basin
lost lodge
full basin
#

Can you speak without saying any word?

lost lodge
full basin
#

That was not the point but ok

lost lodge
#

ok, but thanks anyway

full basin
#

What's the point of not sending any message?

tired goblet
#
            if channel.category == model and channel.name == REMINDER_CHANNEL:```
#

is this a good way to check for the existence of a channel in a particular category?

lost lodge
#

But is there a way to delete a message, which was responded? When i tried to delete a message which was sent via msg = ctx.send i can delete it via msg.delete, but it doesn't work with a msg = ctx.respond message.

silk spindle
flat reef
#

I have a view with select I'm trying to update the options dynamically, how do I reload the View?

#

The code that generates it is already getting the options when run but it happens only when the bot is run

#

(it is a persistent view)

#

Currently I dont need to that message to update, I dont have any problem at re-sending it, I just want it to reload

flat reef
#

How could I do that? The only moment that it is currently "generating" is when self.bot.add_view() run at on_ready()

young bone
#

edit it with a new view and select

#

and use append_option

flat reef
#

I'm doing something like this on the add_option command:
FactionsSelectView().children[0].options.append(SelectOption(**new_option))

new_option is a dict with label, description, value and emoji

#

When debugging seems correct but I might have missed something

lost lodge
young bone
green hinge
#

How can I disable the Select menu after the selection?

class MontageartPosenangel(discord.ui.Select):
    def __init__(self, bot: discord.Bot):
        self.bot = bot
        options = [discord.SelectOption(label=art) for art in montageart]
        super().__init__(
            placeholder="Wähle deine Montageart aus",
            min_values=1,
            max_values=1,
            options=options,
        ) 

    async def callback(self, interaction: discord.Interaction):
        self.disabled = True```
full basin
#

Edit the message with the new view

green hinge
full basin
#

.tag tias ?

winter condorBOT
#

Tag not found.

Did you mean...
tias

full basin
#

.tag tias

winter condorBOT
full basin
#

?

green hinge
#

The placeholder is always displayed and not the selected choice

full basin
#

Did you edit self.values?

green hinge
#

I only disable the menu

self.disabled = True
await interaction.message.edit(view=self.view)```
full basin
#

You need to also edit the values

green hinge
#

How do I have to do this?

#

Ah I can solve it like this

self.disabled = True
        self.placeholder = self.values[0]
        await interaction.message.edit(view=self.view)```
flat reef
#
class FactionsSelectView(discord.ui.View):
    def generate_options(self):
        select = discord.ui.Select(
            placeholder="Clique para selecionar",
            custom_id="faction_selector",
            options=[SelectOption(**x) for x in JsonData.read().get("options")],
        )
        select.callback = FactionsSelectView.select_callback
        return select

    @classmethod
    async def select_callback(cls, select: discord.ui.Select, interaction: Interaction):
        ...
    def __init__(self):
        super().__init__(timeout=None)
        self.clear_items()
        self.add_item(self.generate_options())

I created the view above trying to dynamically change buttons but I get this error when calling the command to show it:

Invalid Form Body 
In components.0.components.0.options.1: The specified option value is already used
#

nvm figured it out

undone falcon
#

is their a way for me to wait for the result to arrive in asyncio in my pool ? _get_all_expired_recurrent_roles is a CPU bound method

#

I would want something like: asyncio.wait(result)

#

I dont want to use the method asyncio.to_thread, because it is specified in the docs that it is for IO bound methods not CPU bound methods

sick quest
#

is there a way to make it so Bot.close() closes with an error code? so like the process exits with error code 1 instead of 0

undone falcon
sick quest
#

but I can't do that since I have to run await Bot.close() first which exits

undone falcon
#

yeah you could do a sys.exit(1) after bot.close()

#

like this

#

I dont know if it woudl really work, but it is work trying

sick quest
#

but I can try that!

proud mason
#

Instead of a thread pool

gleaming falcon
mild sigil
#

If I have a group of 5+ buttons, is it possible to disable certain ones based on the other buttons pressed?

#

Or would it be easier to disable all the buttons and just send a new view with the desired buttons available?

mild sigil
#

So with something like this:

#

I can do this if buttons are children or no?

silver moat
#

given that you a button object, you can disable it with

#

.rtfm button.disable

mild sigil
#

probably a poorly formatted question. I have the buttons currently set up as children and they disable all others when pressed:

    async def second_button_callback(self, button, interaction):
        get_user_id(interaction.user)
        for child in self.children:
            child.disabled = True
        await interaction.response.edit_message(view=None, content="You clicked the B2 button!")```

so, changing to something like:

```@discord.ui.button(label="B2", style=discord.ButtonStyle.primary, row=0)
    async def second_button_callback(self, button, interaction):
        get_user_id(interaction.user)
        for child in self.children:
            if child.label == "B3":
                child.disabled = True
        await interaction.response.edit_message(view=None, content="You clicked the B2 button!")```
mild sigil
#

I guess, am I on the right track? Been trying this for a few hours now and finally came here for a sanity check.

silver moat
#
        await interaction.response.edit_message(view=None, content="You clicked the B2 button!")

I don't understand why you would want to remove the view

mild sigil
#

I only want them to be able to select two buttons max so I have that code to remove the view once that happens, though I haven't figured that part out yet... I'll play with that after I have the other bit working.

silver moat
#

You can create an instance variable named buttons_selected and increment it as you go.

mild sigil
#

sounds right. I'll have to test the logic more but this gives me a good jumping point for more testing and experimentation. Thanks Squid, I appreciate the help.

silver moat
#

yw

novel jay
#

I remember someone telling me that shards can set their own independent status different from other shards and that's how bots get like "Status | Shard X", how do you do this in pycord?

silver moat
novel jay
#

Does that let you change the status of a specific shard though?

novel jay
#

Ohhh for some reason it went to the regular discord bot page

#

thx i see it

undone falcon
#

if I just fetch_or_get() a guild, will the members inside be accurate and up to date to the current moment ? or do I also need to fetch_or_get all members of the guild

full basin
#

Try it and see?

undone falcon
#

well it will be up to date for a tests server for sure

#

I am more asking for a servers with like 100k members or more

#

Which I cannot manually verify

silver moat
#

get will get it from the cache and the cache is updated on every guild event you receive.

undone falcon
#

oooh I see, so if the cache is full, there will be members missing ?

silver moat
#

There is no limit to the guild cache iirc

undone falcon
#

oooh perfect, so the RAM is the limit 😅

cyan quail
#

yeah, the only significant cache limit is messages which is 1000 by default but can be adjusted

undone falcon
#

thanks you !

limber urchin
#

And you also obviously need the guild members intent

undone falcon
#

yesss 💯

silver moat
#

I don't think get_or_fetch_guild and get_or_fetch_role exists tho

limber urchin
#

And it wouldn't make sense to use get_or_fetch on every member of the server, because how would you have every member's ID?

undone falcon
silver moat
#

ic

cyan quail
#

fetch_role doesn't exist because there's no route for it

#

you have to fetch all roles in the guild and pick from there

undone falcon
cyan quail
#

but you can use utils.get_or_fetch(bot, "guild", id)

silver moat
cyan quail
#

hm?

silver moat
#

Also, we don't need 3 people here.

undone falcon
#

which is pretty dumb ahahaha

cyan quail
#

actually huh

#

yeah _fetch_role does just call fetch_roles

#

...maybe it should be public anyway

undone falcon
#

mhm maybe, but would not change much 😄

cyan quail
#

well it'd just force it to be documented

#

and then would be compatible with get_or_fetch

undone falcon
#

oooh smart ! but In the mean time I just did :

silk spindle
#

hello, any one knows how to avoid displaying the avatar of the bot if 2 or more consecutive messages are sent to the user ? I would like to avoid the first image situation.

On the second image you can see that 2 messages were sent to the user but the bot profile /name is only visible for the first message.

limber urchin
#

?tag nojson

obtuse juncoBOT
#

Why not to use json files for data storage
JSON files are commonly used to store data that is read by a program, however, they are unsuitable for storing dynamic data due to a number of reasons.
It is recommended to use a DBMS (Database Management System) as they come with optimized technologies for storing and retrieving information.

Advantages of using a database:

- Database tables can be related, making it easy to separate your information into multiple tables and only fetch what you need
- Databases allow you to use a query/data processing language to make complex data operations easier with less code
- One misplaced character will corrupt an entire file. A database very rarely experiences corruptions due to their automatic handling of data integrity
- Transactions in SQL databases allow you to revert unwanted changes and prevent data corruption in the case of an error
- Databases have support for indexes, allowing retrieval of some data to be extremely fast
- It is very easy to update existing data in a database, as opposed to re-writing a file
- Databases are reliable

Popular database management systems:

- SQLite3
- MongoDB
- PostgreSQL
- MySQL
- MariaDB
- Microsoft Access
blazing tide
#

can anyone help me
im trying tu run a discordcloner selfbot on vscode and the code gives this error! how can i fix it

sweet coyote
#

Is there a way to detect when a new forum post is created?

fervent cradle
#
    async def callback(self, interaction: discord.Interaction):
        report_channel = bot.get_channel(1044192795440709684)
        success = discord.Embed(description="desc", color=discord.Colour.brand_green())
        report = discord.Embed(
            title = f"hidden",
            description = f"hidden",
            color = discord.Colour.brand_green()
        )
        report.set_thumbnail(url=msg.author.avatar)
        report.add_field(name="hidden", value=f"[Click to view]({msg.jump_url})")
        report.add_field(name="hidden", value=self.children[0].value)
        report.set_footer(text=f"{hidden}")
            
        await interaction.response.send_message(embed=success, ephemeral=True)
        await report_channel.send(embed = report)```
Why am I receiving this error? 
- `AttributeError: 'NoneType' object has no attribute 'send'`
#

(this is a modal callback btw)

full basin
obtuse juncoBOT
#

Any function that starts with get_ in Py-cord is retrieving the related object from your bots cache. If the object is not in the bots cache the get_ method will return None. Because of this behavior you should check if the get_x method is None and if it is use the fetch_x method.

Why Is Using fetch_ Without Using get_ First Bad?
The fetch_ method makes a call to the discord API. This API call is unneeded if you already have the information. It will also make your command take longer because it will have to send and than wait for a response from the discord API. It will also contribute to the discord APIs global rate limit of 50 requests per second.

What Is Cache?
The cache is a temporary storage inside your bot. It holds many objects from members to messages. When you restart your bot the cache will be empty. When the cache is full it will delete older objects to make space for the new objects.

ebon drift
#

Is there a way to have different servers play the same game of Guess the Number but with a different preset number

#

For all of them

woeful skiff
#

Can someone send me a giveaway code for Pycord per dm plsss

winter condorBOT
# fervent cradle ```py async def callback(self, interaction: discord.Interaction): re...

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:")
grizzled sentinel
ebon drift
#

I am stuck trying to get categories and owner only commands show up when only owner is using ;help

ebon drift
#

Well my categories are not working

proud mason
proud mason
fervent cradle
#

The bot works for all commands, when I want to add another command, is it not visible in the slash list, or has it not been created? What is on the screen, why such an error occurred, please help

ebon drift
#

@bot.bridge_command(description="Just Say Hello To Dia", category='Random')

tired goblet
#

bot = discord.Bot()



@bot.event
async def on_read():
  print(f"{bot.user} is ready and online!")
  for guild in bot.guilds:
    print(guild.name)

bot.run(token)```

why doesn't this print anything?
silver moat
#

what is on_read

tired goblet
#

oh

#

damn i meant to write on ready

silver moat
#

k

tired goblet
#

*not

silver moat
#

what do you mean

tired goblet
#

bot = discord.Bot()



for guild in bot.guilds:
    print(guild.name)

bot.run()```
#

something like this

proud mason
#

guild data is not populated before ready

tired goblet
#

oh

silver moat
#

well the bot isn’t even connected to gateway

tired goblet
#

okay

silver moat
#

so how does it know

proud mason
tired goblet
#

so basically python doesn't know when to execute that for?

silver moat
#

no it will execute. but there are 0 guilds

tired goblet
#

oh okay

#

makes sense