#Basic Pycord Help (Quick Questions Only)

1 messages · Page 68 of 1

silver moat
#

simplest one @red geyser

red geyser
#

is there a way to have no timeout for a button?

errant craneBOT
#

Here's the persistent example.

cursive nova
#

Hay, how do i edit/update an embed ?

limber urchin
#

You edit the message with a new embed

#

E.g

embed = discord.Embed(...)
message = await channel.send(embed=embed)
embed.description = 'New description'
await message.edit(embed=embed)
cursive nova
#

thx that helped a lot

strange beacon
cursive nova
#

how do i edit an embed posted through an interaction ? .edit seems not to work on interactions

proud mason
cursive nova
#

ty

rare ice
#

How do I make a discord.Attachment object to a bytes object?

shut hedge
#

I may have missed it but how would I import my token from env or a txt. Prefer a TOKEN.txt so I can add it to a gitignore

limber urchin
#

If it's a text file just read it like normal

#

And why wouldn't you be able to add a env file to gitignore?

shut hedge
#

i want to do the .env route

#

TypeError: expected token to be a str, received NoneType instead

#

in my .env file DISCORD_TOKEN = “token”

#

import os
import random
import discord
from dotenv import load_dotenv # used to import the token from the .env file


#print(sys.path)
#defining the global variables

TOKEN = os.getenv('DISCORD_TOKEN')

intents = discord.Intents.all()
client = discord.Client(command_prefix='!', intents=intents)

@client.event
async def on_ready():
  print('We have logged in as {0.user}'.format(client))


@client.event
async def on_ready():
    print("Bot is now online!")
    
client.run(TOKEN)
#

this is a 100% private bot just because it is my first one using pycord.

shut hedge
limber urchin
silver moat
limber urchin
#

I believe quotation marks are fine, but they're not necessary

silver moat
limber urchin
#

Yeah, they're only really used if you have special characters

#

or spaces

shut hedge
#

oh, that would help on the next step. I had needed them on the last bot I made periods and spaces were messing that one up for some reason.

#

this is better... I think Improper token has been passed.

silver moat
#

what's your bot ID?

shut hedge
#

Thank you. Apparently the small space in front of the token was enough to cause the failure. Same with the quotes.

#

thank you.

silver moat
#

yay

silver moat
teal vault
limber urchin
cursive nova
#

Is there a function to get all messages from a user ?

fervent cradle
#

is title supposed to be in here?

         await interaction.response.send_modal(TestFormModal(info=self.info, type="one"))
#

TypeError: TestFormModal.init() got an unexpected keyword argument 'title'

#

i tried putting it there

#

that error is what i got

#

pls ping if u reply 🙂

#

Code:

import json
import discord
from discord import option
from discord.ext import commands

bot = discord.Bot()

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

    @discord.slash_command(description="Create a new message.")
    @discord.default_permissions(manage_guild = True)
    @option("channel", description="Select the channel where the message will be sent.")
    @option("raw", description="Upload the embed's JSON raw file.")
    async def create_message(self, ctx: discord.ApplicationContext, channel: discord.TextChannel, raw: discord.Attachment):
        global msg_channel, embed
        raw_content = await raw.read()
        raw_data = json.loads(raw_content)
        embed = discord.Embed.from_dict(raw_data)
        msg_channel = channel
        success = discord.Embed(
            title = "Message Created!",
            description = f"Created by: {ctx.author.mention} [`{ctx.author.id}`]",
            color = 0x2B2D31
        )
        await ctx.respond(embed=success, view=Components())

class Components(discord.ui.View):
    """Buttons for previewing or sending the message."""
    def __init__(self):
        super().__init__(timeout=None)
    @discord.ui.button(label="Send", style=discord.ButtonStyle.green)
    async def send(self, button, interaction):
        pass
    @discord.ui.button(label="Preview", style=discord.ButtonStyle.gray)
    async def preview(self, button, interaction):
        await interaction.response.send_message(embed=embed, ephemeral=True)

def setup(bot):
    bot.add_cog(createMessage(bot))```
Error: `discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body`
`In data.embeds.0.description: This field is required` 🤔
fervent cradle
#

bc the embed doesnt exist

#

it does?

#

oh ok sry

proud mason
#

why not just pass the embed to the view init?

#

and why tf do you have a bot instance in the extension file blobpain

proud mason
#

(the args and kwargs thing)

soft girder
#

Hello. I wanted to know if it is possible to make it so that I can send a command let's say "controller" in which there will be two changing buttons start and stop registration. When you press start in another channel, the start registration button will be launched, and when you click on stop registration, this button in channel will be disabled.

#

Can use some kind of ID

proud mason
fervent cradle
#

Well what's causing the problem exactly?

ornate current
#
@modsettings_class.command(name="mod", description="Edit moderator roles", guild_ids=[guild_id])
    @discord.option(name="action", description="What action to perform", autocomplete=actions)
    @discord.option(name="role", description="Role to do actions for. There is no need of this field if using the action \"view\"." ,autocomplete=modactions)```
the option "action" doesnt show.

```py
async def actions(ctx):
    return ["add", "remove", "view"]

async def modactions(ctx : discord.ApplicationContext):
    if ctx.options[0] == "view":

        return ["view"]
    else:
        return discord.SlashCommandOptionType.role```
dapper notch
#

Hey, does anyone know how to create User Commands from within a Cog? I've tried @commands.user_command(name="Test") but it doesn't seem to work

fervent cradle
proud mason
proud mason
proud mason
#

What's the issue

fervent cradle
#
print(f"Got guild: {guild.name}") # Prints correct guild name
times = 0        
category = discord.utils.get(guild.categories, name=f'order{times}'.lower())
print(f"Got cat: {category}")
if category is None:
    print("Category is none, making category") # Goes up to here, then no longer does anything. No errors in console
    category = await guild.create_category(name=f"order{times}".lower(), position=0)
    print(f"Created cat: {category}")
right_channel = discord.utils.get(bot.get_all_channels(), name=f"{name}".lower())
print(f"Got channel: {right_channel}")
if right_channel is None:
    right_channel = await category.create_text_channel(f"{name}".lower())
    print(f"Creted channel: {right_channel}")
    await right_channel.send("Hi")```

Nothing happens after ```print("Category is none, making category")```, no errors in console, nothing printed. Guild is correctly fetched, bot has all correct permissions. What could be the problem?
fervent cradle
#

honestly i don't work with __init__() method much personally

#

sorry

ornate current
#

autocomplete doesnt work sometimes when we edit previous values.. why is that man?

fervent cradle
#
    async def test(self, ctx: discord.ApplicationContext):
        await ctx.respond("Ok")
        await ctx.guild.create_text_channel("yo")```
My bot can't create channels or categories at all. It also seems like it can't get channels or categories by name or id, as it just returns None despite existing. Why could this be?
#

Nevermind, I made a new bot and everything works now. I think discord ratelimited the bot

limber urchin
#

If you got rate limited you need to fix the piece of code that got you rate limited. Making a new bot is only a temporary fix.

proud mason
#

get_guild should be enough

fervent cradle
#

i have a quick question, for this line of code right here, instead of setting every role in the server, how do i only change the permissions for one specific role, eg ('verified' or 'moderator')

            await channel.set_permissions(ctx.guild.default_role, view_channels = True, reason = f'{ctx.author.name} unlocked {channel.name} with --server')
proud mason
#

You can get the role object using guild.get_role(id)

fervent cradle
#

Oh alright, thanks

feral hedge
#

how do I give slash command options a Description?

proud mason
#

.rtfm slash_command

proud mason
#

pass description="..."

feral hedge
#

tyvm

leaden relic
#

any way to retain previous modal inputs?

leaden relic
# young bone yes

how do i retain the previous values aside from saving them on a database?

young bone
#

url=

young bone
#

Im not sure if its possible

silver moat
leaden relic
silver moat
#

This is a Discord limitation

leaden relic
#

thanks

soft girder
#

How fix it'

nocturne canopy
#

bots can't run slash commands from another bot, can they?

somber pelican
soft girder
#

I already try all methods

somber pelican
#

I don't know, there's no code to go off of

#

Just restating the obvious

soft girder
#

uhhh

young flint
#

item is an int

#

