#Basic Pycord Help

1 messages · Page 20 of 1

lofty parcel
#

You said you used to use discord.py, these are concepts used in d.py too.

pale scroll
pale scroll
#

it`s bad module(d.py)

lofty parcel
#

Coroutines are present everywhere. Not just in modals.

pale scroll
#

in responds

#

in sends

#

everywhere

#

wtf

#

@lofty parcel

#

sorry for mention

#

I feel useless to anyone, I’m dumber than a cat, plus I’m blind, I don’t deserve to be a programmer and a bot developer

lofty parcel
# pale scroll

You're doing ctx.respond when you should be using ctx.send_modal. Don't know why you modified that line /shrug

pale scroll
#

thx, dark, but it don`t send result in my dm

fresh totem
#
class cardCommands(commands.Cog):
    def __init__(self, bot_: discord.Bot):
        self.bot = bot_

    card = SlashCommandGroup("card", "View, Trade and Sell your Cards!")

    @card.command()
    async def inventory(self, ctx: discord.ApplicationContext):
        "View your Card Inventory"```

This is a group command, how can I lock the `inventory` command to server admins only

normally I use:
```py
@discord.default_permissions(administrator=True)

but this doesn't seem to work with group commands

shell radish
#

permissions can only be assigned to top-level commands like card

#

why? ask discord

fresh totem
#

fair enough

#

how can we add it to the top-level command here => card

edgy nest
#

i think there's a default_permissions kwarg

#

i might be wrong

pale scroll
#

Hi for all

#

how to command author mention paste in embed result modal?

floral ice
#

how do i use @option

outer niche
little cobalt
#

Doesnt really matter because of the version

#

The version is broken

floral ice
#

1 more thing, when i create cog class, how can i access the bot object in @slash_command decorator? i need to access bot.main_guilds (custom attribute)

grim estuary
floral ice
valid panther
#

notlikethis notlikethis I am not trying to deal with the timeout problem:

ERROR:asyncio:Task exception was never retrieved future: <Task finished name='discord-ui-view-timeout-2840ebd01534e1844d2f1979a8c4d407' coro=<ButtonsMatch.on_timeout() done, defined at /app/commands/global/match_games.py:94> exception=HTTPException('401 Unauthorized (error code: 50027): Invalid Webhook Token')> Traceback (most recent call last): File "/app/commands/global/match_games.py", line 105, in on_timeout await self.message.edit( File "/usr/local/lib/python3.10/site-packages/discord/interactions.py", line 1194, in edit return await self._state.interaction.edit_original_response( File "/usr/local/lib/python3.10/site-packages/discord/interactions.py", line 428, in edit_original_response data = await adapter.edit_original_interaction_response( File "/usr/local/lib/python3.10/site-packages/discord/webhook/async.py", line 221, in request raise HTTPException(response, data) discord.errors.HTTPException: 401 Unauthorized (error code: 50027): Invalid Webhook Token
#

Why does the button say that the message does not exist if it does?

shell radish
shell radish
#

yeah then the interaction expired

valid panther
#

is for a button to prox of duration 1-3h hours

little cobalt
#

Is it possible to mention a role without pinging everyone who got the role?

shell radish
little cobalt
#

If you send a normal text message and mention a role in it

shell radish
#

I should clarify. Whom do you want to ping?

#

Is it no one or a subset of people that have the role?

lofty parcel
pale scroll
#

How to create option args

rugged lodgeBOT
#

Here's the cooldown example.

valid panther
#

It doesn't happen every time you do that commands older than one day have worked without problems and you can modify the message.

lofty parcel
#

Then save the original response which gives you a message object.

#

And then edit it.

warm jay
little cobalt
limber wagonBOT
#

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

little cobalt
#

use the master branch

warm jay
#

End of error message:

note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for aiohttp
Failed to build aiohttp
ERROR: Could not build wheels for aiohttp, which is required to install pyproject.toml-based projects
warm jay
#

There is this line as well error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/

little cobalt
#

uh

#

did you read the error?

warm jay
#

yeah

#

aiohttp fails to install

little cobalt
#

read that again

warm jay
#

Yeah, at that link rn

#

I need to install VS?

lofty parcel
#

Read the website and follow the steps

obsidian stratus
#
@bot.slash_command(description="Add xp to a user in a particular server.")
async def add_xp(ctx, guild_id:str, user_id:str, exp:str):```
Why is it giving me "input a valid integer" when I try using the command
#

🤔

#

I'm trying to parse a string into integer later in my code but idt this should affect it

#

For some reason it's only allowing integers 2^53 (When I'm trying input as a string)

noble flax
#

Trying to create a fuzzy autocomplete feature for my bot, how can I retrieve the "option" that has been typed for my fuzzy search? At the moment I'm return the below, how can I retrieve the "unit" in the options? do I need to pass something in the method?

#

This is my full function

warm jay
lofty parcel
lofty parcel
noble flax
#

The idea is "unit" should have the string of the thing I'm looking for

#

I want to then pass that to the fuzzy lookup

lofty parcel
noble flax
#

typing the unit should then return the options based on a fuzzy return

lofty parcel
#

So you don't pass it to the autocomplete function.

#

Autocomplete only receives its own context

#

ctx.value returns the value the user is inputting

rugged lodgeBOT
#

Here's the slash autocomplete example.

lofty parcel
#

See ^

noble flax
#

Thank you so much

warm jay
#

I installed VS 14.0+, and installing still fails

#

I already installed the VS thingy

#

for c++

sage tendon
#

unless you really really really need 3.12, just use 3.11

maiden bloom
#

Which event reference is for button presses?

little cobalt
#

But that is also for Menus and slash commands

#

So you would have to check for it

maiden bloom
#

How can I put an emoji in a button?

maiden bloom
lofty parcel
#

Read the docs

maiden bloom
# lofty parcel There is a emoji= kwarg

I added it and it says it takes in a string but I'm getting an invalid emoji error from this. I'm sure it's obvious but could you point out what I'm doing wrong?
@discord.ui.button(label="Create Ticket", emoji=":envelope_with_arrow:", style=discord.ButtonStyle.primary)

lofty parcel
#

Eh, try emoji=discord.PartialEmoji.from_str(":envelope_with_arrow") or look for the emoji online and pass it to emoji=

maiden bloom
#

Copying it from online worked, thanks

coral lake
#

I'm following up on this (sorry for extremely late reply). I've narrowed down the occurrence. It only happens when I send the message with @ everyone in a public channel and the users spam the buttons attached to the message. Once the button spam commences, the message resends again and again for as long as they continue to spam it.

Again, ZERO circular functionality in the code, zero on_message, and a very basic button response function.

PIP attached

context: #1132206148309749830 message

maiden bloom
# little cobalt on_interaction

Do button views expire? The button I want to act off of will be created and just sit there for a long time. Can I still use a view callback in this case or does it have to be on_interaction event listener?

fervent shoal
#

hey everyone is it better to create a new thread or add to a similar thread?

lofty parcel
warm jay
#

?tag install

limber wagonBOT
#

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

warm jay
#

C:\Users\Wolfie\AppData\Local\Programs\Python\Python311\python.exe: can't open file 'C:\\GIT\\Project-Shadow-Trello-Webhook\\pip': [Errno 2] No such file or directory

#

Using python 3.11.7

#

I was told to downgrade

valid panther
#

I am testing the Persistent buttons, but when I create one and restart the bot, it throws the error

import discord
from discord.ext import commands

class MyView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None) # timeout of the view must be set to None

    @discord.ui.button(label="A button", custom_id="button-1", style=discord.ButtonStyle.primary, emoji="😎")
    async def button_callback(self, button, interaction):
        await interaction.response.send_message("Button was pressed", ephemeral=True)

class ButtonPersistentView(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.slash_command(name="persistent", description="Press the button to see the view persistence status")
    async def persistent(self, ctx):
        await ctx.respond(f"Press the button! View persistence status: {MyView.is_persistent(MyView())}", view=MyView())


def setup(bot):
    bot.add_cog(ButtonPersistentView(bot))
little cobalt
#

Du you add the view to a add_view?

valid panther
little cobalt
#

So, you have to add the view to a add_view at your bot

#

I usually add the view at the on_ready event

steep cliff
#

You’re required to add the view to your bot using bot.add_view(your_view) is what they’re saying

valid panther
#

can't it be done from the cog?

steep cliff
#

.rtfm add_view

steep cliff
#

As you can see, there’s no such function for cogs

valid panther
#

so how do I make it modular?

lofty parcel
#

commands.Cog.listener?

steep cliff
#

Basic events (on error, on ready etc) either go in the main file or listeners exist

lofty parcel
#
@commands.Cog.listener()
async def on_ready(self):
     self.bot.add_view(MyView())
valid panther
#

thank goodness for the listener

wooden turtle
#

Do i understand this correctly?
i should be able to use modal_submit with a modal dialog and then i can use defer() to do my longer processing?

lofty parcel
wooden turtle
#

aha, thank you

hexed saddle
#

im trying to create a bot and i keep getting this error: AttributeError: module 'discord' has no attribute 'Bot'
my code: ```py
import discord

bot = discord.Bot()
@bot.event
async def on_ready():
print("ready")

bot.run("")```
as well as my pip list here:

aiohttp            3.8.6
aiosignal          1.3.1
async-timeout      4.0.3
attrs              23.2.0
charset-normalizer 3.3.2
frozenlist         1.4.1
idna               3.6
multidict          6.0.5
py-cord            2.4.1
typing-extensions  4.9.0
yarl               1.9.4```
little cobalt
hexed saddle
#

lovely, thanks so much

hexed saddle
#

is there an easier way to unban people other than to just go through the ban list and unban them 1 by 1 with asyncio sleep so it doesnt get ratelimited

lofty parcel
#

If you want to unban a specific user, discord.Guild has a method

hexed saddle
lofty parcel
lapis pollen
#

hey im trying to get the ctx users Display name tried
ctx.user.global_name
ctx.user.name

doesnt work
im using latest py-cord version

#

can someone help please

lofty parcel
#

Only the github version does.

lapis dock
#

.tag pomelo

sly karmaBOT
#

Before Pomelo- Versions 2.4.1 and before

member.name          -> username
member.nick          -> guild nick name
member.display_name  -> member.nick OR member.name

After Pomelo- Versions py-cord-dev 2.5.0 and up

member.name          -> username
member.global_name   -> global display name (global nick name)
member.nick          -> guild nick name
member.display_name  -> member.nick OR member.global_name OR member.name
valid panther
#

Sorry guys, I'm looking at the operation of persistent buttons, I'm creating an option in which the user can set the max time of functionality of the button for example 1h-5h. Do you think it is a good idea to make a bot.loop.create_task(self.wait_timeout())

    def __init__(self, value_one:str=None, value_two: int= None, timeout_match: datetime=None, bot=None):
        super().__init__(timeout=None)
        self.value_one = value_one
        self.value_two = value_two
        self.timeout_match = timeout_match

        if self.timeout_match is not None:
            bot.loop.create_task(self.wait_timeout())

    async def wait_timeout(self):
        await asyncio.sleep(self.timeout_match)
        self.disable_all_items()
        self.stop()
valid panther
lofty parcel
#

Eh, im sure the release will be soon

lofty parcel
valid panther
valid panther
fresh totem
#

Hi.

async def shop_add_pack(ctx, cardpack_name: Option(str, "Name of Card Pack", choices=fetchCardSeries()), price: Option(int, "Price of Item in Shop", choices=[])):

How can I dynamically change the choices, fetchCardSeries() fetches a list of items but it gets executed at run-time and doesn't change when the command is ran again so the items stay the same even thought the list is updated.

How can I fetch the list when the command is run to get the updated list, I tried:

choices=lambda: fetchCardSeries()```

but no luck.
little cobalt
#

you have to use autocomplete for it

fresh totem
rugged lodgeBOT
#

Here's the slash autocomplete example.

little cobalt
lapis dock
#

Just a note. Users can enter something not in the auto complete. So you will need to check that they selected a valid choice yourself.

fresh totem
#

Thank you, guys!

young cove
#

Hey all. I'm trying to make a select menu conditional based on a passed variable. Any help will be much appreciated.

 class skillForm(discord.ui.View):
    def __init__(self, characterName, prevInteraction, skillsType1):
        self.characterName = characterName
        self.prevInteraction = prevInteraction
        self.skillsType1 = skillsType1
        super().__init__(timeout=None)


    s1check = False
    s2check = False
    s3check = False
    highlightSkills1 = str
    highlightSkills2 = None
    highlightSkills3 = None


    if self.skillsType1 == True:
        @discord.ui.select(
                           placeholder="Primary Skill",
                           min_values=1,
                           options=craftingSkills
                           )  # a custom_id must be set
        async def skill_callback1(self, select, interaction):
            self.highlightSkills1 = select.values[0]
            self.s1check = True
            await interaction.response.defer()

Of course the if self.skillsType1 == True doesn't work because it's outside the def. I'm probably just being stupid here. Is there a better approach?

lofty parcel
#

And add the options

fresh totem
#

Hey, how can we lockdown grouped commands to a specific server so those commands don't appear in other servers

class grindlistCommands(commands.Cog):
    def __init__(self, bot_: discord.Bot):
        self.bot = bot_

    grindlist = SlashCommandGroup("grindlist", "Grindlist Commands")

    @grindlist.command()
    async def view(self, ctx: discord.ApplicationContext):
        "View the grindlist"```
lofty parcel
#

SlashCommandGroup probably has a guild_ids param

valid panther
#

I am using the @commands.guild_only() tag in some of my commands and I can still run the command in the DM or just view it. Should I put something else in?

valid panther
lofty parcel
valid panther
lofty parcel
fast dust
#

How use Slash Package here?

little cobalt
fast dust
fast dust
little cobalt
#

that is not py-cord

fast dust
little cobalt
#

idk

lapis dock
lapis dock
#

Take a look at our guide if you are just starting

#

.tag guide

sly karmaBOT
little cobalt
#

And the user left...

lapis dock
#

they were not using Pycord anyways ¯_(ツ)_/¯

valid panther
#

commands.CommandOnCooldown and commands.errors.CommandOnCooldown is the same?

plush thicket
#

how do i get a reference message, if i use commands.slash_command?

lofty parcel
maiden bloom
#

Would sending a message to every guild (like an announcement) work or would the API not like it sending that many messages at once? Would it even work or would it take forever to actually finish running? Currently at 1,750 servers

wraith mirage
#

how do i make a new line with slash commands

lofty parcel
lofty parcel
shell radish
stray pasture
#

I just did a fresh install of my bot with the requirements and now there is a problem with Option. Where there a breaking change in the last month ? I install from: git+https://github.com/Pycord-Development/pycord

#
  File "D:\Documents\bot discord\timed_role_je\cogs\StatsCog.py", line 14, in <module>
    class StatsCog(Cog):
  File "D:\Documents\bot discord\timed_role_je\cogs\StatsCog.py", line 31, in StatsCog
    @stats.command(guild_ids=guildIds, description="Show the stats of the bot")      
     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Documents\bot discord\timed_role_je\.venv\Lib\site-packages\discord\commands\core.py", line 1256, in wrap
    command = cls(func, parent=self, **kwargs)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Documents\bot discord\timed_role_je\.venv\Lib\site-packages\discord\commands\core.py", line 693, in __init__
    self._validate_parameters()
  File "D:\Documents\bot discord\timed_role_je\.venv\Lib\site-packages\discord\commands\core.py", line 711, in _validate_parameters
    self.options = self._parse_options(params)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Documents\bot discord\timed_role_je\.venv\Lib\site-packages\discord\commands\core.py", line 769, in _parse_options
    option = Option(option)
             ^^^^^^^^^^^^^^
  File "D:\Documents\bot discord\timed_role_je\.venv\Lib\site-packages\discord\commands\options.py", line 227, in __init__
    self.input_type = SlashCommandOptionType.from_datatype(input_type)
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Documents\bot discord\timed_role_je\.venv\Lib\site-packages\discord\enums.py", line 802, in from_datatype
    if datatype.__name__ in ["Member", "User"]:
       ^^^^^^^^^^^^^^^^^
AttributeError: 'str' object has no attribute '__name__'. Did you mean: '__ne__'?
#

I install: git+https://github.com/Pycord-Development/pycord@fc7b1042c4a9a942b9996dfe96f56aac059e179c It is working on that version

valid panther
#

.pomelo

sly karmaBOT
#

Before Pomelo- Versions 2.4.1 and before

member.name          -> username
member.nick          -> guild nick name
member.display_name  -> member.nick OR member.name

After Pomelo- Versions py-cord-dev 2.5.0 and up

member.name          -> username
member.global_name   -> global display name (global nick name)
member.nick          -> guild nick name
member.display_name  -> member.nick OR member.global_name OR member.name
stray pasture
azure cobalt
#

Is Spotify classified as discord.ActivityType.listening?

unborn cargo
azure cobalt
unborn cargo
lapis dock
lapis dock
azure cobalt
#

I figured it out, I now am using isinstance(activity, discord.Spotify)

#

Since Spotify is represented by the Spotify object instead of Activity

lapis dock
stray pasture
#
aiofiles==23.2.1
aiohttp==3.9.3
aiolimiter==1.1.0
aiomysql==0.2.0
aiosignal==1.3.1
aiosqlite==0.19.0
attrs==23.2.0
certifi==2024.2.2
cffi==1.16.0
charset-normalizer==3.3.2
colorama==0.4.6
cryptography==42.0.2
frozenlist==1.4.1
idna==3.6
iniconfig==2.0.0
multidict==6.0.5
mysql-connector-python==8.3.0
packaging==23.2
pluggy==1.4.0
psutil==5.9.8
py-cord @ git+https://github.com/Pycord-Development/pycord@fc7b1042c4a9a942b9996dfe96f56aac059e179c
pycparser==2.21
PyMySQL==1.1.0
pytest==7.4.4
pytest-asyncio==0.23.4
python-dateutil==2.8.2
python-dotenv==1.0.1
pytz==2024.1
requests==2.31.0
six==1.16.0
stripe==8.2.0
typing_extensions==4.9.0
urllib3==2.2.0
yarl==1.9.4
#

The only difference is the py-cord version

azure cobalt
#

Does client.get_message(message_id) get data from the bot cache? May be pointless to use it with on_raw_message_delete if so.

rotund quarry
#

Ok this is a simple question, how can i get the value of username and print it using print()?

@bot.command(name="verify", description="Verify your account")
async def verify(ctx, username: discord.Option(str, "Put the exact in game username")): 
    username: discord.Option(discord.SlashCommandOptionType.string)
little cobalt
rotund quarry
#

The internet say is correct

#

if you want you can delet one of them

#

if is not correct

little cobalt
#

two times discord.Option?

rotund quarry
#

I tought this is not a mistake but ok, i read wrong on internet ig

azure cobalt
#

Can the bot user cache be disabled?

little cobalt
azure cobalt
#

Yes, it is for a function of the bot that must get all of the users it shares guilds with

sly ember
#

if i change bot to client, the command works again, but the command which shows me all of my coins wont work then

vestal folio
#

how to get icon from the guild

azure cobalt
vestal folio
#

Ok

#

Thanks

cloud bloom
#
    @to_do_group.command()
    async def get(self, ctx,
                  name:discord.Option(str, autocomplete=getAllToDoLists(ctx.user.id), description="The name for your to-do list.")):

I'm a bit stuck on how to structure the above. I have the function getAllToDoLists which basically gets the user's to-do lists from a database. However, how do I pull from that database with the user's id when I can't access it in the parameter?

#

I'm not sure how I should structure my code to achieve that

#

waait

#

I think I remember the autocomplete func having another parameter

#

yep that was it

#

it does have an interaction

#

AutocompleteContext

valid panther
#

I understand that this is not possible

solar sonnet
#

is there a workaround i can do to dynamically display layers in a world from an option the user selected?

wooden turtle
#

how do i use <t:{time.time() + 600}:R> in a discord bot?
description=f"Your token has been generated and expires in <t:{time.time() + 600}:R>"

wooden turtle
#

thank you kind sir

lofty parcel
rugged lodgeBOT
#

Here's the slash autocomplete example.

lofty parcel
#

.rtfm AutocompleteContext.options

sly karmaBOT
minor crescent
#

having issues with an error that has never come up in my 3+ months working on this bot

#

no clue what's causing it

little cobalt
#

What is your py-cord version?

minor crescent
#

let me update

minor crescent
#

had no errors 2 days ago

#

just opened the file today and now it's full of warnings

#

fixed it through editing pylance's typecheck overrides

waxen arrow
#

I have a bot that regularly disconnects, and after it does, I see a log message I put into on_ready, but the other functions of the bot cease, and on discord the bot appears offline. Where might I look first to work out why this might be happening?

minor crescent
#

actually

#

are there any errors in your bot's console?

waxen arrow
#

the "we have logged in as blah" message prints

minor crescent
#

does on_message function at all

waxen arrow
#

Until it reconnects, yes

#

Stuff ends up in the DB, and !last works

valid cipher
#

Hello. how can i check if the server has an active subscription?

solar sonnet
#

how can i handle multiple users running the same command at once? 9/10 times one user will recieve The application did not respond error and they still will get cd for command

shell radish
#

it's probably one of the following reasons:

  1. something to do with the way your command was written
  2. the bot's connection to the internet/cloudflare
  3. Discord was just bad
lofty parcel
valid cipher
lofty parcel
#

?tag install

limber wagonBOT
#

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

valid cipher
#

jup. worked. now i only have to understand how to actually implement it without any documentation...

#

documentation has also a master branch. so that should work for me

delicate scroll
#

Is it possible to check for a users role outside of a command event, specifically I have an on message event that will send the message off to an ai for a response but I want to limit who is actually able to speak to the ai / have their messages read by it

All I keep finding results on is checking roles for commands but that doesn't really work for what I've got cooking

lofty parcel
delicate scroll
lofty parcel
#

You have to get the role

#

.rtfm get_role

sly karmaBOT
delicate scroll
lofty parcel
delicate scroll
#

No i know i just mean like when I'm printing stuff out to console and something looks like itll work one way but doesn't

lofty parcel
rich jolt
#

Hi
I'm running version pycord 0.1.1 (don't ask..)
And now getting the error
KeyError: <StickerFormatType.unknown_4: 4> when starting the bot.
I assume it's due to a breaking change and I need 2 update? Is there a version that I can update to to fix this without having to work on any breaking changes/adjust code? I only have mobile rn 😅

limber terrace
#

Updates are always recommended during security and compatibility changes

#

pandapopcorn so yes, run the update

cunning stirrup
#

hey guys i have a stupid question is it possible for a bot to see a users bio or like description ?

unkempt cipher
cunning stirrup
#

okey thx

little cobalt
azure cobalt
#

pypi pycord is for video decode

little cobalt
azure cobalt
little cobalt
#

ye

azure cobalt
little cobalt
#

?tag requests

limber wagonBOT
#

Why you should not use the requests library for your bot
requests is a popular HTTP library for Python. It is however not a good option for Discord bots, since it is not async and blocking.

This essentially means that your bot will not be able to execute any code at all while a request is happening. Since requests usually take a few seconds to complete, this can have a detrimental effect on your bot's performance. E.g if a user executes a command that performs a request taking 5 seconds to complete, no one else will be able to use your bot for those 5 seconds.

Please look at using a HTTP library that has async support, such as aiohttp or httpx

azure cobalt
#

oh, ok

#

thanks

little cobalt
#

np ^^

round heart
lapis dock
lapis dock
round heart
azure cobalt
#

But this is Discord...

round heart
#

Our server attracts a lot of Discord newbies in general.

round heart
azure cobalt
#

I don't think any bot can read the About Me

round heart
#

Correct, that's the discussion, Wolfy asked if Discord's built-in AutoMod could, but it cannot.

#

So there are no available protections for users being duped by fake role names in scammer bios.

azure cobalt
#

Unless someone wants to check all of the bios

round heart
#

Yeah, we do occasionally. But that's a shitty mod experience.
Like this should never be able to happen. People brand new to Discord can't always tell that's falsified, especially through DM.

azure cobalt
#

Discord should have that in the API. If users can see it, bots should be able to see it.

lofty hedge
solar sonnet
solar sonnet
#

Oh wait, my bad, I am deferring it and it throws that error

lapis dock
shell radish
#

i thought you could access that info with oauth2

solar sonnet
#

i remember being in a server which had access to check your current activity and if it was a specific one you'd get an auto ban

lofty hedge
azure cobalt
#

unrelated to bios and pronouns

round heart
azure cobalt
#

Is it possible to get connections from a user profile, such as eBay and Xbox?

shell radish
#

same thing with oauth2

#

except this one is a confident yes

deft kestrel
#

how to create a post in a discord forum?

#

and how to delete the post

young skiff
#

I am trying to show an emoji in the state of my bot, but it is not showing, nor does it return any error, the text is shown but the emoji is not

await bot.change_presence(activity=discord.CustomActivity(name=status, emoji=discord.PartialEmoji(id=1191100279106576526, name='burple_check'),status=discord.Status.online))
edgy nest
#

which is stupid

#

but it is what it is

young skiff
azure cobalt
young skiff
warm jay
#

VScode can't find Pycord

#

Oh

#

fixed it

#

Changed py versions

azure cobalt
tidal estuary
#

I had all my slash commands disappear, restarted the bot a million times, re-invited it, still only some of them are showing up yet all cogs showing as loaded during startup. Any suggestions or troubleshooting ideas? I didn't change anything which is odd, but the commands have been out all day.

sterile bobcat
#

I am making a Game that involves clicking a button, the game has teams and once a team has clicked a button they are not allowed to press the button again. The game itself is contained in a Cog and I want the Cog to be informed about who pressed the button, how can I do that?

class QuestionPost(discord.ui.View):

        def __init__ (self, question: JeopardyQuestion, voice: discord.StageChannel):
            """
            Initializes the QuestionPost instance.

            Args:
                question (JeopardyQuestion): The question to display.
                voice (discord.StageChannel): The voice channel to move the user to.

            """
            super().__init__(timeout=None)
            self.question = question
            self.voice = voice

   
        @discord.ui.button(label="Buzz In", style=discord.ButtonStyle.blurple)
        async def button_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
            button.disabled = True
            user = interaction.user
            button.label = (f"{user.name} buzzed in!")         
            await interaction.response.edit_message(view=self)
            await user.move_to(self.voice)
            await user.request_to_speak()

Here is where I want the Button to Update:

async def show_question(self, uuid : str):
        """
        Asynchronously shows a question to the players.

        Args:
            uuid (str): The UUID of the question to show.
        """
        if uuid in self.question_post.keys():
            question_data = self.game.get_question_by_uuid(uuid)
            embed = discord.Embed(
                title="🌟QUESTION🌟",
                description= "Here is the question again! \n" ,
                color=discord.Color.random()  
            )
            question = QuestionPost(question_data, self.stage)
            await self.question_post[uuid].edit(embed=embed, view=question)
lofty parcel
#

You could probably use a bot var

shell radish
lofty parcel
#

I assumed that would be obvious

shell radish
lofty parcel
sterile bobcat
sand reef
#

I have modals set up in separate modules that get imported to my main script. I want to create a new channel with the command and then send the interaction response to that channel, but I'm struggling to find out the proper flow for this. Any advice?

lofty parcel
sand reef
lofty parcel
#

What are you trying to do?

sand reef
#

I'm creating a bot that integrates with my business panel and allows users to submit tickets via interaction.

#

I have other bots that use modals but they, as you said, send reponses to the same channel and that works for those.

lofty parcel
#

You could just send an ephemeral response.

#

And then send whatever data the user submitted with channel.send

sand reef
#

Well, the purpose of the creation of the new channel would be that it would send and receive messages for the ticketing system in that channel.

#

That logic is pretty easy to do since it just uses API, but that initial interaction is where I'm struggling.

stray pasture
#

I am trying to create a Option in a slash command with a Enum. I am not sure why it is not working:

    @discord.option(
        "language",
        description="The language of the output",
        default=Language.MANDARIN,
        type=Language
    )
    @slash_command(guild_ids=guildIds, name="membership", description="Show you current membership")
    async def show_membership(self, ctx: ApplicationContext, language: Language):
        await self._show_timed_role_of_member(ctx, ctx.author, False)

i get the error:

stray pasture
#
class Language(Enum):
    ENGLISH = 1
    MANDARIN = 2
sand reef
# lofty parcel What's the flow exactly?

User submits interaction. Simple enough.

The data from the interaction, which includes an account email and the query itself, is sent through my panel's API to the ticketing system, which creates a new ticket.

A new channel is created for the user, and the information they submitted from the ticket is the first message from the bot.

Any responses to the channel by the user or staff member are collected by the bot, embedded, and added to the ticket on the ticketing system.

The only thing I really am struggling with is returning the data from the modal, since I've only ever used modals to return ephemeral messages or otherwise in the same channel it is sent in.

lofty parcel
#

Guild.create_text_channel returns the created channel

#

You use that returned object to send whatever info you want

sand reef
#

No, the issue is accessing the data submitted from the modal.

rugged lodgeBOT
#

Here's the modal dialogs example.

lofty parcel
#

You can see there how you access the data.

sand reef
#

I suck at explaining my question, I'm sorry. So pulling from the example, is there a way to return the value of InputText to the modal_message command so that it can be used away from the modal class?

#

Keeping in mind my modals are placed in a separate module

cloud bloom
#

can you have async innit

outer niche
#

I feel like there is a joke to be made using the spelling error but I can't find it

digital zenith
#

Heyo! Was just wondering what I need to do to get it to recognise/find the discord module.

Code

``
import discord
import config

bot = discord.Bot()

@bot.slash_command()
async def hello(ctx, name: str = None):
name = name or ctx.author.name
await ctx.respond(f"Hello {name}!")

@bot.user_command(name="Say Hello")
async def hi(ctx, user):
await ctx.respond(f"{ctx.author.mention} says hello to {user.name}!")

bot.run(config.TOKEN)
``

My error:
line 1, in <module> import discord ModuleNotFoundError: No module named 'discord'

#

🙂

outer niche
digital zenith
#

yeah

#

Am I meant to have the discord/discord.py module installed?

#

I tried with them and it didnt work

digital zenith
floral ice
#

how can i add more than 25 choices for slash command?

hallow copper
#

install py-cord

digital zenith
#

oki

hallow copper
#

then you should be able to import it

floral ice
hallow copper
#

that’s a great question

digital zenith
#

same error

#

😦

hallow copper
digital zenith
#

dont think so

#

xD

hallow copper
#

hmm

digital zenith
#

i just wanted to use something other than nextcord with a simpilar api like this

hallow copper
#

yis this one way better

digital zenith
#

?

hallow copper
#

pycord better

digital zenith
#

ye lol

hallow copper
#

we have her

digital zenith
#

oo

hallow copper
#

oki good night

digital zenith
#

gn

little cobalt
#

Else the limit is 25

tepid coyote
#

is there any reason why interaction.resonse.send_message doesn't show as a function in my ide (pycharm) the resonse doesn't show that send_message id a fnction that is available to it

shell radish
#

also that’s not how python intellisense works

tepid coyote
shell radish
#

iirc, they only go one layer deep

#

so it would autocomplete interaction.response

#

but not response’s attrs

tepid coyote
#

okie

#

just was a bit wierd

modern cedar
#

hi

warm jay
#

I'm getting a discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

Why is that

#

What permission does it need

edgy nest
shell radish
modern cedar
#

ok I fixed my prpeviois error

#

but Now a small error

#

message = await ctx.respond(embed=embed, file=(discord.File(img_bytesio, filename="riddle_image.png")))

correct_answer_given = False

def check(answer_msg):
 print(f"Received message: {answer_msg.content}")
 print(f"Reference message ID: {answer_msg.reference.message_id}")
 print(f"Expected message ID: {message.id}")
 return (
    answer_msg.author != bot.user
    and answer_msg.reference
    and answer_msg.reference.message_id == message.id
)
modern cedar
shell radish
#

respond returns an interaction, not a message

modern cedar
#

So how I get the Id of the embed I sent?

#

through respond

#

When I use use answer_msg.reference.message_id
It gives the correct value

#

but that's for replies

#

I need it beforehand to check

#

it

shell radish
#

that should just be await ctx.interaction.original_response()

modern cedar
#

wdym

shell radish
#

that is how you would get the message associated with the message you responded with

modern cedar
#

yeah but I need to check it right

#

basically the bot will only those answers that are replied to the riddle embed

shell radish
#

I understand

modern cedar
#

yeah

shell radish
#

you know how to get a message's ID right

modern cedar
#

yes

shell radish
#

so you can check it

modern cedar
#

in this code

shell radish
#

interactions are not messages

#

so the ID is different

modern cedar
#

that's what I am asking

shell radish
#

if await ctx.interaction.original_response() returns a message, what does that mean

modern cedar
#

message = await ctx.interaction(embed=embed, file=(discord.File(img_bytesio, filename="riddle_image.png")))

shell radish
#

no

modern cedar
#

I see

shell radish
#

you would respond as usual, without the message assignment. Then, use await ctx.interaction.original_response() to store the message object

modern cedar
#

you are saying that I get the refrence from interaction itself?

#

instead of the message

shell radish
#

the reference message stays the same

modern cedar
#

await ctx.respond(embed=embed, file=(discord.File(img_bytesio, filename="riddle_image.png")))
message = await ctx.interaction.original_response()

modern cedar
shell radish
modern cedar
#

yeha but it stores the id of the interaction

shell radish
#

no, this message is a Message object

modern cedar
#

oh ok

#

So in the end what do I do

#

in the code

shell radish
#

the only thing you need the change is outside the function

modern cedar
#

I just want the message id of the interaction instead of the intereaction id
So that the reference would be equal to it.

#
message = await ctx.respond(embed=embed, file=(discord.File(img_bytesio, filename="riddle_image.png")))


    correct_answer_given = False

    def check(answer_msg):
     print(f"Received message: {answer_msg.content}")
     print(f"Reference message ID: {answer_msg.reference.message_id}")
     print(f"Expected message ID: {message.id}")
     return (
        answer_msg.author != bot.user
        and answer_msg.reference
        and answer_msg.reference.message_id == message.id
    )

    try:
        answer_msg = await bot.wait_for('message', check=check, timeout=30.0)```
shell radish
#
+ await ctx.respond(embed=embed, file=(discord.File(img_bytesio, filename="riddle_image.png")))
+ message = await ctx.interaction.original_response()
- message = await ctx.respond(embed=embed, file=(discord.File(img_bytesio, filename="riddle_image.png")))

these are quite literally all the changes you need in your code

shell radish
#

yes

modern cedar
#

and I will get it

#

ok

shell radish
#

do you understand OOP lol

modern cedar
#

english is not just my mother tongue

#

i am making a discord bot first time

shell radish
#

do you understanding object-oriented programming

modern cedar
#

i know you are talking about instance variable of the message class

#

of which the message object is created

shell radish
#

ok

modern cedar
#

finally worked

#

thanks @shell radish

shell radish
#

yw

modern cedar
#

im follow you on github in return

shell radish
#

ty

cloud bloom
#

how does one create a followup response for a modal?

#

Docs say Interaction.response.followup has:

Returns the followup webhook for followup interactions.
But I have no idea what that extends from

lofty parcel
#

interaction.response.followup.send?

cloud bloom
#
    await interaction.followup.send_modal(AddItemModal(message=self.view.message, title=self.title))
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Webhook' object has no attribute 'send_modal'
#

wait...

#

OH

lofty parcel
#

Followups can't send modals

cloud bloom
#

why

lofty parcel
#

Ask discord

cloud bloom
lofty parcel
#

Don't defer.

cloud bloom
#

that might take a while

lofty parcel
#

Send a button then that opens the modal

cloud bloom
#

ok

rotund harness
#

How would i get Py-cord 2.5 so the pomelo works properly? (Considering py-cord-dev doesn't work anymore)

#

Nevermind (git+https://github.com/Pycord-Development/pycord)

grim estuary
#

Hello! How I can add buttons when is View initialized? (I can't figure out how to bind a callback function to a button)

class ViewClass(View):
    def __init__(self, ...):
        super().__init__(timeout=...)
        self.add_item(... # here)
#

I take it I should create a subclass for the buttons? I just don't see any other way out

class ButtonClass(Button):
    def __init__(self, ...):
        super().__init__(...)

    def callback(self, button: Button, interaction: Interaction):
        ...
rugged lodgeBOT
#

Here's the confirm example.

lapis dock
upper drift
#

is it necessary to make a select class? cant we just declare it without it

#

I need examples

shell radish
#

it depends on your implementation

round heart
#

Uhh, anyone ever seen this before?

pip3 install -U py-cord@git+https://github.com/Pycord-Development/pycord

WARNING: Generating metadata for package py-cord produced metadata for project name unknown. Fix your #egg=py-cord fragments.
Discarding git+https://github.com/Pycord-Development/pycord: Requested unknown from git+https://github.com/Pycord-Development/pycord has inconsistent name: filename has 'py-cord', but metadata has 'unknown'
ERROR: Could not find a version that satisfies the requirement py-cord (unavailable) (from versions: 1.7.3, 2.0.0b1, 2.0.0b2, 2.0.0b3, 2.0.0b4, 2.0.0b5, 2.0.0b6, 2.0.0b7, 2.0.0rc1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.1.2, 2.1.3, 2.2.0, 2.2.1, 2.2.2, 2.3.0, 2.3.1, 2.3.2, 2.3.3, 2.4.0, 2.4.1)
lofty hedge
#

In some updates on this server

round heart
lofty hedge
#

Oh I misread I dunno

round heart
#

Updated setuptools and pip itself and it magically worked. Friggin weird.

digital zenith
#

Hiya,

So when trying to run my bot I get this error:

AttributeError: module 'discord' has no attribute 'Bot'

This was not happening yesterday.

#

Here is my code:

import discord
import asyncio
import os


bot = discord.Bot(command_prefix='!%') # Defining the bot

@bot.event # Logged in
async def on_ready():
    print(f'I am logged into the discord api as: {bot.user}')
@bot.event()
async def on_member_join(self, member):
        await member.send('Welcome to the server!')
        auto_assign_role = discord.utils.get(member.guild.roles, name='Member')
        if auto_assign_role:
            await member.add_roles(auto_assign_role)
            print(f'Auto Added Member Role to {member.display_name}')

@bot.slash_command(name='ping', description='Check my latency!') # Ping Command
async def ping(ctx):
    latency = round(bot.latency * 1000)
    embed = discord.Embed(
        title='Pong! :ping_pong:',
        description=f'My current latency is: **{latency}ms**',
        color=discord.Color.blurple()
    )
    await ctx.respond(embed=embed)

@bot.slash_command(name='donate', description='Donate to the creators of the bot') # Donate Command
async def donate(ctx):
    embed = discord.Embed(
        title='MAGI WALLET: 96Ld2MYadxQbNCBGcbPYDhXkEDurNbGH65',
        description='Donating helps the bot by keeping it online',
        color=discord.Color.blurple()
    )
    await ctx.respond(embed=embed)

# Cogs Stuff only beyond this point


async def load():
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            bot.load_extension(f'cogs.{filename[:-3]}')

@bot.command(name='reload', description='Reloads a cog.')
async def reload(self, ctx):
    async with ctx.typing():
        embed = discord.Embed(
            title='Reloading all cogs.',
            color=0x808080,
            timestamp=ctx.message.created_at
        )
        for ext in os.listdir('./cogs/'):
            if ext.endswith('.py') and not ext.startswith('_'):
                try:
                    self.bot.reload_extension(f'cogs.{ext[:-3]}')
                 ```
#

embed.add_field(
                        name=f'Reloaded: `{ext}'
                    )
                except Exception as e:
                    embed.add_field(
                        name=f'Failed to reload: `{ext}`',
                        value=e
                    )
                await asyncio.sleep(0.5)
        await ctx.respond(embed=embed)

@bot.command(name='unload', description='Unloads a cog.')
async def unload(self, ctx):
    async with ctx.typing():
        embed = discord.Embed(
            title='Unloading all cogs.',
            color=0x808080,
            timestamp=ctx.message.created_at
        )
        for ext in os.listdir('./cogs/'):
            if ext.endswith('.py') and not ext.startswith('_'):
                try:
                    self.bot.unload_extension(f'cogs.{ext[:-3]}')
                    embed.add_field(
                        name=f'Unloaded: `{ext}'
                    )
                except Exception as e:
                    embed.add_field(
                        name=f'Failed to unload: `{ext}`',
                        value=e
                    )
                await asyncio.sleep(0.5)
        await ctx.respond(embed=embed)

async def main():
    await load()
    await bot.start('my token you no get xD')

asyncio.run(main())
little cobalt
#

Also discord.Bot does not have a prefix

digital zenith
#

Whats the pip list

little cobalt
#

You dont know what the pip list is?

digital zenith
#
Package            Version
------------------ ---------
aiohttp            3.8.6
aiosignal          1.3.1
annotated-types    0.5.0
async-timeout      4.0.3
asyncio            3.4.3
attrs              23.2.0
certifi            2022.9.24
charset-normalizer 2.1.1
colorama           0.4.6
decorator          4.4.2
disnake            2.7.0
frozenlist         1.4.1
idna               3.6
imageio            2.22.4
imageio-ffmpeg     0.4.7
moviepy            1.0.3
multidict          6.0.5
numpy              1.23.5
packaging          23.1
Pillow             9.3.0
pip                24.0
proglog            0.1.10
py-cord            2.4.1
pydantic           2.4.2
pydantic_core      2.10.1
replicate          0.13.0
requests           2.28.1
tqdm               4.64.1
typing_extensions  4.8.0
urllib3            1.26.13
yarl               1.9.4
digital zenith
#

is disnake needed?

little cobalt
#

No

#

Uninstall it and py-cord and only reinstall py-cord

red mist
lofty parcel
autumn gust
#

okay, I may need some guidance here:

#

I want to make a bot that works similar to an announcement channel w/ publishing, right?

#

the issue is, how do I copy the message, word for word and with an attachement?

#

the attachement will always be a .png

#

and it will always contain one

lofty parcel
sly karmaBOT
#

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

lofty parcel
#

Ok misspelled

#

.rtfm Message

little cobalt
red mist
#

Oh wow thanks didnt know that existed.

noble flax
#

Is it possible to create a modal or something similar off the back of a slash command from a user for them to select a datetime from a dropdown?

lofty parcel
noble flax
lofty parcel
#

Only text inputs.

noble flax
#

I'm thinking of the bot messaging a user and them being able to choose the date-time from a dropdown.

#

So its free-type options for the user only?

lofty parcel
#

Yes.

noble flax
#

No worries - thanks for your help.

lofty parcel
#

You could just send a normal select menu.

#

Instead of a modal.

opal hemlock
#

i have a command /trivia with parameter topic: which is important but is it possible to have a optional parameter like language: where if user doesn't type anything it will just be handled by code? Or something like that

shell radish
#

yes

rugged lodgeBOT
#

Here's the slash options example.

opal hemlock
#

aha

finite plover
#

How to sync slash commands?

little cobalt
#

but Im not sure if it works to 100%

finite plover
#

Thx

lethal loom
#

Have the AutoComplet a limit

little cobalt
lethal loom
# little cobalt No not really

okay, but why i dont see the 32 from this list
['Paper (1)', 'PurPur (2)', 'Fabric (3)', 'Forge (4)', 'Bungeecord (5)', 'Wordpress (6)', 'Basic (7)', 'THE ISLE (8)', 'Euro Truck Sim 2 (9)', 'American Truck Sim (10)', 'Satisfactory (11)', 'Python (12)', 'CurseForge Modpacks (13)', 'ARK (17)', 'Terraria (18)', 'tModLoader (19)', 'Next Cloud (20)', 'TVS - Temp Voice System (21)', 'TS - Ticket System (22)', 'ECS - Embed Creator System (23)', 'BCS - Button Creator System (24)', 'MH - MySQL Handler (25)', 'Python Lifetime (27)', 'Palworld (29)', 'Webhook Test (31)', 'Test V1 (32)']

little cobalt
#

discord only shows 25 of it

#

the other ones have you to type to see them

#

that is how autocomplete also works at your Phone

hard kettle
#

This is in an async def function(): its saying key word url

 view = discord.ui.Button(label = "CLAIM", url = "https://gg.gg")
 await ctx.respond(embed = embed, view = view)
finite plover
#

ahh how to add slash command in cog?

#

it doesn't work

rugged lodgeBOT
#

Here's the slash cog example.

outer niche
#

@finite plover

opal hemlock
#

how do i stop defer answer thing if it sent alr sent embed

#

nvm

#

got it

#

im dumb

finite plover
lethal loom
#

Hi, how can react when a user switch the side from a paginator

lofty parcel
#
view = discord.ui.View()
view.add_item(discord.ui.Button())
lofty parcel
lethal loom
#

yeah but idk how can i work with thios

lofty parcel
#

You'd subclass the paginator and override the method

#

Do your stuff, then call the super() method to not lose what the method was originally doing

lunar isle
#

AttributeError: 'SlashCommand' object has no attribute 'command'
What's the meaning of this?

#

@image.command(name="some command", description="some description")
@commands.cooldown(2, 7200, commands.BucketType.user)
@commands.has_permissions(manage_messages=True)

#

lol nvm

#

i got the function defined wrong

lapis dock
#

My guess is it was supposed to be SlashCommandGroup

lunar isle
#

i forgot to change the function name

graceful swift
#

Hi. I have a quick question.

If I create a task loop, specifying it's looping interval times in a variable
@tasks.loop(seconds=delay_seconds)

Can I update the variable time to update the loop accordingly, or I need to stop the loop and start it again to make the change take affect?

graceful swift
#

Very useful answer. Thanks.

#

Answer was loop.change_interval method if anyone else have the same question.

maiden bloom
#

Can I populate a command option choice with a guild's current automod rules?

rugged lodgeBOT
#

Here's the slash autocomplete example.

finite plover
#

why i add new slash command (now there are 8) but it doesn't show up?

lofty parcel
finite plover
lofty parcel
finite plover
maiden bloom
high pilot
#

can the bot wait for message inside a button callback?

#

it doesnt seem to so when i am doing it

#
    async def button_callback1(self, button, interaction):
        
        button.disabled = True
        msg = await bot.wait_for("message", timeout = None)

deft bronze
#

Im getting a certificates error when i try to launch my bot

#

idk why

#

from exc
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1006)')]

high pilot
sly karmaBOT
#

Tag not found.

remote meteor
#

uhh

lapis dock
#

.tag sslfix

sly karmaBOT
#

If you're getting the [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1108) error on a Windows host do the following:

Download and install this certificate here: https://crt.sh/?id=2835394
--> It can be installed by double-clicking the file and installing it to Local Computer, download link location: https://beans-took-my-kids.reeee.ee/38qB2n.png

For those curious, it was caused by this:
https://support.sectigo.com/Com_KnowledgeDetailPage?Id=kA03l00000117LT

lapis dock
#

actually might not be the same thing

round heart
round heart
#

Is there still no way of getting a member's chat history without iterating through every channel?

azure cobalt
#

Then separates that data into each database for each user

nimble pilot
#
@commands.Cog.listener()
   async def on_button_click(self, interaction: discord.Interaction):``` is there such an event in pycord?
little cobalt
#

its on_interaction

#

but that triggert all the interaction stuff so you have to filter it

nimble pilot
#

How do I determine what type of interaction is button click ?

round heart
nimble pilot
#

how to handle on modal submit event?

valid panther
#

I'm making a view to return if it has interacted, i.e. an on_click_button:

# View
class ConfirmView(discord.ui.View):

    def __init__(self):
        super().__init__(timeout=None)
        self.is_confirmed = False

    @discord.ui.button(label="Confirm", style=discord.ButtonStyle.green, emoji=f"{Emojis.green_tick.value}")
    async def confirm(self, button: discord.ui.Button, interaction: discord.Interaction):

        self.is_confirmed = True

        await interaction.response.edit_message(
            content=f"{Emojis.pensil_edit.value} Cleaning {interaction.user.mention}...",
                                                view=None,
                                                embed=None)
# command /example
    async def example():
        #--
        view = ConfirmView()
        await ctx.respond(embed=embed, view=view, ephemeral=True, delete_after=120)
        await view.wait()
        #--
        if view.is_confirmed:
          print("On click")

This should be correct?

lofty parcel
valid panther
lofty parcel
azure cobalt
lethal loom
#

Hi, how can i add to my slashcommandgroup a nother group like test add <command>
pr test remove <command>

lofty parcel
#

You can't

minor crescent
#

is there an easy way to run a function at the start of every hour

little cobalt
#

you mean instead of a task?

minor crescent
#

cause afaik tasks only use relative time (seconds from x) instead of set times

rugged lodgeBOT
#

Here's the background task example.

round heart
#

I still like aiocron a bit more than internal tasks.

shell radish
minor crescent
round heart
#

Only downside to aiocron is that you can't use their decorators with Cogs (or any class), so you have to define and start them from __init__ (or a method called from init)

round heart
#

re: message deletion, when are messages "bulk deleted"? Does that happen when you ban a user and opt to remove all messages from 'x' time?

shell radish
#

banning has an option to remove messages

#

but bulk deleting is its own separate thing

round heart
shell radish
#

it’s an api thing

obsidian stratus
#

Quick question, does the library offer some way to clear cache or refresh the bot? My bot reaches upto 4 gb ram when it’s idle is only 200mb and is in 25 servers only (it’s just a basic level bot)

round heart
obsidian stratus
obsidian stratus
#

Pretty basic, i feel it’s the buttons which act up, any example gist code link to make memory optimised buttons?

shell radish
obsidian stratus
#

It’s the level roles button, servers can customise this upto 3 buttons (my bot is being used in big servers tho like 99k members)

obsidian stratus
#

Pretty sure I have overwritten it in the next line to enable members intent and presences intent

shell radish
#

yeah members intent is why you have such a high memory usage then

obsidian stratus
#

Oh I see, thanks for lmk

shell radish
#

the buttons are negligible in comparison

obsidian stratus
#

If I turn it off, will it affect the bot’s ability to sense messages to add xp

obsidian stratus
shell radish
round heart
#

Members? Probably not, if it has messages.

obsidian stratus
azure cobalt
#

Is there a way to run a function at a specific time every day?

shell radish
#

#1132206148309749830 message

azure cobalt
#

Oh, it is also in the docs, I am blind

supple wraith
#

i need help im trying to attach a callback to an existing button everytime the bot is started but its not doing anything

async def suggestion_callback():
    print("Works")

@bot.event
async def on_ready():
    print("Ready!")

    channel = bot.get_channel(1206445575759724619)
    message = await channel.fetch_message(1208606430924636221)
    view = discord.ui.View.from_message(message)
    view.children[0].callback = suggestion_callback
#

the message referred to does have a valid button view

stray pasture
#

does async for ... in audit_logs retrieves all the entries at first, or does it fetch them as needed ?

stray pasture
#

Also the oldest_first options does not seems to be working. It return the newest_first

#

In the docs it says oldest_first (bool) – If set to True, return entries in oldest->newest order. Defaults to True if after is specified, otherwise False.

stray pasture
lofty parcel
#

Use persistent views if you want callbacks to persist

rugged lodgeBOT
#

Here's the persistent example.

supple wraith
#

nevermind it was just bot.add_view(MyView())

round heart
#

nm, it was being weird. Sometimes it sends bulk, sometimes not.

#

Is there a way to determine whether a Member is banned in the current guild/server? Doesn't seem like it, but asking in case it's buried somewhere I'm not looking.

round heart
#

Need some brainstorming assistance -- So ban and message deletion are separate events, and ban reasoning is even more separate, being in the Audit Log. I always want to alert (to a channel) when a user has been banned, but I'd also like to get the last message or two that was deleted, if that option was selected.

My current ban event hook attempts to grab the Audit Log entry and display that in the alert. My new hook sets the user id in an internal dict so that on_message_delete/on_bulk_message_delete can be matched to a ban event.

So what might be a good code path to include that in such an alert, if available, knowing that there may be times a user is banned but no message delete event would be fired.

Ban Event -> Catch Deleted Message(s) via Event -> Fetch Reason -> Display completed alert
Ban Event -> No Assoc Delete Event -> Still Fetch Reason -> Display completed alert

deft bronze
#

If i need to wait an hour after a command to make the bot send a message

#

should i asyncio.sleep or use other thing

lofty parcel
little cobalt
lofty parcel
little cobalt
#

Wasn't it like 15 minutes?

lofty parcel
little cobalt
#

oh ok?

lofty parcel
#

Docs don't mention any limit.

azure cobalt
#

Is it possible to pass parameters to a Cog?

shell radish
azure cobalt
#

Do I just add a non-keyword argument to load_extension?

#

How do I pass the parameters?

shell radish
azure cobalt
#

Actually an extension (I often get confused on the two). It is for running something before all of the cogs are loaded in setup(client) if a certain command line flag/argument is present.

shell radish
#

so how would checking that inside the cog help

azure cobalt
#

I forgot I could actually use sys.argv within an extension

errant trout
little cobalt
#

No

#

I mean asyncio.sleep

errant trout
#

sleep doesn't necessarily have a limit, it could just be considered unreliable the longer you sleep

errant trout
#

I mean, it's fine to use it if it works for you

#

I just personally opt for tasks if I'm waiting for anything beyond a few minutes

round heart
#

Just shitposting on the being “considered unreliable the longer you sleep”

errant trout
#

Ah LOL

stray pasture
#

is there a way to fetch audits logs without discord.audit_logs ? The current implementation seems broken

#

it fetches multiple times the same logs

stray pasture
#

i found a solution for it. You just need to change in the after strategy self.after = Object(id=int(entries[0]["id"])) to self.after = Object(id=int(entries[-1]["id"])) . Because when using after, list is reversed and appears in ascending order (older entries first). So you want the after to be the newest entry (the last one). Also removed the oldest_first options. Now the before and after are behaving as expected

#

in AuditLogIterator

coral snow
#
import discord
from discord.ext import commands
from globalsupport import config_support

class Weiterleitung(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_voice_state_update(self, member, before, after):
        channelweiterleitung = self.bot.get_channel(config_support().weiterleitung_id)

        if not before.channel or before.channel and after.channel:
          if after.channel.id == config_support().warteraum_id:

            nickname = member.nick
            name = member.name

            if nickname == None:
              if name.startswith("@"):
                await member.move_to(channelweiterleitung)
                
            if nickname != None:
              if nickname.startswith("@") or name.startswith("@"):
                await member.move_to(channelweiterleitung)
        else:
          return


def setup(bot):
    bot.add_cog(Weiterleitung(bot))

this is my cog, to move people to a different channel when their name starts with "@"
if i join the channel with a "@" it moves me but if i then remove the "@" and join the channel again it still moves me

#

does anybody know why?

sage tendon
#

print both of the variables and see what they actually contain, then you can troubleshoot with that info

#

most probably one of those variables prefixes an @ like @username

#

btw, else: return can be completely removed

grim estuary
#

Hello! What does py-cord documentation version v0.1 mean? Is this the master?

sage tendon
#

context?

grim estuary
# sage tendon context?

Master version has file READ_ME, at the bottom of it is a link to the documentation v0.1. I tried to find documentation for this version

frail ocean
#

Can someone explain me how i use the on message cooldown in a cog

lapis dock
shell radish
frail ocean
shell radish
minor crescent
#

is there a way to pass variables to extensions, or is there an on_load or smth for cogs? i need to establish a database connection when I load my cogs

sage tendon
#

i already replied to you

rotund quarry
#

oh

azure cobalt
#

how are subcommands like this made?

rugged lodgeBOT
#

Here's the slash groups example.

#

Here's the slash cog groups example.

shell radish
#

@azure cobalt ^

azure cobalt
#

cool, thanks

ivory beacon
#

can't fetch_channel(id)
why ??
also get_channel(id) retuning None

limber wagonBOT
#
Tags (117)

yt-tutorials, youtube, xy, wavelink, virtualembed, usernames, usercmd, update, unofficialguide, um_cmds, tryitandsee, tokens, token, timer, tias, this, tcr, tca, tags, tagrules, swasvid, subcommands, sslfix, sqli, solved, snowflake, slashcommandmention, slashblog, rie, restartcmd, requests, replit-install, replit, removeall, pythonversion, pythonserver, python, practices, pp, pomelo, persistant_view, paste, partial_objects, oracle, option, oop, om, official, objects, notpycord, norepl, nojson, nohelp, nohello, no_status, name-conventions, mybot, msgcmd, mongodb, modal, missing_access, message-content, lp, logging, localfile, learnpython, json, intents, install_git, install, inline-fields, importerror, idw, ide, how2sql, helpgist, guide, git, gif_avatar, getalpha, get_x, get-help, gather, fork, forbidden, exception, examples, ex, ephemeral, eh, docs, discord.app, discord.Bot, deploy, commandnoshow, colors, codeexamples, codeblock, cmd-limits, closing, client, chatgpt, buttons2, buttonlimit, bridge, breaking-changes, botvar, bitwise, asset, applicationcommands-registration-delay, announcement_channel_options, aiohttp, activedevbadge, Woc, Timestamps, DMChannel, 429

#
Tags (1)

exception

lofty hedge
#

?tag exception

loud kayak
#

please provide code or else i cannot help you.

shell radish
ivory beacon
ivory beacon
ivory beacon
lofty hedge
#

how do you do the gif avatar

#

?tag gif_avatar

limber wagonBOT
#

How to upload an animated avatar for your bot

To use and upload an animated avatar you can run the following snippet as standalone script:

import discord
import asyncio

# Intents to enable certain events
intents = discord.Intents.all()

# Create a Discord client instance with intents
client = discord.Client(intents=intents)

# Event to handle bot's initialization
@client.event
async def on_ready():
    print('Logged in as {0.user}'.format(client))

    # Upload animated avatar
    try:
        with open('yourpicture.gif', 'rb') as avatar:
            await client.user.edit(avatar=avatar.read())
        print('Animated avatar uploaded successfully!')
    except Exception as e:
        print('Failed to upload animated avatar:', e)

# Run the bot
client.run("YOUR_TOKEN")

That should be all, have fun!

ivory beacon
#

but the fun fact is i run the code by eval and it's working 🙂
idk whyyy

#

print(bot.get_channel(1101552767404888084))

this is working in on_message()
but not working in other function

loud kayak
#

run pip freeze in your terminal as well and send the output.

ivory beacon
loud kayak
ivory beacon
loud kayak
#

as a .txt file

ivory beacon
#

ok wait

ivory beacon
loud kayak
#

if you're just using pycord for your project, you don't need that many packages.

#

do you have git installed on your machine? @ivory beacon

ivory beacon
#

yeap

loud kayak
#

.install

sly karmaBOT
#

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

loud kayak
#

run the last one to install from the source

#

probably has a fix to that

ivory beacon
#

ok let me check

loud kayak
#

i saw

shell radish
#

use ```py
channel = bot.get_partial_messageable(id)
await channel.send(...)

ivory beacon
shell radish
#

where are you calling this function

loud kayak
#

like i asked, but won't give the code

ivory beacon
shell radish
loud kayak
#

no, where are you calling that function

ivory beacon
#

let me push to git

whole needle
#

how do i make it in my command have

/signup sendemail [true or false]

rugged lodgeBOT
#

Here's the slash options example.

#

Here's the slash groups example.

ivory beacon
loud kayak
ivory beacon
#

i hope you can read my code 🙂💔

loud kayak
#

if you can't answer my question, i can't help you. where are you using that function

#

im not gonna search for the function in your code.

ivory beacon
#

180 Number Line

loud kayak
#

just send the code here

#

its not that hard

ivory beacon
#

as file ?

loud kayak
#

no, where you are using the function.

shell radish
loud kayak
ivory beacon
loud kayak
#

bad practices

ivory beacon
shell radish
#

the issue is that you are passing around a stale bot object

ivory beacon
#

didn't working in my function 🙂💔

loud kayak
#

the channel id has to be wrong

shell radish
ivory beacon
#

with same id

loud kayak
#

doesn't make sense for it to not work in a function but to work in an eval command

shell radish
shell radish
loud kayak
#

^

ivory beacon
shell radish
loud kayak
#

the object wasn't being updated, since it was being imported

shell radish
upbeat sluice
#

I just noticed however that the image wont load in discord

#

however if you actually go to the image it does load

#

so, im quite confused as to what is going on here?

#

is there something about this image that just doesnt make it work?

atomic fern
#

does Paginator has built-in features for adding select menu like this? or i need to create manually the menus selector? I'm not referring to the page navigator button

shell radish
atomic fern
#

what i mean is, the menu has value inside the embeds

#

ok

atomic fern
#

how do i make pagjnation pages persistent? do i only need to set the timeout to None?

floral ice
#

how can i have dropdown menu, without callback and interaction failed message?

cyan violet
#

Hey.

#

Is there a function to get the messages when the bot gets an dm?

grim estuary
#

Hello! Can you please tell me by what logic the position of the Role and CategoryChannel is determined?

icy badge
cyan violet
#

thx

winter saffron
#

hello!
what's the difference between ctx and interaction?
i realized in my old file i have both
await interaction.response.send_message("Hello!")
and
await ctx.respond("Hello!")
both in slash command, they seem to do the same thing

lofty parcel
#

interaction gets passed to components like buttons, and it is a discord.Interaction object

#

ctx.respond internally does interaction.response.send_message or sends a followup if the interaction was deferred

winter saffron
#

so they are essentially the same thing, just when it's slash commands you can use ctx instead of interaction?

#

oh WAIT nvm i got it

#

thanks!

lapis dock
#

Message components get interactions slash commands get ApplicationContext that includes interaction+more info

lofty hedge
#
    @tasks.loop(minutes=1.0)
    async def pay_business_owners_loop(self):
        await self.bot.wait_until_ready()
        # ensure we arent already paying business owners
        if self.is_paying_business_owners:
            return
        
        now = datetime.now()
        if now.minute == 0:  # check if its :00
            self.is_paying_business_owners = True
            try:
                await self.db_utils.pay_business_owners(self.bot)
            except Exception as e:
                channel = self.bot.get_channel(1129214926259494962)
                await channel.send(f"Failed to pay business owners because {e}")
                print(f"Failed to pay business owners because {e}")
            finally:
                await asyncio.sleep(600)
                self.is_paying_business_owners = False
        else:
            # if its not 00 just return 
            return``` hey I am having an issue where for several hours its only paying out once, then eventually it will start to pay out double, any ideas why?
little cobalt
lofty hedge
little cobalt
#

Still weird that its happening two times

lofty hedge
#

yeah, it makes 0 sense

#

whats more stupid is it works correctly for several hours than randomly break

shell radish
#

my best guess is that it is somehow running the tasks twice in a minute

ivory beacon
#

can i send link button via webhook ?

shell radish
lapis dock
#

That might help a bit

lofty hedge
#

i never knew that

#

ill be giving this a shot, thank you

upbeat sluice
# sage tendon code?
import logging
from os import path

import discord
from discord import bot
from discord.commands import option
from discord.ext import commands


class TestCommand(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_ready(self):
        logging.info(
            f"Cog {path.basename(__file__).removesuffix('.py')} loaded successfully"
        )


    @bot.command(description='test command')
    @option(
        "image",
        description="The image to add to your embed!",
        required=True,
    )
    async def testcommand(self, ctx, image):
        embed = discord.Embed(
            title='Test Embed',
            description='Test Description'
        )
        embed.set_image(url=image)
        await ctx.respond(embed=embed)

def setup(client):
    client.add_cog(TestCommand(client))```
#

it does not work with the image I linked above but it does work with other images

sage tendon
#

then just post the image on discord and copy the media URL

upbeat sluice
#

thats not really an option. the url is stored in a database alongside many other images from the same website

#

this is just a test cog I made to see if images embed properly

#

fooling around with the real cog I run into the same problem - urls from that website do not load properly in the embed, but if I replace the url with ones that load into discord properly, it works just fine

sage tendon
#

then that website is just weird

#

its definitely not above the embed size limit

upbeat sluice
#

yeah, it worked fine before

#

but it suddenly stopped working

sage tendon
#

i mean it is the website

#

however you manage to break that functionality

upbeat sluice
#

figured..

sage tendon
#

is it your website or

upbeat sluice
#

nope

#

so I assume they blocked images from loading on discord? idk how thats possible..

sage tendon
#

i mean, i dont think discord uses any of these UAs

#

yea, weird, their embeds dont seem to work whatsoever

#

well depending on how many images we're talking, it might just be easiest to "host" them on discord

lofty parcel
#

Considering the coming change on CDNs, not really tbh

sage tendon
#

why not?

#

You are loading it from inside discord

#

so its always gonna work

#

Plus, the changes are already in effect lol

lofty parcel
#

They arent afaik

sage tendon
#

to my knowledge they are

lofty parcel
#

@unkempt cipher

sage tendon
#

and as long as you request that media via discord, it will always renew the "lease" so to speak

edgy nest
#

most likely anti bot measures

#

seeing as they are protected by cloudflare

unkempt cipher
#

mew?

rich quartz
#

Hey! I'm trying to subscribe to on_application_command, check if the slash command was run in a discord.TextChannel, and send an ephemeral error message if the slash command was not run in a text channel. My command creates a thread, which makes an error if you try and make a thread from in a thread.

After I send that error, how do I stop the actual command from trying to execute from within on_application_command?

frail ocean
#
webhook = discord.Webhook.partial(result[1], result[0], adapter=discord.RequestsWebhookAdapter())```
How can i use this in pycord?
edgy nest
frail ocean
edgy nest
#

yes

upbeat sluice
#

ive asked the website devs whats going on, then

#

I suppose if they say they wont revert it there's nothing much I can do aside from saving the image locally and uploading that..?

edgy nest
#

you could just

#

copy the discord link

#

im pretty sure it'll refresh it

sweet anchor
#

what does this mean 🥹 🥹

#

it works perfectly fine, it only popped up today

upbeat sluice
edgy nest
#

well just save the url in a database

upbeat sluice
#

yeah but then id have to upload every image on discord 💀

edgy nest
edgy nest
#

maybe

#

if your bot isn't blocked

sweet anchor
#

okay thank u

upbeat sluice
#

have the bot download every image and upload it, then snag the link?

edgy nest
#

yeah

upbeat sluice
#

I mean, yeah that could work

#

thanks for the help though, and the embed resource

#

perhaps its a website bug and theyll fix it but if not I guess ill do that instead

atomic fern
#

how to get current page in paginator? that i can used for custom_view

#

i need to know current page to updating the custom_view

upbeat sluice
#

setting up a task does not work for me

#
import logging
from os import path
from discord.ext import commands, tasks


class TestCommand(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_ready(self):
        logging.info(
            f"Cog {path.basename(__file__).removesuffix('.py')} loaded successfully"
        )


    @tasks.loop(seconds=20.0)
    async def test(self):
        print("Test!")


def setup(client):
    client.add_cog(TestCommand(client))

output: nothing

little cobalt
upbeat sluice
#

thank you, that worked!

granite meteor
#

maybe im delusional but i remember there was a way to make get requests using the discord.Bot object...

little cobalt
#

?

#

Or requests with aiohttp?

granite meteor
ivory beacon
shell radish
sand panther
#

How can I fetch a message from a StageChannel?

rugged lodgeBOT
sand panther
#

ah, I was in an older version, thank you

topaz halo
#

how do I determine if a slash command came from a guild or a DM

frail ocean
#

Is it not possible to use id in something like that:

bot.get_guild(id=…)```
topaz halo
#

I am going to try something

#

I hooked a debugger on a command in DMs, ctx.guild is None

topaz halo
#

some of my slash commands are not appearing in discord

#
@bot.slash_command(name = "save", description = "Save the configuration, can only be used by the owner")
async def save(ctx : discord.ApplicationContext) -> None:
    if int(bot.owner_id) == int(ctx.author.id):
        config.save()
        await ctx.respond("Configuration saved")
        return
    await ctx.respond("You are not my owner")
shell radish
#

try restarting discord

hazy turret
#

Does anyone have an idea how I can determine the arrangement in an embed field?

For example, if I say I have a heading:

Text 1 | Text 2 | Text 3 | Text 4 |

And then I want to determine the sizes of the fields so that it looks like this afterwards:

Text 1    |        Text 2         |    Text 3    |     Text 4        
Hello     | How are you? |     Nice       |  Great 

Instead of

Text 1 | Text 2 | Text 3 | Text 4 |
Hello | How are you? | Nice | Great

little cobalt
#

or you add spaces

hazy turret
hazy turret
wide jasper
frail ocean
#

Ok

wide jasper
#

it also has member informations. but very weird that channel.members returns a empty list

#

i think its a cache problem or smth

frail ocean
#

Could be