debug with prints

#

your sql query literally says SELECT rowid

river dove
#

how do i make my button a fixed size like this

swift smelt
#

how to pass a variable (res) to a discord.ui.View class? sorry for a rather stupid question but i havent used classes a lot before

class logging_command_view(discord.ui.View):
    @discord.ui.button(label="Enable logging", style=discord.ButtonStyle.primary)
    async def button_callback(self, button, interaction):
        await interaction.response.send_message("You clicked the button!")

@bot.slash_command(description="Logging information and settings")
async def logging(ctx):
    hasPermission = checkPermission("command:permissions:logging", ctx.author)
    if not hasPermission:
        await ctx.respond("You have insufficient permissions to do that.", ephemeral=True)
        return
    res = dbexec(1, f"SELECT messages_deleted, messages_edited FROM logging WHERE server_id = {ctx.guild.id}", fetch=1)
    await ctx.respond("This is a button!", view=logging_command_view())```
proud mason
swift smelt
#

yep, i want to adjust the style of buttons depending on that variable

#

and i suck on classes so i have no idea how to do that

proud mason
#

then you should override the init and store it on self
smth like

class MyView(View):
    def __init__(self, res, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.res = res

that way you can access self.res wherever you have access to self in your class

swift smelt
#

oh right, thanks :)

proud mason
#

also i would name classes in PascalCase instead of snake_case

swift smelt
#

right

proud mason
swift smelt
buoyant pier
#

Hello. How i can edit interaction.send_message?

Im trying

msg = interaction.response.send_message(embed=embed, view=view)

msg.edit(embed=new_embed)```
But doesnt work. Any idea ?
proud mason
#

use interaction.edit_original_response to edit the msg

buoyant pier
drifting birch
#

how can I add other people as bot owners (so they pass the check is_owner())

#

I guess I'll make a custom check

proud mason
#

bot = commands.Bot(... , owner_ids = [...])

drifting birch
#

thanks

sweet meteor
#

Possible to create a listener in pycord that listens for specific HTTP requests instead of Discord events?

limber urchin
#

Not with just pycord, no. You have to use something like aiohttp

#

As long as it's async

fervent cradle
#
class TestFormModal(discord.ui.Modal):
    def __init__(self, plan, type):
        super().__init__(timeout=None)  # timeout of the view must be set to None
        self.add_item(discord.ui.InputText(label="mail"))
        self.plan = plan
        self.type = type```
#

where would i put it?

#

i need to pass in plan and type

fervent cradle
#

super().init(*args, **kwargs)
TypeError: Modal.init() got an unexpected keyword argument 'plan'

#
        self.plan = kwargs.pop('plan')
        self.type = kwargs.pop('type')
#

tried this as well no luck

full basin
#

You should also pass *args and **kwargs to the init

fervent cradle
#

this is what i have and it gives that error

full basin
#
def __init__(self, plan, type, *args, **kwargs)
     super().__init__(*args, **kwargs)
     self.plan = plan
     self.type = type```
ocean pumice
#

Hello
I have a bot that’s made to regularly send messages to a set of channels. And it’ll do it all at once sometimes
So is there a limit by discord on how many messages can be sent before it being blocked ? Do I have to wait some time between every message (smth like half a second)?

sage bear
#

How do i make an embed send when a button has been pressed? i've tried this:

await interaction.response.send(embed=n)```
serene spindle
sage bear
#

oh okay

sage bear
limber urchin
#

What error?

#

You never showed any errors

limber urchin
sage bear
proud mason
proud mason
#

Are you using that

sage bear
#

ohh i missed out response

#

uhh idk how to resolve thisdiscord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In data.embeds.0.thumbnail.url: Scheme "none" is not supported. Scheme must be one of ('http', 'https').

limber urchin
#

You're sending an invalid url as the thumbnail, just like the error tells you

sage bear
#

oh yea

#

whoops

ocean pumice
fast badger
#

i need to check if a user has sent a message in a channel
how can i check?

full basin
#

Depends. You can use the on_message event as a listener

#

Or use wait_for

leaden relic
#

how do you attach video on an embed? embed.set_image definitely works on image but embed.video is not like set_image and a video does not work on set_image

proud mason
#

Discord only allows setting images by bots

amber shale
#

i have this function in a separate file

#

how is this thing working?

#

i thought when it went to that function whole control was only/i need to do everything what pycord does to connect to discord

full basin
#

Your interpreter is clearly telling you something is wrong

#

Run the bot and see what's the error

amber shale
#

i was asking how it worked

#

it wants me to follow some strict rules and here i am just testing it so didnt follow..

leaden relic
amber shale
#

its okay

proud mason
amber shale
leaden relic
#

also ctx was not passed

amber shale
#

ctx was not needed

amber shale
proud mason
# amber shale so member has everthing to do validation etc.. and all the work?

well member is an object of the class discord.Member
the library implements all the stuff that the api offers in there

if you are talking about the typehints, those are just hints. Although the slash cmd uses this to figure out the option type. so yeah you basically dont need to directly deal with the api. the library does it for you

leaden relic
#

really? i thought you need ctx to retrieve the member from the guild using the bot to edit that member??????

amber shale
#

okay

amber shale
#

thanks both for helping

leaden relic
#

i didn't help though 😅

viscid sluice
#

How do I replace Auth.COMMAND_PREFIX with a normal command_prefix?

usage = f"{Auth.COMMAND_PREFIX}{cmd_name} "

amber shale
viscid sluice
proud mason
#

use that

#

there is also context.prefix if you want

viscid sluice
#

And what should I do with it?

viscid sluice
proud mason
#

you wanted the prefix right?

proud mason
viscid sluice
#

The command_prefix is defined in another file

#

I want to display it or I make hard code

proud mason
#

||you could just use context.prefix if you have access to context||

otherwise use bot vars to use a variable across files

#

?tag bot_var

obtuse juncoBOT
#

dynoError No tag bot_var found.

viscid sluice
#

Can I do that in one line?

proud mason
#

?tag botvar

obtuse juncoBOT
#

Need to keep track of a variable between functions? No problem!

⚠️ Careful what you name it though, else you might overwrite something ⚠️

Just add it to your commands.Bot or discord.Client instance like so:

bot = commands.Bot(...)
bot.my_variable = 0

async def foo():
    bot.my_variable += 1

# In a cog
@commands.command()
async def counter(self,ctx):
    await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))

This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance

proud mason
viscid sluice
#

I want to display the command_prefix

proud mason
#

and do you have access to context?

viscid sluice
#

Yes

proud mason
#

then just use context.prefix ngl

#

it has the prefix of the bot

viscid sluice
#

Context is not defined

proud mason
viscid sluice
#

Im sorry

proud mason
#

gonna need more code to help you

viscid sluice
#

I send it to you privately

sage bear
#

im wanting to get the content of a message in a
tasks.loop() but how do i do it?

amber shale
#

is there any way to let my flask app get some data from a guild?

#

anything other than ipc

sage bear
#

oh okay ty

amber shale
proud mason
viscid sluice
#

How can I embed a users name, tag and profile picture as title?

distant roost
#

How can i cretae a channel wich is only visible for a specific role? Can anyone help me or say how i can find it in the docs?

silver moat
#

.rtfm embed.set_author for the "title"

winter condorBOT
viscid sluice
silver moat
winter condorBOT
# viscid sluice I tried that but it doesnt work

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.

distant roost
viscid sluice
#

And that doesnt work either

viscid sluice
young bone
viscid sluice
#

I corrected await ctx.send(embed=em) that was the problem

#

And now the tag should be displayed

#

How can I do that?

digital ingot
#

can you put view classes in a separate directory in their own files and import them as needed?

viscid sluice
digital ingot
#

ty

silver moat
winter condorBOT
viscid sluice
#

Thats not what I need

silver moat
viscid sluice
#

The Discord tag like Spliqc#0001

silver moat
#

the 0001 is the discriminator

viscid sluice
#

The documentation is so long

#

Can you tell me what I have to do?

silver moat
#

you to build anything, you need to learn how to read the docs.

viscid sluice
#

🥲

viscid sluice
#

It works now thank you

silver moat
digital ingot
#

Hi, so when I execute a slash command, it seems it's actually running twice..? The normal output comes, but then a "sending command..." message above it leads to this (see attachment below)

#

with the error on top and the expected output below

#

although those buttons are also not working as intended, but that's a separate issue

silver moat
#

Send code

proud mason
digital ingot
#

OHHH WAIt

#

it's because the interaction expects a response

#

i seeee

proud mason
#

yes

digital ingot
proud mason
#

np

swift smelt
#

how do i set button to unactive

#

cuz that stupid vscode doesnt want to tell me possible functions 💀

proud mason
proud mason
swift smelt
#

oh alright

digital ingot
#

Sorry to bug again, but I have 3 buttons within my VIew class, yet only one is showing up when I actually run the command:

class ReactionRolesView(discord.ui.View):

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

    @discord.ui.button(label="Announcements", custom_id="button-announcements", style=discord.ButtonStyle.primary)
    async def button_a(self, button, interaction):
        ...

    @discord.ui.button(label="1v1s", custom_id="button-1v1", style=discord.ButtonStyle.red)
    async def button_b(self, button, interaction):
        ...

    @discord.ui.button(label="2v2s", custom_id="button-2v2", style=discord.ButtonStyle.green)
    async def button_c(self, button, interaction):
        ...
#

i don't think it's actually using this class, since the ButtonStyle isn't even correct, but I can't figure out what else could be happening

strange beacon
digital ingot
#

Never mind! I've figured it out. I had left a duplicate class (I moved stuff around in a rework of my project) and the message was using that instead of the one above ;-;

#

coding is pain fun

strange beacon
viscid sluice
#

How can I get the two embeds to be deleted after await asyncio.sleep(3) has expired?

graceful mortar
#

Error: py Traceback (most recent call last): File "C:\Users\fhaue\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\client.py", line 378, in _run_event await coro(*args, **kwargs) File "C:\Users\fhaue\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\bot.py", line 1164, in on_connect await self.sync_commands() File "C:\Users\fhaue\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\bot.py", line 719, in sync_commands registered_commands = await self.register_commands( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\fhaue\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\bot.py", line 588, in register_commands data = [cmd["command"].to_dict() for cmd in filtered_deleted] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\fhaue\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\bot.py", line 588, in <listcomp> data = [cmd["command"].to_dict() for cmd in filtered_deleted] ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\fhaue\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\commands\core.py", line 1183, in to_dict ] = self.default_member_permissions.value ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'flag_value' object has no attribute 'value' Code: py admin = SlashCommandGroup( "admin", "", default_member_permissions = discord.Permissions.administrator ) Please help 🙏

graceful mortar
proud pagoda
proud pagoda
viscid sluice
graceful mortar
#

if they don't want anything after that

viscid sluice
#

No I need that for something else

#

But thank you both

full basin
graceful mortar
#

thanks, that seems to work

fervent cradle
#

how to get a user by id?

young bone
solemn idol
winter condorBOT
solemn idol
#

@fervent cradle

young bone
digital ingot
#

I think there is

#

.rtfm Guild.fetch_member()

winter condorBOT
#

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

digital ingot
#

.rtfm guild.fetch_member

winter condorBOT
digital ingot
#

Or rather

#

.rtfm guild.get_member

winter condorBOT
digital ingot
#

If you have member caching enabled

solemn idol
#

https://docs.pycord.dev/en/stable/api/models.html#discord.User.id

This is seriously most I can say to help with the question... Is he trying to make a command which lets you ping someone to then get that users id or idk

fervent cradle
digital ingot
#

A bot’s range typically doesn’t extend beyond the guild that it’s in (for security reasons), and also I doubt Discord’s API supports that

#

I could be totally wrong tho, so leave it to a staff member to give you a definitive answer :>

fervent cradle
solemn idol
#

But you need the users exact Tag for that to work though.

young bone
solemn idol
young bone
#

Every user got his own ID

solemn idol
#

😵‍💫

#

Sorry yeah fetch member works.

fervent cradle
#

.rtfm bot.fetch_member

winter condorBOT
#

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

young bone
#

.rtfm fetch_member

solemn idol
#

First one

young bone
#

At the end try discord utils

#

.rtfm get_or_fetch_member

winter condorBOT
#

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

young bone
#

Mhm

digital ingot
# winter condor

isn't this restricted to just the server that the bot is in though?

#

all 3 of these

silver moat
#

.rtfm bot.fetch_user

silver moat
young bone
#

Uh

digital ingot
#

you can fetch a user by their ID, but most operations require you to share a guild with them

#

pretty cool

silver moat
#

hence, the difference between user and member

plain cave
#

How would I get and return a members name? Not to mention but say I wanted to reply to a /hello command with Hello {name here}!"

silver moat
#

Is that person the one who executed the command?

plain cave
#

Yes

silver moat
#

then that would just be

#

.rtfm applicationcontext.author

silver moat
winter condorBOT
silver moat
#

so to link it together: ctx.author.name

plain cave
#

Ahhh thank you. That worked I was trying to pull it from the message.

fast badger
#

is there any way to track people who react to a message?

silver moat
#

.rtfm message.reaction

cosmic wing
#

AttributeError: 'ClientUser' object has no attribute 'create_dm'

async def on_raw_reaction_add(payload):
    guild = client.get_guild(redacted)
    member = guild.get_member(payload.user_id)
    if payload.channel_id == redacted:
        if payload.emoji.name == "🔊":
            roletogive = discord.utils.get(guild.roles, id=redacted)
            await member.add_roles(roletogive)
            try:
                # Use the 'User' object associated with the 'Member' object to create a DM channel
                dm_channel = await member.create_dm()

                # Send the message to the DM channel
                await dm_channel.send('You have signed up for a ping.')
            except discord.errors.Forbidden:
                pass```
#

What is weird is, it works fine for me

limber urchin
cosmic wing
#
Traceback (most recent call last):
  File "/home/nolsen/.local/lib/python3.10/site-packages/discord/client.py", line 378, in _run_event
    await coro(*args, **kwargs)
  File "/home/nolsen/bot/bot/bot.py", line 820, in on_raw_reaction_add
    dm_channel = await member.create_dm()
  File "/home/nolsen/.local/lib/python3.10/site-packages/discord/member.py", line 189, in general
    return await getattr(self._user, x)(*args, **kwargs)
AttributeError: 'ClientUser' object has no attribute 'create_dm'```
silver moat
#

why create a DM channel while you can just send it

limber urchin
#

Is there a reason you're creating a DM channel and not just using member.send ?

cosmic wing
#

Isn't it needed now?

limber urchin
fast badger
#

is there anyway i can get a message just from it's id?

silver moat
#

.rtfm bot.get_message

silver moat
#

if it doesn't exist then you also need a channel

#

.rtfm channel.fetch_message

fast badger
#

tysm

tawny fulcrum
#

this is probably a very dumb question, but is there a way to add buttons to a view with the @discord.ui.button decorator without manually defining them in a custom view class? because i would like to create many buttons using the decorator based off data that i have

#

i know about discord.ui.Button, but the callback with only the interaction argument has proven it very difficult to update the style of the button, given that the button clicked will be just 1/25 in a view

#

any help would be greatly appreciated

proud mason
#

that gives you such a callback async def callback(self, interaction)
where self is the button object itself, and self.view will give the view object

#

if you have largely similar callbacks for many button, you could use this and only need 1 subclass for all those buttons

#

you can even override the init if you want to set some attributes or stuff on self

errant craneBOT
#

Here's the button roles example.

proud mason
#

that is an example of button subclass

tawny fulcrum
#

thank you. i did indeed think of that, im just not sure how to update the style of the button to the view, even when i have access to the button's self

proud mason
tawny fulcrum
#

oh, that does make sense! its real late for me, but ill give that a shot in the morning. i think i see how that works

#

thank you!

proud mason
#

np 🙃

ornate current
#
    @discord.option(name="channel", description="The channel to set as the log channel", type=discord.SlashCommandOptionType.channel)

this also shows the categories and voice channels, but i only want text channels

proud mason
#

thats another parameter

#

.rtfm channeltype

proud mason
#

pass a list of whatever of these you want

ornate current
#

oky

#

i just put in discord.TextChannel in type and it works

proud mason
#

that works too lol

#

library figures stuff our for you

ornate current
#

ye

#

cant even imagine how hard is to make wrappers like these

fast badger
#

how come this is saying i passed 3 arguments when i only passed 2?

msg = await mychannel.fetch_message(mychannel.id, msgid)
soft girder
#

What is the name of the error on cooldown

ornate current
#

but i think we should use channel.history

#

.rtfm TextChannel.history

winter condorBOT
fast badger
fast badger
proud mason
#

fetch_message is an instance method
the instance is already passed to it

proud mason
#

.rtfm channel.fetch

fast badger
#

oh it doesnt?

proud mason
#

mychannel has the id on it

#

fetch message uses that id

fast badger
#

ight works now

#

thanks'

soft girder
#

How to write to a server member that the command is on cooldown

proud mason
#

.rtfm oncooldown

fast badger
#

sorry for flooding this channel with my issues but this is (hopefully) the last one
im trying to iterate through every user who has reacted to a message but it's throwing 'AttributeError: 'list' object has no attribute 'users''
in the docs however, there are 2 examples showing reactions.users() being used as a list (see https://docs.pycord.dev/en/stable/api/models.html#discord.Reaction.users)
how can i fix this?

fervent cradle
#

how is it not int

proud mason
#

accept as string

fast badger
proud mason
#

when your brain types string instead of list 💀

fast badger
#

almost had a heart attack when you said string troll_skull

proud mason
#

i mixed up the 2 questions lol

fast badger
#

i'm using python userslist = await reaction.users().flatten()
but it's still throwing 'list' object has no attribute 'users'

fast badger
#
msg = await ruleschannel.fetch_message(msgid)
reaction = msg.reactions```
proud mason
#

msg.reactions is a list of reaction

#

each reaction means 1 emoji on the msg

proud mason
#

each has an individual list of users

fast badger
#

thanks a ton
it's working now

one last thing, is there any way i can pull the reactor's ID when iterating through them?

fast badger
proud mason
#

to get the id of the 1st user of 1st reaction

#

oh wait users is an async iterator

#

so smth like

async for user in msg.reactions[0].users:
    user_id = user.id
    break
#

or you can flatten it

fast badger
#

now it's throwing TypeError: 'Reaction' object is not iterable

#

oh i need to flatten it im dumb

fallen cove
#
Ignoring exception in view <MedbayWelcomPageButtons timeout=None children=3> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='NFFC' emoji=None row=None>:
Traceback (most recent call last):
  File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\philc\Desktop\Artemis-2.0\bot\src\cogs\medbayV2.py", line 134, in nffc_callback
    nffcticket = await interaction.guild.create_text_channel(
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\guild.py", line 1263, in create_text_channel
    data = await self._create_channel(
                 ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\guild.py", line 1142, in _create_channel
    "id": target.id,
          ^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'id'

any idea why id get this error in some servers but not others?

#
ticket = await interaction.guild.create_text_channel(
            name=f"NFFC-{interaction.user.name}",
            category=NFFC_category,
            overwrites=overwrites,
        )
fallen cove
fast badger
fallen cove
#

so why it doesnt work in other i have no idea

fervent cradle
#

is it possible to access a user's about me content?

proud mason
proud mason
fast badger
fallen cove
proud mason
#

Also what is guild.category?? Does that even exist

#

.rtfm guild.category

winter condorBOT
#

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

proud mason
#

Nope

fallen cove
proud mason
#

It is guild.categories 👀

proud mason
fallen cove
fallen cove
coarse cargo
#

How can i get an emoji from his name like :incoming_envelope:, bot.get_emoji() would work?

proud mason
proud mason
fast badger
#

how can i check if a message has an image attached?

full basin
#

.rtfm Message.attachments

fervent cradle
#

What can I do with custom ids of modals/views?

full basin
#

Persistent views or differentiate between objects for logging or stuff like that

#

You can use it as you want

tawny fulcrum
# proud mason np 🙃

man, my brain was not functioning yesterday. i got it working quick this morning. thank you for your help! i really appreciate it

fervent cradle
#

How to get a message's content from its link?

solemn idol
fervent cradle
#

Whenever someone posts a message link in chat, the bot will get its contents

solemn idol
#

Getting its content as in downloading it to the bot?

fervent cradle
#

just put it in a variable

#

rest thing is out of the context

silver moat
#

get the channel by id and then get the message by id

solemn idol
#

You can also just make a bot event (on_message) which then checks if the message contains a message link.
Then you extract the IDs from the link by splitting at the "/" and dividing it into guild_id, channel_id and message_id then you get the guild channel and message objects and then you can simply put it into a variable. And then idk await that channel to send it into a different channel or wherever you want it to go.

#

I hope that is what you were looking for, at least that's how I understood with what you meant.

sand niche
#

How can I create a timer specific to an event handler? Like: each time it is handled should be an independent timer.

rare ice
#

create a task

#

or a loop with tasks.loop

#

.rtfm discord.ext.tasks.loop

rare ice
errant craneBOT
#

Here's the background task example.

rare ice
#

or that

sand niche
#

I had looked at tasks, but the examples assume you have timers set from cog load or bot load. I need tasks timers to be created on certain events, but I need to handle multiple timers. they may have different settings etc.

#

Should I create a thread for this instead? Wasn't sure if it was too complicated for here.

silver moat
#

you can start tasks from anywhere

sand niche
#

So, say I have an event handler setting these timers, if the event fires twice, then the two independent timers are created with different start times?

silver moat
sand niche
proud mason
#

So wait do you want to run it every time event is fired or only once

sand niche
#

I need a new timer every time the event fires, but it must keep running previous ones. For context, I am doing user verification.

proud mason
#

you could use the one time event listeners available on master branch nope. Just understood what you meant

silver moat
#

just use a normal event loop

proud mason
silver moat
#

yes, event loop

proud mason
#

How did event loop come into this

sand niche
#

yikes. and here I thought my question was simple. I will make a thread, mb.

silver moat
proud mason
silver moat
#

they are asking for a timer

proud mason
#

Event loop is a task switcher and a scheduler

proud mason
silver moat
proud mason
#

you could also use loop.call_later but i find it weird to use

silver moat
#

where did their thread go

proud mason
silver moat
#

oh there's their thread

#

#1092862641480933446

sand niche
#

Sorry, was slow on mentioning you. I havent made a thread on disc before.

proud mason
#

no worries. lets continue in the thread

silver moat
proud mason
woeful skiff
#

How to add a reaction to a message that the bot sent via discord.Interactions?

winter condorBOT
silver moat
#

.rtfm message.add_react

proud mason
#

||interaction.message isnt available if msg is sent for an app cmd||

#

you would need msg = await interaction.original_response() then

woeful skiff
#

so what do i need to react to the message, what code?

#

(i can't write pycord that good so don't yell at me)

#

and i can't really find anything in the docs

proud mason
woeful skiff
#

modal

proud mason
#

ah

woeful skiff
#

i made a modal that sends a message to another channel

proud mason
#

so msg = await interaction.original_response will give you the message object

#

you can then use await msg.add_reaction(...)

woeful skiff
#

yeah, i made this

woeful skiff
proud mason
#

haha np

woeful skiff
#

await msg.add_reaction("✅")?

#

like this?

proud mason
#

.tias

winter condorBOT
woeful skiff
#

kk lol

#
  File "/home/container/bot.py", line 72
    msg.add_reaction(✅)
                     ^
SyntaxError: invalid character '✅' (U+2705)
proud mason
#

forgot "

woeful skiff
#

oh lol i forgot that exclamation marks iOSkull

proud mason
#

they are called quotation marks btw

woeful skiff
#

yeah sry my main lang is german

woeful skiff
silver moat
#

could you show your code?

woeful skiff
#

Yes wait my pc is starting

#
class ticket(discord.ui.Modal):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

        self.add_item(discord.ui.InputText(label="Titel des Tickets", style=discord.InputTextStyle.short))
        self.add_item(discord.ui.InputText(label="Inhalt des Tickets", style=discord.InputTextStyle.long))

    async def callback(self, interaction: discord.Interaction):
        embed = discord.Embed(title="Neues Ticket!")
        embed.add_field(name="Titel des Tickets:", value=self.children[0].value)
        embed.add_field(name="Inhalt des Tickets:", value=self.children[1].value)
        embed.add_field(name="Benutzer ID des Erstellers:", value=interaction.user.id)
        await interaction.response.send_message("Dein Ticket wurde ans Server-Team von *an link so i don't advertise* gesendet!", ephemeral=True)
        my_channel = await interaction.guild.fetch_channel(1092885376688984154)
        await my_channel.send(embeds=[embed])
        msg = interaction.original_response
        await msg.add_reaction("✅")
        await msg.add_reaction("❌")
fervent cradle
#

quick question: if i have a string and i ask the user to guess a letter, how do i get the index of whatever that letter in the string is?

limber urchin
woeful skiff
#

so it's await interaction.original_response?

limber urchin
#

no

#

it's a method, not a coroutine

silver moat
woeful skiff
#

how to i make it a method?

#

i want it to work

limber urchin
#

Do you know how to call a method?

woeful skiff
#

not really, i'm kinda a beginner

limber urchin
#

Read rule 1 in #help-rules

woeful skiff
#

i said kinda

#

not completely

#

i know python

limber urchin
#

Then you should know how to call a method

#

since that is basic Python

woeful skiff
#

oh yes lol

#

i read it wrong twice

limber urchin
#

And if you know basic OOP you'll know the difference between a method and an attribute

woeful skiff
#

you just put () at the end right

#

?

acoustic birch
#

what is this error

woeful skiff
#

Now I got this error FalseFacePalmLaugh

limber urchin
silver moat
solemn idol
acoustic birch
#
Package            Version
------------------ ---------------------
aiohttp            3.8.4
aiosignal          1.3.1
arandr             0.1.10
astroid            2.5.1
asttokens          2.0.4
async-timeout      4.0.2
attrs              22.2.0
automationhat      0.2.0
beautifulsoup4     4.9.3
blinker            1.4
blinkt             0.1.2
buttonshim         0.0.2
Cap1xxx            0.1.3
certifi            2020.6.20
chardet            4.0.0
charset-normalizer 3.1.0
click              7.1.2
colorama           0.4.4
colorzero          1.1
cryptography       3.3.2
cupshelpers        1.0
dbus-python        1.2.16
discord.py         2.2.2
distro             1.5.0
docutils           0.16
drumhat            0.1.0
envirophat         1.0.0
ExplorerHAT        0.4.2
Flask              1.1.2
fourletterphat     0.1.0
frozenlist         1.3.3
gpiozero           1.6.2
html5lib           1.1
idna               2.10
isort              5.6.4
itsdangerous       1.1.0
jedi               0.18.0
Jinja2             2.11.3
lazy-object-proxy  0.0.0
logilab-common     1.8.1
lxml               4.6.3
MarkupSafe         1.1.1
mccabe             0.6.1
microdotphat       0.2.1
mote               0.0.4
motephat           0.0.3
multidict          6.0.4
mypy               0.812
mypy-extensions    0.4.3
numpy              1.19.5
oauthlib           3.1.0
pantilthat         0.0.7
parso              0.8.1
pexpect            4.8.0
pgzero             1.2
phatbeat           0.1.1
pianohat           0.1.0
picamera           1.13
picamera2          0.3.8
pidng              4.0.9
piexif             1.1.3
piglow             1.2.5
pigpio             1.78
Pillow             8.1.2
pip                20.3.4
praw               7.7.0
prawcore           2.3.0
psutil             5.8.0
py-cord            2.4.1.dev42+g279f616b
solemn idol
#

yeah that can interfere

acoustic birch
#

yeah most likely the error

wind jay
#

why can i do self.message.id before bot restart but after restart i get nonetype not have id
why is message none then?

acoustic birch
#

ty

solemn idol
#

also I see youre using a developer version

#

that can cause a conflict too

acoustic birch
solemn idol
#

try using a more stable version 2.4.1 itself

wind jay
proud mason
proud mason
woeful skiff
#

What is my error now

#

I made

limber urchin
#

You still didn't show us the full error

woeful skiff
#
Ignoring exception in modal <__main__.ticket object at 0x7f7936691de0>:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/ui/modal.py", line 341, in dispatch
    await value.callback(interaction)
  File "/home/container/bot.py", line 72, in callback
    await msg.add_reaction("✅")
  File "/home/container/.local/lib/python3.10/site-packages/discord/message.py", line 1584, in add_reaction
    await self._state.http.add_reaction(self.channel.id, self.id, emoji)
  File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 367, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message

silver moat
woeful skiff
#

Oh I’m stupid 💀

#

I acidentally made it ephemeral

#

now i am getting this error

#
Ignoring exception in modal <__main__.ticket object at 0x7fd125b2a2f0>:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/ui/modal.py", line 341, in dispatch
    await value.callback(interaction)
  File "/home/container/bot.py", line 70, in callback
    msg = await interaction.original_response()
  File "/home/container/.local/lib/python3.10/site-packages/discord/interactions.py", line 316, in original_response
    data = await adapter.get_original_interaction_response(
  File "/home/container/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
silver moat
#

you can try putting

msg = await interaction.original_response()

earlier in your code

woeful skiff
#

already did

silver moat
#

earlier as in before sending a response

woeful skiff
#

0ok

#
Ignoring exception in modal <__main__.ticket object at 0x7f2e08622230>:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/ui/modal.py", line 341, in dispatch
    await value.callback(interaction)
  File "/home/container/bot.py", line 68, in callback
    msg = await interaction.original_response()
  File "/home/container/.local/lib/python3.10/site-packages/discord/interactions.py", line 316, in original_response
    data = await adapter.get_original_interaction_response(
  File "/home/container/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
#
    async def callback(self, interaction: discord.Interaction):
        embed = discord.Embed(title="Neues Ticket!")
        embed.add_field(name="Titel des Tickets:", value=self.children[0].value)
        embed.add_field(name="Inhalt des Tickets:", value=self.children[1].value)
        embed.add_field(name="Benutzer ID des Erstellers:", value=interaction.user.id)
        msg = await interaction.original_response()
        my_channel = await interaction.guild.fetch_channel(1092885376688984154)
        await my_channel.send(embeds=[embed])
        await msg.add_reaction("✅")
        await msg.add_reaction("❌")
#

its my code

silver moat
#

wait what message are you trying to react to?

#

the one in my_channel?

woeful skiff
#

yeah

silver moat
#

oh, then just

msg = await my_channel.send(embeds=[embed])
woeful skiff
#

oh lol i'm seeing the error too

sand niche
#

o/ Hello again squid and nom,
How would I go about dispatching a custom event? I've seen discord.py post about using bot.dispatch (assuming discord.ext.commands.Bot.dispatch()), but I am not finding a method like that in the docs.

woeful skiff
#

ty it worked

silver moat
#

The syntax for it is just
bot.dispatch("event", args1, args2...)

#

say your custom event is

@bot.event
async def on_sleep():
  ...

bot.dispatch("sleep")
limber urchin
#

If you find a need to use dispatch there's probably a better way to do whatever you're trying to do

clever hinge
#

is there a way to edit slash message responses?
ctx.edit("test") returns TypeError: Interaction.edit_original_response() takes 1 positional argument but 2 were given

full basin
#

content="test"

clever hinge
#

ah, thanks

frank thistle
#

Can you not add a description to bridged command arguments.

That way the options show a description, rather than being blank when using the slash version?

Ping me on reply pls

sand niche
errant vale
#

im trying to add auto completion to a slash command, can i have some help? i have the guide open but i cant seem to adapt it to my use case. this is my code: ```py
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
import hypixelapi
#load bot token from sys env
load_dotenv("secrets.env")
TOKEN = os.getenv('DISCORD_TOKEN')
api_key = os.getenv("HYPIXEL_API_KEY")
#create bot objects
intents = discord.Intents.all()
bot = commands.Bot()

#initialize param variables
item_name = "CRUDE_GABAGOOL"
crude_gabagool_count=0
username= "uAiden"
profile = "Banana"
hypixelapi.get_sack_data("uAiden","Banana",api_key)

@bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(bot))

@bot.event
async def on_message(message):
print("message-->", message)
if message.author == bot.user:
return

if message.content.startswith('hierarchal'):
    await message.channel.send('Hello!')

if message.content.startswith('imagification'):
    await message.channel.send(file=discord.File('logo.jpg'))

async def get_profile_names(ctx: discord.AutocompleteContext):
#setting up options the user may type
profiles = ctx.options["Profile"]

@bot.slash_command(name="auto",guild_ids=[958497524564500500]) #Add the guild ids in which the slash command will appear. If it should be in all, remove the argument, but note that it will take some time (up to an hour) to register the command if it's for all guilds.
async def setup(
ctx: discord.ApplicationContext,
profiles: discord.Option(str, choices=[
"Apple",
"Banana",
"Blueberry",
"Coconut",
"Cucumber",
"Grapes",
"Kiwi",
"Lemon",
"Lime",
"Mango",
"Orange",
"Papaya",
"Peach",
"Pear",
"Pineapple",
"Pomegranate",
"Raspberry",
"Strawberry",
"Tomato",
"Watermelon",
"Zucchini"]),
profile_name: discord.Option(str, autocomplete=discord.utils.basic_autocomplete(get_profile_names))
):
await ctx.respond(f"You are on profile:{profile_name}")

bot.run(TOKEN)``` and so far, the bot runs, but i cant use any commands let alone see if my autocompletion is working. could it be that im inputting the guild id incorrectly?

fervent cradle
#

does anyone know why bot.close isnt actually shutting down the connection?

#
client_session: <aiohttp.client.ClientSession object at 0x000002287604EC20>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x000002287602FA00>, 98674.234)]']
connector: <aiohttp.connector.TCPConnector object at 0x000002287604E920>
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x000002287604FB80>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x000002287602FA60>, 98684.281)]']
connector: <aiohttp.connector.TCPConnector object at 0x000002287604FC10>```
#

it throws that error when i reconnect

fast badger
#

how come this isn't working? it's not throwing any errors but when i upload an image w/ a message it deosnt detect
(inside on_message, msg being the message)

if msg.attachments:
        print('message has file')```
silver moat
silver moat
#

Autocomplete only needed when you have more than 25 options or they are dynamic in some way

errant vale
#

yeah i realized that, but now i definitely need it for my next option

silver moat
#

it seems like you have a static "set" of options.

fast badger
silver moat
errant vale
#

i need to autocomple from a list of all minecraft names

#

as you type in

#

using namemc api

cerulean yarrow
#

hello! I have a question, how to add a role for the person who clicks on the button? I want to do a verification command

errant vale
#

i thinkk

fast badger
cerulean yarrow
#

tysm ❤️

fast badger
#

oh nvm got it working now

fervent cradle
#

yall please bot.close isnt working

silver moat
#

@fervent cradle @errant vale @fast badger Could you guys please make your own threads? ty.

errant vale
#

ok

#

i waas in the process of doing that

silver moat
#

Ping me in your threads too

cerulean yarrow
sand niche
#
roles = interaction.guild.fetch_roles()
for role in roles:
 if role.id == role_id:
   interaction.user.add_roles(role_to_add)
sand niche
silver moat
sand niche
#

oh, that also works.

silver moat
young bone
#

Fetch can give you really fast a rate limit

cerulean yarrow
#

hmm, thx, sometimes i get confused

sand niche
#

My bad. I am not used to pycord yet. I usually do this in node tbh.

tropic cradle
#

I have a slash command for a select menu that seems to be working fine, but nothing shows up when I trigger it on mobile(ios). Do select menus not work on mobile?

cerulean yarrow
silver moat
#

last time I chcked, a select menu works just fine.

young bone
tropic cradle
#

Seems to be up to date

silver moat
#

oh yeah the last iOS update broke stuff

#

dw it's probably not your fault

tropic cradle
#

Honestly, all I was looking for.

#

ty!

sand niche
#

Do buttons not get custom ids for the view decorators?

sand niche
#

oh nvm it was a typo elsewhere.

#

was wondering about that. I just forgot a paren. oops.

silver moat
#

oof

sand niche
#

I want to edit an ephemeral response to an interaction. Is it possible to do this, or do I need to delete the original response and respond again with the edited message?

sand niche
#

Perfect! Thank you squid. you are my spirit animal lmao

sand niche
#

Is there still a time limit editing ephemeral messages?

young bone
#

Well you can edit them but they are not ephermeral after it

silver moat
#

@sand niche no

errant vale
#

is it possible to use the normal json embed because i cba to make it by myself and wanna use a generator

errant vale
#

i dont see it in the guide

young bone
#

Im not really sure if there is a guide for it

errant vale
#

everywhere i look tells me to do it differently

#

i have this big sample json that i need to add my variables and formatting to

young bone
#

Im not sure if this is helping

#

oof

#

could you maybe delete it pls? x3

#

thx

young bone
errant vale
#

maybe ill just look at the json and convert to pycord convention so i can understand it better

distant roost
#

How do i change the name of a category?

woeful skiff
#

help

#

my code is
msg = await interaction.original_response()
but i get the error:
Ignoring exception in command umfrage_start: Traceback (most recent call last): File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped ret = await coro(arg) File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 982, in _invoke await self.callback(ctx, **kwargs) File "/home/container/main.py", line 613, in umfrage_start msg = await interaction.original_response() AttributeError: 'ApplicationContext' object has no attribute 'original_response' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 1114, in invoke_application_command await ctx.command.invoke(ctx) File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 375, in invoke await injected(ctx) File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped raise ApplicationCommandInvokeError(exc) from exc discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'ApplicationContext' object has no attribute 'original_response'

winter condorBOT
proud mason
proud mason
#

.rtfm guild.get_channel

winter condorBOT
proud mason
#

.rtfm channel.edit

distant roost
#

I was not sure if this will work thank you

fervent cradle
#

Why this doesn't disable the button after pressing it?

class WaveButton(discord.ui.View):
    @discord.ui.button(emoji=":wumpus_wave:", style=discord.ButtonStyle.gray)
    async def waved(self, button, interaction):
        await interaction.response.send_message(f"**{interaction.user.name}** sent you a wave!")
        button.disabled = True
limber urchin
#

You need to edit the message with the updated view

fervent cradle
#

oh

woeful skiff
woeful skiff
#

so can i remain the code how it is but i only change the interaction to.ctx?

#

to ctx*

young bone
woeful skiff
#

yeah that is basic pycord

young bone
woeful skiff
#

idk xD

#

the latest

#
Ignoring exception in command umfrage_start:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
    ret = await coro(arg)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 982, in _invoke
    await self.callback(ctx, **kwargs)
  File "/home/container/main.py", line 627, in umfrage_start
    await msg.add_reaction("🅰️")
AttributeError: 'function' object has no attribute 'add_reaction'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 375, in invoke
    await injected(ctx)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'function' object has no attribute 'add_reaction'```
#

this is my code

#
@bot.slash_command(description="Umfrage starten.")
async def umfrage_start(ctx, frage, a_antwort, b_antwort, c_antwort = None):
    if c_antwort is None:
        id = str(ctx.author.id)
        msg = ctx.interaction.edit_original_response
        await ctx.send(f"<@&1025110392445345863>\nNeue Umfrage!\nErstellt von <@"+id+f">\n"+frage+f"A = "+a_antwort+", B = "+b_antwort)
        await msg.add_reaction("🅰️")
        await msg.add_reaction("🅱️")
    else:
        id = str(ctx.author.id)
        msg = ctx.interaction.edit_original_response
        await ctx.send(f"<@&1025110392445345863>\nNeue Umfrage!\nErstellt von <@"+id+f">\n"+frage+f"A = "+a_antwort+", B = "+b_antwort+", C = "+c_antwort)
        await msg.add_reaction("🅰️")
        await msg.add_reaction("🅱️")
        await msg.add_reaction("🇨")
young bone
full basin
young bone
#

^

woeful skiff
#
Ignoring exception in command umfrage_start:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
    ret = await coro(arg)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 982, in _invoke
    await self.callback(ctx, **kwargs)
  File "/home/container/main.py", line 631, in umfrage_start
    msg = await ctx.interaction.edit_original_response()
  File "/home/container/.local/lib/python3.10/site-packages/discord/interactions.py", line 428, in edit_original_response
    data = await adapter.edit_original_interaction_response(
  File "/home/container/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 375, in invoke
    await injected(ctx)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10015): Unknown Webhook
#

code:

@bot.slash_command(description="Umfrage starten.")
async def umfrage_start(ctx, frage, a_antwort, b_antwort, c_antwort = None):
    if c_antwort is None:
        id = str(ctx.author.id)
        msg = await ctx.interaction.edit_original_response()
        await ctx.send(f"<@&1025110392445345863>\nNeue Umfrage!\nErstellt von <@"+id+f">\n"+frage+f"A = "+a_antwort+", B = "+b_antwort)
        await msg.add_reaction("🅰️")
        await msg.add_reaction("🅱️")
    else:
        id = str(ctx.author.id)
        msg = await ctx.interaction.edit_original_response()
        await ctx.send(f"<@&1025110392445345863>\nNeue Umfrage!\nErstellt von <@"+id+f">\n"+frage+f"A = "+a_antwort+", B = "+b_antwort+", C = "+c_antwort)
        await msg.add_reaction("🅰️")
        await msg.add_reaction("🅱️")
        await msg.add_reaction("🇨")
proud mason
#

What are you even doing...

woeful skiff
#

an poll cmd

#

in german cwinge

young bone
#

also why this if you could just do ctx.author.mention?

woeful skiff
#

idk, don't ask me

young bone
#

Kannst du die Basic´s von Python?

proud mason
#

Remove the edit original response at the top

Change ctx.send to ctx.respond

Change the edit original response at the bottom to ctx.original_response

woeful skiff
fervent cradle
#

How do I get a specific guild's member count by its ID?

proud mason
#

bot.get_guild and guild.member_count

young bone
proud mason
#

Then iterate through guild.members, check and store the count yourself

woeful skiff
#

how do i fix my error?

woeful skiff
#

oh lol

young bone
#

f string without the {} stuff lul

#

I really want python with {} and ; doggokek

woeful skiff
#

Ignoring exception in command umfrage_start: Traceback (most recent call last): File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped ret = await coro(arg) File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 982, in _invoke await self.callback(ctx, **kwargs) File "/home/container/main.py", line 631, in umfrage_start msg = await ctx.original_response() AttributeError: 'ApplicationContext' object has no attribute 'original_response' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 1114, in invoke_application_command await ctx.command.invoke(ctx) File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 375, in invoke await injected(ctx) File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped raise ApplicationCommandInvokeError(exc) from exc discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'ApplicationContext' object has no attribute 'original_response

full basin
#

It's ctx.interaction.

woeful skiff
#

got this error again

#

Ignoring exception in command umfrage_start: Traceback (most recent call last): File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped ret = await coro(arg) File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 982, in _invoke await self.callback(ctx, **kwargs) File "/home/container/main.py", line 625, in umfrage_start msg = await ctx.interaction.original_response() File "/home/container/.local/lib/python3.10/site-packages/discord/interactions.py", line 316, in original_response data = await adapter.get_original_interaction_response( File "/home/container/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 219, in request raise NotFound(response, data) discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 1114, in invoke_application_command await ctx.command.invoke(ctx) File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 375, in invoke await injected(ctx) File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped raise ApplicationCommandInvokeError(exc) from exc discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10015): Unknown Webhook

#

i don't even use a webhook

young bone
woeful skiff
#

lol what

young bone
#

the slash commands ;3

woeful skiff
#

ohhhhhh

#

how do i fix it

young bone
#

could I see the changes again?

full basin
#

You're trying to get the original response when you didn't even respond to the slash command

woeful skiff
#

@bot.slash_command(description="Umfrage starten.") async def umfrage_start(ctx, frage, a_antwort, b_antwort, c_antwort = None): if c_antwort is None: id = str(ctx.author.id) msg = await ctx.interaction.original_response() await ctx.respond(f"<@&1025110392445345863>\nNeue Umfrage!\nErstellt von <@"+id+f">\n"+frage+f"A = "+a_antwort+", B = "+b_antwort) await msg.add_reaction("🅰️") await msg.add_reaction("🅱️") else: id = str(ctx.author.id) msg = await ctx.interaction.original_response() await ctx.respond(f"<@&1025110392445345863>\nNeue Umfrage!\nErstellt von <@"+id+f">\n"+frage+f"A = "+a_antwort+", B = "+b_antwort+", C = "+c_antwort) await msg.add_reaction("🅰️") await msg.add_reaction("🅱️") await msg.add_reaction("🇨")

#

i made it like ctx.respond

young bone
#

dont do the msg stuff before the message

woeful skiff
#

tyy it worked

distant roost
#

How do i get the amount of members in a guild i tried members = guild.members but it returns the whole information of the guild. Can someone help me?

distant roost
distant roost
#

Ok thanks

prisma atlas
#

Heyo, I'm not able to upgrade my pycord version above 0.1.1, any clue on how to upgrade?

#

I've tried pip install pycord==2.0.0

#

pip install --upgrade pycord

full basin
#

It's py-cord

#

Not pycord

prisma atlas
#

Ope just a sec

#

Uh, well I get this error while tryna run it

ModuleNotFoundError: No module named 'pycord'```
limber urchin
#

You don't import pycord. It's still import discord

#

And please use the latest version, not 2.0.0

prisma atlas
limber urchin
prisma atlas
prisma atlas
#

Also, button component should work right? /genq
I keep getting this error 😅

    from discord import Embed, ButtonComponent, ButtonStyle, InteractionType
ImportError: cannot import name 'ButtonComponent' from 'discord' (C:\Users\maddi\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\__init__.py)```
young bone
#

also discord.ui

prisma atlas
#

Ope, I think that was a bit too long 😅

young bone
prisma atlas
#

I already have 2.4.1 installed in pycord

limber urchin
#

You can't have discord.py and pycord installed at the same time

prisma atlas
#

I just uninstalled it 😅
Thought I already removed it

proud mason
uncut skiff
#

Is it possible for the attendees arg to autocomplete for users, but I want to be able to choose multiple users in the same arg (possibly separated by commas)

full basin
#

You'd need to get a string and parse it yourself

uncut skiff
#

if it was a str, would mentioning someone work? I want it to be as easy as possible for the user 🙂

#

Actually I'll just try it anyway

#

thanks guys

full basin
#

They'd have to @ the user themselves

#

Instead of the Discord autocomplete for members

#

I mean, iirc they discord autocomplete will appear once they type @

uncut skiff
#

Yup it does

#

That's nice

green hinge
#

I have run a unit test through my select menu and always get this error:

======================================================================
ERROR: test_init (__main__.TestFirstBottomFishingBait)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\unittest\async_case.py", line 64, in _callTestMethod
    self._callMaybeAsync(method)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\unittest\async_case.py", line 87, in _callMaybeAsync
    return self._asyncioTestLoop.run_until_complete(fut)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
    return future.result()
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\unittest\async_case.py", line 101, in _asyncioLoopRunner
    ret = await awaitable
  File "c:\Users\User\Documents\Coding\Bot\test_bottomfiishing.py", line 13, in test_init
    self.assertEqual(select.placeholder, "Wähle deinen Köder aus")
  File "C:\Users\User\Documents\Coding\Bot\Bot\lib\site-packages\discord\ui\select.py", line 188, in placeholder
    return self._underlying.placeholder
AttributeError: 'FirstBottomFishingBait' object has no attribute '_underlying'```
Does anyone know what the problem is?
#
    async def __new__(cls, *args, **kwargs):
        obj = super().__new__(cls)
        await obj.__init__(*args, **kwargs)
        return obj

    async def __init__(self, bot: discord.Bot, spotdaten):
        self.bot = bot
        self.spotdaten = spotdaten
        baits = sorted(await dab.get_koeder_grundangel(spotdaten.baittype, spotdaten.baitproducer))
        options = [discord.SelectOption(label=bait) for bait in baits]
        super().__init__(
            placeholder="Wähle deinen Köder aus",
            min_values=1,
            max_values=1,
            options=options,
            custom_id="FirstBottomFishingBait",
        )```
young bone
green hinge
young bone
green hinge
young bone
#

no

green hinge
young bone
#

could you not just do ```py
list = []
for item in list:
self.append_option(discord.SelectOption(label=item))

#

after the init stuff

green hinge
young bone
#

it would replace x3

green hinge
# young bone it would replace x3

But I can't call the await function after init:

    baits = sorted(await dab.get_koeder_grundangel(spotdaten.baittype2, spotdaten.baitproducer2))```
young bone
#

I just dont know what all the is

green hinge
# young bone I just dont know what all the is

I can do at most that in the init but there I do not know where the advantage should lie?

    async def __init__(self, bot: discord.Bot, spotdaten):
        self.bot = bot
        self.spotdaten = spotdaten
        super().__init__(
            placeholder="Wähle deinen Köder aus",
            min_values=1,
            max_values=1,
            custom_id="SecondBottomFishingBait",
        )
        baits = sorted(await dab.get_koeder_grundangel(spotdaten.baittype2, spotdaten.baitproducer2))
        for item in baits:
            self.append_option(discord.SelectOption(label=item))```
young bone
#

what is dab.get_koeder_grundangel?

green hinge
young bone
#

is it a list?

green hinge
# young bone is it a list?

There is a list back yes.
But the values can always be different that's why I can't write the values before in a list in the code

viscid sluice
#

What can I do to make the time display look like it does in the third picture and not like in the second picture? The code for this is in the first picture

winter condorBOT
viscid sluice
#

Thats style f right?

#

How and where should I write this?

#

Im not getting it right now

limber urchin
#

the docs explain everything

hybrid flower
#

Can i set a command only display in a specific guild?

fervent cradle
#

Any event function to call when someone boosts the server?

covert kayak
#

Hi, I want the bot to send messages in a particular channel but am not sure exactly how. Normally I would use:

channel = bot.get_channel(<id>)
await channel.send(<content>)

But apparently, this works no longer. Please help me, thank you!

young bone
#

Something like this

covert kayak
young bone
#

if you do "bot.channel* you should see more

covert kayak
#

what do you mean

young bone
#

The autocompletion of the editor

covert kayak
#
File "c:\Users\duchu\Desktop\MMO\database.py", line 72, in addexp
    channel = await bot.fetch_channel(1092403329323257956)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\duchu\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\client.py", line 1824, in fetch_channel
    data = await self.http.get_channel(channel_id)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\duchu\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\http.py", line 604, in request
    if not self._global_over.is_set():
           ^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: '_MissingSentinel' object has no attribute 'is_set'
#

😭

#

there is fetch_channel

young bone
#

What is the py-cord Version?

covert kayak
#

22.3.1

silver moat
#

what

young bone
#

lol

young bone
covert kayak
#

Wait a sec

#

I think i did pip install pycord, is that correct

young bone
obtuse juncoBOT
#

dynoError No tag pycord found.

young bone
#

Its should be py-cord and not pycord

proud mason
tough lion
#

did anyone know how to get status of a user type ?

#

or how to change type of a user to member ?

olive marsh
#

How to automatically restart after Discord's API rate limit?

silver moat
vapid pumice
#

discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0.options.4: The specified option value is already used

Any clue what this means when there is only 1 option in the view (ui Button) and there are no duplicate custom IDs?

vapid pumice
# silver moat Show code?
class ExitCombat(discord.ui.View):
    def __init__(self, profile, profiles, user_id, enemy):
        super().__init__(timeout=None)
        self.profile = profile
        self.profiles = profiles
        self.user_id = user_id
        self.enemy = enemy
        
    @discord.ui.button(label="Continue", custom_id="combat-exitting", style=discord.ButtonStyle.red) 
    async def first_button_callback(self, button, interaction):

        reflection_direction = None
        byte_array, updated_position = update_map_image(self.profiles[interaction.user.id], reflection_direction=reflection_direction)
        file = discord.File(byte_array, filename="map_image.jpeg")
        embed = discord.Embed()
        embed.set_image(url="attachment://map_image.jpeg")

        await interaction.response.edit_message(content = "", embed = embed, attachments=[], file=file, view = UIButtons(self.profile, self.profiles, self.user_id))
silver moat
#

full traceback?

spring hare
#

await interaction.response.edit_message(content = "", embed = embed, attachments=[], file=file, view = UIButtons(self.profile, self.profiles, self.user_id))
wait, what?

vapid pumice
#

Traceback (most recent call last):
0|ethergame | File "/usr/local/lib/python3.10/dist-packages/discord/ui/view.py", line 414, in _scheduled_task
0|ethergame | await item.callback(interaction)
0|ethergame | File "/root/ethergame.py", line 5485, in first_button_callback
0|ethergame | await interaction.response.edit_message(content = "", embed = embed, attachments=[], file=file, view = UIButtons(self.profile, self.profiles, self.user_id))

#

sorry for weird bars...coming from server

silver moat
vapid pumice
spring hare
vapid pumice
#

like..file replacement

#

well otherwise it just adds a file

spring hare
vapid pumice
#

so that's the best way to do it I've found

spring hare
#

fair enough

silver moat
#

It seems like the error is coming from UIButtons.

vapid pumice
#

interestinng....see, this happened to me before and it was actually the code that called the ExitCombat view previously

#

But I can't for the life of me figure out what tf could cause that

silver moat
#

show UIButtons code?

vapid pumice
spring hare
#

Do you use anywhere in your code select menus?

vapid pumice
#

That's the issue

spring hare
#

True

vapid pumice
#

frek frek frek LMFAO

spring hare
silver moat
#

yeah should be that select menu's duplicate options

spring hare
#

only select menus can have options

vapid pumice
#

Yea, I completely forgot that this boss drops an item that's already in my backpack lmfao

spring hare
#

You can't have 2 options with same name

silver moat
#

Unless I'm reading it wrong.

vapid pumice
#

thanks, gang <3

silver moat
#

alr have fun

vapid pumice
spring hare
vapid pumice
#

for some reason file = None doesn't work

spring hare
silver moat
silver moat
#

Attachment would be used to change existing files.

silver moat
spring hare
silver moat
spring hare
silver moat
#

well, view=discord.ui.View() also exists

spring hare
#

but... You still need to use edit_message

silver moat
#

yes

spring hare
#

okay, thank you

silver moat
#

If you don't like the syntax you can always implement your own abstration

spring hare
#

It would be convenient to see this in Pycord, but maybe this is not so important feature

limber urchin
#

You can always make a PR on GitHub if you feel like you can implement it and it's useful

fallow hawk
#

is there a way to make it so it will complete a task at a desired time? eg. send a message to a channel at 8pm est

errant craneBOT
#

Here's the background task example.

fallow hawk
#

thank you

desert path
#

uh so, i've done command groups but they only work for regular commands not bridge commands

#

i've got @play.command(), should i make it @play.bridge_command()?

errant vale
#

was wondering how variables work if multiple people use the bot? id like each user to have their own private variables

#

is that done automatically?

full basin
desert path
errant vale
errant vale
desert path
#

then im pretty sure it wont be overriden

errant vale
#

never used a database before

full basin
#

Then you'll need to learn

#

You must use a database

errant vale
#

where do i start to learn though

full basin
#

Google

desert path
#

yeah im not the best at it either but just create a table, and select each variable from the table

full basin
#

Find a database that you like SQL or non SQL

errant vale
#

sorry shoulda been more specific, what would be a simple database that would fit with pycord? i only need to store 3 variables for the user

desert path
#

bridge cmds are confusing

full basin
#

You can use MySQLite

#

Or mongo

desert path
#

isnt mongo kinda bad

errant vale
desert path
#

ngl idk

#

can anyone tell me about bridge command grps

full basin
full basin
#

Use actual databases

round rivet
full basin
#

It'll be useful long term

errant vale
#

k

#

should i just learn a full featured one so i can apply the skill elsewhere

silver moat
solemn idol
novel jay
#

Honestly probably my entire life
Its the dumbest idea ever

errant vale
#

Whats the convention to add a function call to a slash command

#

I try adding one and it causes the command to not be registered

silver moat
#

what?

errant vale
#

When someone does a slash command, i want it to be run with one of my own functions so i can supply the output with information

silver moat
errant vale
#

I dont see anything on calling functions with a slash command there

#

Anywhere i tried putting my function to be called with the slash command didnt work

silver moat
#

I'm really not sure what you mean.