#Basic Pycord Help (Quick Questions Only)

1 messages · Page 9 of 1

lost lodge
#

hey i made a file for all views (i know from guide xD):

class View(discord.ui.View): # Create a class called View that subclasses discord.ui.View
    @discord.ui.button(label="Click me!", style=discord.ButtonStyle.primary, emoji="😎") # Create a button with the label "😎 Click me!" with color Blurple
    async def button_callback(self, button, interaction):
        await interaction.response.send_message("You clicked the button!") # Send a message when the button is clicked```
#

how can i import it to a other file

#

so that i can use it in a other cog

smoky forge
cyan quail
#

No

smoky forge
lost lodge
#

ah

smoky forge
#

so like a views.py file and then from views import View

cyan quail
#

Can you show your code? Worked fine for me just now (deferred, slept for 5 minutes and used ctx.send)

lost lodge
#

so i made a import and now i try to sind the imported button:

    @commands.command()
    async def hello(self, ctx):
        await ctx.send("hdj", view=View)```
cyan quail
# cyan quail No

(As an addon, I presume it's because discord doesn't want user privacy settings to be arbitrarily exposed on the api to prevent abuse, e.g a malicious bot checking who it can DM before sending mass messages so the ratelimit is lighter)

smoky forge
lost lodge
smoky forge
#

so you forgot the parenthesis is all

harsh dust
#

i've literally tried everything, i've managed to pass down the group object to every cog and it refuses to register commands if the group is being used in more than 1 cog so i'm assuming this is some sort of py-cord limitation

lost lodge
proud pagoda
fervent cradle
# cyan quail Can you show your code? Worked fine for me just now (deferred, slept for 5 minut...
async def replace(self, ctx: discord.ApplicationContext, key: Option(str, 'Key', required=True), password: Option(str, 'Pass', required=True)):

confirm = await ctx.respond('Continue? Yes/No')

response = await self.client.wait_for('message', check=lambda message:message.author == ctx.author and message.channel.id == ctx.channel.id, timeout=60.0)

if response.content.lower() not in ('yes', 'y', 'yup', 'sure', 'ok'):
  await confirm.edit_original_message('Cancelled')

else:
  if key == 'dfsJIOFDJifdo49gjg'
    async with aiohttp.ClientSession() as session:
      async with session.get('https://www.myurl.com', json={'key': 'dfsJIOFDJifdo49gjg', 'password': password}) as a:
        r = (await a.text()).lower()
        #THIS CAN TAKE UP TO 5 MINUTES

  if 'successfully' in r: 
    await confirm.edit_original_message('Success!')
peak chasm
#

Hello, I have a question, how can I make a bot copy the embeds?

#

I tried many things but none works for me, it detects the embeds as empty arrays

#

and when using "message.embeds[0]" it returns me that the index is out of range

sterile canopy
#

how do i close a modal after e.g. a specific input was successful?

full basin
#

Close?

sterile canopy
#

yes so the input is successful but still comes a something went wrong message in the modal

#

this is what i mean, however nothing went wrong and the user has to close the modal by himself now

sterile canopy
#

this is the code of the whole modal```class EnterVerificationCode(discord.ui.Modal):
def init(self, *args, **kwargs) -> None:
super().init(*args, **kwargs)

    self.add_item(discord.ui.InputText(label="Enter your Verification Code the Bot send you", style=discord.InputTextStyle.singleline))

async def callback(self, interaction: discord.Interaction):
    if(checkVerificationCode(self.children[0].value , interaction.user.id)):
        await interaction.user.add_roles(bot.get_guild(guildID).get_role(memberRoleID))
        await interaction.user.send('Your verification was successful')
        await userJoined(interaction.user)
        
        ```
smoky forge
peak chasm
smoky forge
#

is it enabled in the dev portal

sterile canopy
#

so there is no way around this? too bad, anyway thanks

prisma flicker
sterile canopy
peak chasm
smoky forge
#

to copy an embed it should simply be like embeds = message.embeds

#

but if the message has no embeds then it's gonna be None

#

no idea what the message you're trying to get looks like

peak chasm
#

I sent a message with a bot but it still detects that it has no content

#

I am trying to extract the title and description from that embed

slim drum
#

is there a way to make hybrid command groups in cogs?

prisma flicker
#

do you mean bridge commands?

#

you can use channel.last_message

fervent cradle
#

Hi, so Im trying to catch exceptions raised by an external module but for some reason using except module.ExceptionName: doesnt work (as in I have an error that says the module has no attribute ExceptionName and raises a second exception)

lusty token
#

i had to reflash my raspi and I think i'm missing some packages but I'm unsure as to what i need

prisma flicker
prisma flicker
lusty token
#

Oh I forgot about the .env file not being passed through github lol

fervent cradle
prisma flicker
#

maybe

fervent cradle
#

Welp that doesnt work, couldnt find much info so Ill just use a generic Except for the time being

prisma flicker
fervent cradle
#

Which part of it?

#

its... kind of messy atm

frank yew
#

How can I delete a response ephemeral with delay?

near hollow
frank yew
#

Ohh.. Ok

#

Ty

near hollow
#

Np

peak wing
#

  @commands.group(name = 'color')
  async def color(self, ctx):
    if ctx.invoked_subcommand is None:
      embed1 = discord.Embed(title = 'color', description = 'sets personal color to server by hex code', color=0x303135)
      embed1.set_author(icon_url=f"{self.bot.user.avatar.url}", name="cope")
      embed1.add_field(name = f"category", value = f"utility", inline=True)
      embed1.add_field(name = f"permissions", value = f"none", inline=True)
      embed1.add_field(name = f"usage", value = f";color set [hex code]\n;color unset", inline=False)
      embed1.add_field(name = f"commands", value = f"color set - sets personal color for you in the server\ncolor unset - unsets the color", inline=False)
      embed1.add_field(name = f"aliases", value = f"none", inline=False)
      await ctx.send(embed=embed1)

  @color.command(name = 'on')
  @commands.guild_only()
  async def mycoor1(self, ctx):
    self.color = YES
    embed = discord.Embed(description = 'color roles for this server has been **enabled**', color = red)
    await ctx.send(embed=embed)

  @color.command(name = 'off')
  @commands.guild_only()
  async def mcoor1(self, ctx):
    self.color = None
    embed = discord.Embed(description = 'color roles for this server has been **disabled**', color = red)
    await ctx.send(embed=embed)


  @color.command(name = 'set')
  @commands.guild_only()
  async def mycolor1(self, ctx, color):
    if self.color == None:
        return await ctx.send("sorry, this guild has color disabled")
    if self.color == YES:
        name = f"{ctx.author.name}:color"
    if name in [role.name for role in ctx.author.roles]:
        embed2 = discord.Embed(description = f'you already have a color', color=0x303135)
        return await ctx.send(embed=embed2)
    
    try:
            ape = await ctx.guild.create_role(name=f'{ctx.author.name}:color', color=int(f'0x{color}', 16))
            await ctx.author.add_roles(ape)
            embed = discord.Embed(description = f'{ctx.author.mention} assigned your color to **{color}**', color=int(f'0x{color}', 16))
            await ctx.send(embed=embed)
    except ValueError:
            embed3 = discord.Embed(description = f'invalid hex code', color=0x303135)
            return await ctx.send(embed=embed3)

    except:
        embed4 = discord.Embed(description = f'hex code is too long', color=0x303135) 
        return await ctx.send(embed=embed4)


  @color.command(name = 'unset')
  @commands.guild_only()
  async def mycolor(self, ctx):
    if self.color == None:
        return await ctx.send("sorry, this guild has color disabled")
    if self.color == YES:
        role = discord.utils.get(ctx.message.guild.roles, name=f'{ctx.author.name}:color')
        if not role:
            embed2 = discord.Embed(description = f'you dont have a color', color=0x303135)
            return await ctx.send(embed=embed2)
    
    try:
        await role.delete()
        embed = discord.Embed(description = f'{ctx.author.mention} removed your color role', color=0x303135)
        await ctx.send(embed=embed)
    except:
        await ctx.send("s")``` how come when i use `;color off` in one server it applies to all server even though i used `@commands.guild_only()`?
rare ice
peak wing
obtuse juncoBOT
#

Why JSON is unsuitable as a data storage medium.

  1. JSON, quite simply, is not a database. It's not designed to be a data storage format, rather a way of transmitting data over a network. It's also often used as a way of doing configuration files for programs.

  2. There is no redundancy built in to JSON. JSON is just a format, and Python has libraries for it like json and ujson that let you load and dump it, sometimes to files, but that's all it does, write data to a file. There is no sort of DBMS (Database Management System), which means no sort of sophistication in how the data is stored, or built in ways to keep it safe and backed up, there's no built in encryption either - bear in mind in larger applications encryption may be necessary for GDPR/relevant data protection regulations compliance.

  3. JSON, unlike relational databases, has no way to store relational data, which is a very commonly needed way of storing data. Relational data, as the name may suggest, is data that relates to other data. For example if you have a table of users and a table of servers, the server table will probably have an owner field, where you'd reference a user from the users table. [This is only relevant for relational data]

  4. JSON is primarily a KV (key-value) format, for example {"a":"b"} where a is the key and b is the value, but what if you want to search not by that key but by a sub-key? Well, instead of being able to quickly use var[key], which in a Python dictionary has a constant return time (for more info look up hash tables), you now have to iterate through every object in the dictionary and compare to find what you're looking for. Most relational database systems, like MySQL, MariaDB, and PostgreSQL have ways of indexing secondary fields apart from the primary key so that you can easily search by multiple attributes.

For more info and resources about storing persistent data, please check out https://vcokltfre.dev/tips/storage/

peak wing
full basin
#

Json files are not databases.

#

Use a proper database like Mongo or MySQL

rare ice
# peak wing so i cant?

It’s not recommended with json, no. I recommend using mongodb since it’s really easy to use and setup.

#

?tag mongodb

obtuse juncoBOT
#

MongoDB is a NoSQL database that stores data as documents in BSON format. Not recommended in general as most of Discord data you are storing is relational (e.g. economy things) while mongodb is for non-relational data, hence there is no reason to use NoSQL over SQL to store relational data.

Nevertheless, if you still want to use mongodb within your asynchronous code, use motor for the async driver, even it sucks because motor is just a run_in_executor wrapped version of pymongo. Keep in mind that odds of you getting mongo support here are low.

In conclusion, NoSQL databases are fine but not MongoDB. Consider using SQL database for your bot, e.g. PostgreSQL, it's broadly the best relational database you can get.

peak wing
rare ice
#

Yes but you probably won’t get support here for it.

peak wing
rare ice
#

I don’t use json as a database nor I do I recommend it so you may have to just search it up on Google or something.

prisma flicker
#

@peak wing just do a dict of guild id to color

#
colors={}
colors[ctx.guild.id] = "blue"```
#

or whatever

peak wing
#

?

woeful spindle
#
self.load_extension('app/__init__.py')

Would this successfully load my __init__.py file in my app directory?

harsh dust
#

what does this error mean?

discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In _errors: [{'code': 'APPLICATION_COMMAND_TOO_LARGE', 'message': 'Command exceeds maximum size (4000)'}]
#

i have a /leaderboard command with 3 subgroups and each have like 24 commands

harsh dust
woeful spindle
#

ty

harsh dust
#

as long as there is a function "setup(bot)" somewhere in there

hushed ledge
#

One message removed from a suspended account.

harsh dust
#

and if your asyncio.sleep'ing for a long time do it in small increments with a for loop and cache it at the same time

hushed ledge
rare ice
obtuse juncoBOT
#

Why JSON is unsuitable as a data storage medium.

  1. JSON, quite simply, is not a database. It's not designed to be a data storage format, rather a way of transmitting data over a network. It's also often used as a way of doing configuration files for programs.

  2. There is no redundancy built in to JSON. JSON is just a format, and Python has libraries for it like json and ujson that let you load and dump it, sometimes to files, but that's all it does, write data to a file. There is no sort of DBMS (Database Management System), which means no sort of sophistication in how the data is stored, or built in ways to keep it safe and backed up, there's no built in encryption either - bear in mind in larger applications encryption may be necessary for GDPR/relevant data protection regulations compliance.

  3. JSON, unlike relational databases, has no way to store relational data, which is a very commonly needed way of storing data. Relational data, as the name may suggest, is data that relates to other data. For example if you have a table of users and a table of servers, the server table will probably have an owner field, where you'd reference a user from the users table. [This is only relevant for relational data]

  4. JSON is primarily a KV (key-value) format, for example {"a":"b"} where a is the key and b is the value, but what if you want to search not by that key but by a sub-key? Well, instead of being able to quickly use var[key], which in a Python dictionary has a constant return time (for more info look up hash tables), you now have to iterate through every object in the dictionary and compare to find what you're looking for. Most relational database systems, like MySQL, MariaDB, and PostgreSQL have ways of indexing secondary fields apart from the primary key so that you can easily search by multiple attributes.

For more info and resources about storing persistent data, please check out https://vcokltfre.dev/tips/storage/

harsh dust
#

true

round rivet
#

file extensions can be changed, what really matters is the data in the file

prisma flicker
#

mime type

round rivet
#

theoretically a webserver could be bad and intentionally set an incorrect mime type

#

¯_(ツ)_/¯

slim drum
abstract frigate
#

No module named discord.app

outer obsidian
#

ya is pretty long time since it is renamed

abstract frigate
#

Oh

#

Ty

outer obsidian
#

np

abstract frigate
#

Also why is message.content empty?

abstract frigate
#

How do i check if a channel exists

outer obsidian
#

b!rtfm pyc Bot.get_channel

outer obsidian
# dire spade

@abstract frigate. or you could also look through Guild.get_channel

simple canopy
#

@fervent cradle

rocky stump
simple canopy
#

also, be sure to install the latest library version

dreamy nebula
#

is there any example of having a dropdown in a modal

#
class MyModal(Modal):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.add_item(InputText(label="+1 or -1", value="+1"))
        self.add_item(Select(
        placeholder="Choose a TimeZone!",  # the placeholder text that will be displayed if nothing is selected
        min_values=1,  # the minimum number of values that must be selected by the users
        max_values=24,  # the maxmimum number of values that can be selected by the users
        options=[  # the list of options from which users can choose, a required field
            discord.SelectOption(
                label="GMT-12",
                description="Anywhere on Earth",
            ),
            discord.SelectOption(
                label="GMT-11",
                description="Samoa Standard Time",
            )
        ]))
        self.add_item(
            InputText(
                label="Feedback",
                placeholder="Add feedback here",
                style=discord.InputTextStyle.long,
            )
        )```
#

gives me TypeError: expected InputText not <class 'discord.ui.select.Select'>

young bone
dreamy nebula
#

ty

simple canopy
young bone
#

does it work with pycord?

simple canopy
#

no its not, but it should be out soon

#

discord's type of soon™️

dreamy nebula
#

Saw it in the docs and had hope

frank yew
#

Can I make a select menu with de Roles of server?

#

I cant make it...🤯

woeful spindle
#

Fixed.

young bone
frank yew
young bone
#

yes

frank yew
# young bone yes

do you have any suggestion? I would like to create a ticket where people could request a role

solid agate
#

My server has just been granted access to test the Forum Channeltype.

And I have a question, is there a way to automatically tag a forum thread, when creating it through a bot?

ashen pulsar
#

How can i make multiple rows of buttons

full basin
prisma flicker
frank yew
#

How can I print in two columns?

simple plover
#

hi, how can i edit the slash command response?

frank yew
#

But I can't print the mentions or that they are separated like this

frank yew
prisma flicker
verbal gulch
#

Hello, how can i add a role to someone? add_role isn't working

frank yew
prisma flicker
prisma flicker
cerulean drum
simple plover
#

can you edit a normal message to an embed?

verbal gulch
frank yew
simple plover
frank yew
obtuse juncoBOT
#

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.

verbal gulch
#
@bot.slash_command()
async def accept_break(ctx: discord.ApplicationContext, member: discord.Option(discord.Member), note: str):
    embed1 = discord.Embed(
        title='Break request accepted in GA!',
        description=f'Hello, {member}, Im happy to tell you your break request has been accepted by {ctx.author}.\nNote by {ctx.author}: {note}.',
        color= discord.Colour.green()
    )
    user1 = bot.get_user(member)
    await user1.send(embed=embed1)
    ctx.respond(f'Break request by {user1} has been accepted by {ctx.author}.')
    await member.add_roles(1007030026702688306)
    


prisma flicker
#

you need to give it a role, not an id

#

role = discord.utils.get(ctx.guild.roles, id=1007030026702688306)

verbal gulch
#

Okay, thanks you so much

simple plover
#

i am trying to edit this embed 'Loading profile..' to the embed below it, but its just responding the new embed instead of editing the first one, i am using await ctx.edit(embed=embed)

dusty linden
#

It's made for it.

prisma flicker
#
response = await ctx.respond(embed=embed)
# do the work
await response.edit_original_message(embed=embed)```
verbal gulch
#

Why i get this error?

#
Ignoring exception in command hire:
Traceback (most recent call last):
  File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 127, in wrapped    ret = await coro(arg)
  File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 881, in _invoke    await self.callback(ctx, **kwargs)
  File "c:\Users\danie\OneDrive\Documentos\GA staff bot.py", line 46, in hire
    await member.send(embed=embed1)
AttributeError: 'NoneType' object has no attribute 'send'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 992, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 358, in invoke 
    await injected(ctx)
  File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 135, in wrapped    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no 
attribute 'send'

#
@bot.slash_command()
async def hire(ctx: discord.ApplicationContext, user_id: discord.Option(discord.Member), team: str):

    invite = 'deleted'
    embed1 = discord.Embed(
        title=':tada: You have been hired, congratulations! :tada:',
        description=f"Hello, <@{user_id}>, We accepted your application for ``{team}``\nWe're happy to have you with us!\nAs staff of GA, please join our staff server. **:warning: Don't share the invite! :warning:**\n {invite} ",
        color= discord.Colour.green()
    )
    member = bot.get_user(user_id)
    channel = await bot.fetch_channel(1007038870694658160)
    await channel.send(f':heavy_check_mark: @user_id got hired in ``{team}``.')
    await member.send(embed=embed1)
    await ctx.respond(f'The member {member} got hired in the team {team}.')
prisma flicker
#

why are you calling get_user when you already have a discord.Member object?

verbal gulch
#

Because the command asks for a id

prisma flicker
#

just change user_id to member

#

it will take in an id or a member and convert it to a member

verbal gulch
#

it should get a id and convert it to a member

prisma flicker
#

it does

#

just rename user_id to member and delete your member = line

verbal gulch
#

Done, let me test it

peak wing
#

how do i connect my mongo database to my code?

prisma flicker
#

using mongodb python bindings

peak wing
prisma flicker
#

I'm sure there's lots

#

I like sqlalchemy but I'm not sure if they support mongo

verbal gulch
# prisma flicker just rename user_id to member and delete your member = line
Ignoring exception in command hire:
Traceback (most recent call last):
  File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 127, in wrapped    ret = await coro(arg)
  File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 881, in _invoke    await self.callback(ctx, **kwargs)
  File "c:\Users\danie\OneDrive\Documentos\GA staff bot.py", line 46, in hire
    await ctx.respond(f'The member {member} got hired in the team {team}.')
  File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\context.py", line 258, in respond
    return await self.interaction.response.send_message(*args, **kwargs)  # self.response
  File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 709, in send_message
    await self._locked_response(
  File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 956, in _locked_response
    await coro
  File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 211, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 992, in invoke_application_command
#
    await ctx.command.invoke(ctx)
  File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 358, in invoke 
    await injected(ctx)
  File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 135, in wrapped    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
#

I sent the code but it's getting removed idk why

#

also this

#
Ignoring exception in command accept_break:
Traceback (most recent call last):
  File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 127, in wrapped    ret = await coro(arg)
  File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 881, in _invoke    await self.callback(ctx, **kwargs)
  File "c:\Users\danie\OneDrive\Documentos\GA staff bot.py", line 66, in accept_break
    role = discord.utils.get_role(ctx.guild.id, id=1007030026702688306)
AttributeError: module 'discord.utils' has no attribute 'get_role'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 992, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 358, in invoke 
    await injected(ctx)
  File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 135, in wrapped    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: module 'discord.utils' has no attribute 'get_role'
young bone
verbal gulch
young bone
verbal gulch
#

Okie, i appreciate your help :)

prisma flicker
wooden lodge
#

How to ge the ban reason of a user using audit log?

cyan quail
wooden lodge
ashen pulsar
#

Hey can anyone help me with this? im trying to change the view of a message after a button press but it doesnt change the view

await interaction.response.edit_message(content="Upgrades", view=view)```
cyan quail
#

do note that audit logs aren't infinite so you won't find older bans

ashen pulsar
#

its just a variable that has a View

#

with buttons in it

cyan quail
#

can you show the full code

wooden lodge
# cyan quail eh i'd say that's more of a problem with their admins rather than something you ...

I am currently using:

audit_logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.ban).flatten()

But the only information i get by doing that is the following:
[<AuditLogEntry id=1007347748250599514 action=AuditLogAction.ban user=<Member id=424657032252096525 name='Klaro' discriminator='2506' bot=False nick=None guild=<Guild id=837590922610737162 name='Rainbow Six [DE] | BOT Test' shard_id=0 chunked=True member_count=17>>>]
As you can see, i am not getting the rason

cyan quail
#

does audit_logs[0].reason not return anything

harsh dust
#

how do i call another application command within another?

#
help_cmd = ctx.bot.get_application_command('help')
help_cmd

not sure what else to do from here

ashen pulsar
# cyan quail can you show the full code
async def button_callback(interaction):    
  view = View(Button(label="a", style=discord.ButtonStyle.grey),          Button(label="b", style=discord.ButtonStyle.green))
  await interaction.response.edit_message(content="Upgrades", view=view)

        ```
cyan quail
wooden lodge
# cyan quail does audit_logs[0].reason not return anything

<AuditLogEntry id=1007348590898839593 action=AuditLogAction.ban user=<Member id=424657032252096525 name='Klaro' discriminator='2506' bot=False nick=None guild=<Guild id=837590922610737162 name='Rainbow Six [DE] | BOT Test' shard_id=0 chunked=True member_count=17>>>

#

.reason (did not saw that) i am getting an error for that

cyan quail
#

idk discord makes audit logs kind of a pain to work with, if it isn't working then GuraShrug

wooden lodge
#

ok thank you anyways :)

cyan quail
cyan quail
#

well it kinda tells you

simple canopy
dry echo
#

can i get the original message in on_command_error() ?

cyan quail
copper dew
dry echo
cyan quail
#

yep

#

ctx/context has a lot of info

solid agate
#

Anyone here managed to add tags to a forum thread, through code yet?

cyan quail
#

since thread tags are also on the server side, we'd need guild tag objects available on the api too which i don't think exist yet

solid agate
#

Yeah, I figured, couldn't find anything on the discord developer documentation either.

#

But thought it wouldnt hurt to ask.

cyan quail
#

dicts use .pop, remove is for lists

finite flame
#

can I somehow get a list of all timeouts currently going on on a guild?

cyan quail
#

(or if member.timed_out is True, either works)

finite flame
#

aight

#

timeouts aren't an own event right? they are a part of member_update?

cyan quail
#

yes

queen kayak
#

In a slash command, how can I have a parameter for an unspecified number of roles? I've tried this but am getting a "unexpected keyword argument error"

async def foo(self, ctx, *roles)
peak wing
#

i have this color command: @commands.group(name = 'color') async def color(self, ctx): if ctx.invoked_subcommand is None: embed1 = discord.Embed(title = 'color', description = 'sets personal color to server by hex code', color=0x303135) embed1.set_author(icon_url=f"{self.bot.user.avatar.url}", name="cope") embed1.add_field(name = f"category", value = f"utility", inline=True) embed1.add_field(name = f"permissions", value = f"none", inline=True) embed1.add_field(name = f"usage", value = f";color set [hex code]\n;color unset```", inline=False)
embed1.add_field(name = f"commands", value = f"color set - sets personal color for you in the server\ncolor unset - unsets the color", inline=False)
embed1.add_field(name = f"aliases", value = f"none", inline=False)
await ctx.send(embed=embed1)

@color.command(name = 'on')
@commands.guild_only()
async def mycor1(self, ctx):
self.color = YES
embed = discord.Embed(description = 'color roles for this server has been enabled', color = red)
await ctx.send(embed=embed)

@color.command(name = 'off')
@commands.guild_only()
async def moor1(self, ctx):
self.color = None
embed = discord.Embed(description = 'color roles for this server has been disabled', color = red)
await ctx.send(embed=embed)

@color.command(name = 'set')
@commands.guild_only()
async def mycolor1(self, ctx, color):
if self.color == None:
return await ctx.send("sorry, this guild has color disabled")
if self.color == YES:
name = f"{ctx.author.name}:color"
if name in [role.name for role in ctx.author.roles]:
embed2 = discord.Embed(description = f'you already have a color', color=0x303135)
return await ctx.send(embed=embed2)

try:
        ape = await ctx.guild.create_role(name=f'{ctx.author.name}:color', color=int(f'0x{color}', 16))
        await ctx.author.add_roles(ape)
        embed = discord.Embed(description = f'{ctx.author.mention} assigned your color to **{color}**', color=int(f'0x{color}', 16))
        await ctx.send(embed=embed)
except ValueError:
        embed3 = discord.Embed(description = f'invalid hex code', color=0x303135)
        return await ctx.send(embed=embed3)

except:
    embed4 = discord.Embed(description = f'hex code is too long', color=0x303135) 
    return await ctx.send(embed=embed4)

@color.command(name = 'unset')
@commands.guild_only()
async def mycolor(self, ctx):
if self.color == None:
return await ctx.send("sorry, this guild has color disabled")
if self.color == YES:
role = discord.utils.get(ctx.message.guild.roles, name=f'{ctx.author.name}:color')
if not role:
embed2 = discord.Embed(description = f'you dont have a color', color=0x303135)
return await ctx.send(embed=embed2)

try:
    await role.delete()
    embed = discord.Embed(description = f'{ctx.author.mention} removed your color role', color=0x303135)
    await ctx.send(embed=embed)
except:
    await ctx.send("s")```  and the problem is that self.color is a global command so if i do it in one guild for examle `color off` the color is off for all guilds the bot is in, i made a json database here: ```  @commands.Cog.listener()

async def on_guild_join(self, guild):
with open ('color.json', 'r') as f:
colors = json.load(f)

colors[str(guild.id)] = {}
with open ('color.json', 'w') as f:
    json.dump(colors, f, indent=4)``` but the problem is since im in a cog `colors =`  wont work in my commands, how can i make colors = work for all my commands? before anyone say it i tried to make a mongo dtabase but idont know how to apply it
prisma flicker
#

if it's within the same bot just import the cog and call it like a normal function

#

@harsh dust ^

lost lodge
#

why the permanent view doesn't works?

import json
import sys
import os
import asyncio
import datetime
import platform
import discord
import discord.ext
from discord.utils import get
from discord.ext import commands, tasks
from discord.ext.commands import has_permissions, CheckFailure, check
from discord import option
from discord.commands import Option
from discord.ext.commands import MissingPermissions
from datetime import timedelta
from discord.ui import Button, View

from views import rules_view
from views import ticketmsg_view


with open("config.json") as file:
    config = json.load(file)


bot = commands.Bot(command_prefix="!", intents=discord.Intents.all(), case_insensitive=True)
bot.remove_command('help')



@bot.event
async def on_ready():
    view_saver()





@bot.command()
@commands.is_owner()
async def ticketmsg(ctx):
    embed = discord.Embed(description=f"Hier kommt deine Beschreibung rein!", title=f"Ticket System")
    channel = bot.get_channel(TICKET_CHANNEL)
    await channel.send(embed=embed, view=ticketmsg_view())
    await ctx.reply("Gesendet!")




def view_saver():
    bot.add_view(ticketmsg_view())




bot.run(config["token"])
#

error:

Ignoring exception in on_ready
Traceback (most recent call last):
  File "/Development/Python/AKIRU/akiru-private/venv/lib/python3.10/site-packages/discord/client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "/Development/Python/AKIRU/akiru-private/main.py", line 41, in on_ready
    view_saver()
  File "/Development/Python/AKIRU/akiru-private/main.py", line 257, in view_saver
    bot.add_view(ticketmsg_view())
  File "/Development/Python/AKIRU/akiru-private/venv/lib/python3.10/site-packages/discord/client.py", line 1732, in add_view
    raise ValueError("View is not persistent. Items need to have a custom_id set and View must have no timeout")
ValueError: View is not persistent. Items need to have a custom_id set and View must have no timeout```
prisma flicker
lost lodge
#

ah

lost lodge
#

there isn't any timeout

harsh dust
prisma flicker
lost lodge
prisma flicker
#

no

lost lodge
#

how can i make a init

prisma flicker
#

it would go in the ticketmsg_view class

#

same way you make any other method... def __init__(self):

lost lodge
# prisma flicker same way you make any other method... `def __init__(self):`

like that?

class ticketmsg_view(discord.ui.View):
    def __init__(self):
        self.persistent_views_added = False
    @discord.ui.select(
        placeholder = "Select reason!",
        min_values = 1,
        max_values = 1,
        options = [
            discord.SelectOption(
                label="help",
                description="See the rules in english",
                value="1"
            ),
            discord.SelectOption(
                label="bug report",
                description="Siehe die Regeln auf Deutsch an",
                value="2"
            ),
            discord.SelectOption(
                label="team apply",
                description="Ver las normas en español",
                value="3"
            )
        ]
    )
    async def select_callback(self, select, interaction):
        if select.values[0] == "1":
            await interaction.response.edit_message("Aweo!")
        if select.values[0] == "2":
            await interaction.response.edit_message("Awesome! I like  too!")
        if select.values[0] == "3":
            await interaction.response.edit_message("Awe.values[0] too!")```
#

@prisma flicker help pls

cyan quail
#

you'd have to make it a string and parse it yourself

lost lodge
#

anyone help?

queen kayak
#

ty

prisma flicker
errant craneBOT
#

Here's the persistent example.

lost lodge
prisma flicker
#

so follow the example

lost lodge
proven mantle
#

Somehow my Interaction times out when i need to wait for something. Is this my fault or cant discord wait for something?

#

That is my code:

generations = await dalle.generate(self.children[0].value) # Can take a while
index = random.randint(0, len(generations) - 1)
image = generations[index]
url = image["generation"]["image_path"]
r = requests.get(url)
with open("image.png", "wb") as f:
    f.write(r.content)
embed.set_image(url="attachment://image.png")
await interaction.response.send_message(embed=embed, file=discord.File("image.png"))
dry echo
#

any pycord lavalink documentation out there?

tulip bobcat
proven mantle
#

yee. i fixed it now and it works fine

peak wing
#
@commands.is_owner()
async def scrape(ctx):
  for guild in bot.guilds:
    z = random.choice(guild.text_channels)
  invitelink = await z.create_invite(max_uses=100, unique=True)
  await ctx.send(f'{invitelink}')``` why is this only sending 1 server when i use the command?
cyan quail
peak wing
cyan quail
orchid hull
#

How could I sandbox a cog so that it cannot access variables in the rest of my project?
I want to add custom commands to my bot, but I don't want users to be able to import/access internal variables

patent halo
#

Anyone know a reason/fix as to why bot.loadextension() would not be throwing an error if given an invalid extension name. I have two bots I work on and one will throw an error from this function while the other will not.

# bot is created above
if __name__ == "__main__":
    bot.load_extension(name="this should error but doesn't")
proud pagoda
sage galleon
#

Is there a limit on the size of the integer that can be an option for a slash command? I'm trying to enter a guild ID as a slash command int parameter and it's saying it isn't an integer unless I remove two numbers off of the guild ID

rare ice
sage galleon
#

That's what I ended up doing

patent halo
peak wing
#
    @commands.is_owner()
    async def role(self, ctx, user: discord.Member = None, *, role: discord.Role = None):
        if user == None:
            return await ctx.send("i <3 harley")

        if role == None:
            return await ctx.send("i <3 harley")

        elif role in user.roles:
            await user.remove_roles(role)
            return await ctx.send(f'removed {role} from {user.mention}')

        await user.add_roles(role)
        await ctx.send(f'added {role} too {user.mention}')




    @role.command(name = 'rename')
    async def role1(self, ctx, role: discord.Role = None, *, name):
        await role.edit(name=name)
        await ctx.send("renamed the role, ily har <3")

    @role.command(name = 'create', aliases = ['make'])
    async def role2(self, ctx, *, rn):
        await ctx.guild.create_role(rn)
        await ctx.send(f'created role named: {rn}')

    @role.command(name = 'delete', aliases = ['del'])
    async def role3(self, ctx, *, role: discord.Role):
        await role.delete(role)
        await ctx.send(f'deleted role named: {role}')

    @role.command(name = 'color')
    async def role4(self, ctx, role: discord.Role, name):
        try:
            await role.edit(color=int(f'0x{name}',16))
            await ctx.send(f'changed role color')
        except ValueError:
            await ctx.send("please only enter hex codes")
        except:
            await ctx.send("your hex code is too long")``` i have this role sub command and the first command to add and remove roles works but how do i make `user: discord.Member = None` only apply to that and not the rest of my sub commands?
rare ice
peak wing
#

async def line?

rare ice
#

No

#

b!rtfm pyc commands.Group.invoke_without_command

#

@dire spade

#

@peak wing

abstract frigate
#

How to get a file from slash commands and download it?

tiny wagon
#

whats wrong

#

error: unknown interaction

hidden raft
#

Does bot.guilds update before on_guild_join respond?

round rivet
#

probably

fervent cradle
#

Is there any site to know all commands we can make using py-cord example

Ban, timeout,mute,kick

#

These type

frank yew
#

How can i create a button_callback from a specific button? Specifically of the two buttons defined to do different things

smoky forge
#

if you need to pass arguments to the buttons, subclass the buttons

young bone
frank yew
young bone
#

I do it with this without a class

@client.command()
async def test(ctx):

    button = discord.ui.Button(label="text")

    async def button_callback(interaction: discord.Interaction):
        await interaction.response.send_message("text")
    
    button.callback = button_callback
    view = discord.ui.View()
    view.add_item(button)
    await ctx.send(view=view)
slim drum
#

is there a way to make bridge command groups in cogs?

#

example:
/reactions hug or /reactions cry

young bone
#

you mean slashcommand groups?

frank yew
slim drum
smoky forge
#

I think it's not possible with bridge commands yet

slim drum
#

Extension 'cogs.fun' raised an error: AttributeError: 'SlashCommandGroup' object has no attribute 'bridge_command' hm yeah sadly

smoky forge
#

your best bet is to make the command a function and then call it in both commands

#

it's ineffective but its what wotks

frank yew
#

@young bone Do u know why interaction failed?

#
class VoteView(discord.ui.View):

    votantes_1 = []
    votantes_2 = []

    def __init__(self, id_channel, author = None, emoji1="✅", emoji2="❌"):
        super().__init__()
        self.id_channel = id_channel
        self.author = author

        self.button1 = discord.ui.Button(style=discord.ButtonStyle.grey, emoji=emoji1)
        self.button2 = discord.ui.Button(style=discord.ButtonStyle.grey, emoji=emoji2)
        
        self.button1.callback = self.button1_callback
        self.button2.callback = self.button2_callback
        
        self.add_item(self.button1)
        self.add_item(self.button2)
    
    async def button1_callback(self, interaction: discord.Interaction):
        await interaction.message.channel.send(f"{interaction.user.mention} has voted")
    async def button2_callback(self, interaction: discord.Interaction):
        await interaction.message.channel.send(f"{interaction.user.mention} has voted")
smoky forge
#

use interaction.response

frank yew
#

Sure, ty

slim drum
#

how can i make a modal have optional inputs?

restive harbor
#

Are there any alternatives to ffmpeg, for playing music?

restive harbor
# young bone why?

I am using it right now and the bot sometimes randomly just speeds up songs for a few seconds

smoky forge
#

i think that's an internet thing

woeful spindle
#

When using commands.cooldown, when I’m entering the BucketType, do I use server or guild?

peak wing
#
@commands.is_owner()
async def d(ctx):
  count = 0
  for roles in ctx.guild.roles:
    count = count + 1
    rl = roles.created_at.timestamp()
    embed = discord.Embed(description = f'**{count}**. - {roles.mention} created (<t:{int(rl)}:R>)', color=0x303135)
    await ctx.send(embed=embed)``` this sends each role with different embeds but how can i make it send the roles in 1 embed together?
coral kindle
#

Why i cant do my bot on replit

#

bruuh

full basin
woeful spindle
#

I forgot how to make custom command errors? Do I use this:

@ban.error
async def on_command_error(self, ctx, error):
   if instance(error, commands.CommandOnCooldown):
        await ctx.send("my error message")
peak wing
cyan quail
cyan quail
coral kindle
#

Yo

#

I have buttona and it work 3 minutets

#

and tthen when i click it

#

it says that application don respond

#

how can i fix this

#
class View(discord.ui.View):
    @discord.ui.button(label=':white_check_mark:', style=discord.ButtonStyle.green)
    async def button_callback(self, button, interaction):
        role = bot.get_guild(interaction.guild_id).get_role(1007405357880062012)
        await interaction.user.add_roles(role)
        await interaction.response.send_message(content=f'<@{str(interaction.user.id)}>', embed=discord.Embed(title='Gratulacje!', description='Zweryfikowałeś się!', color=0x55FF55).set_footer(text=strftime('%d/%m/%Y')), delete_after=2.5)```
lime lichen
#

my bot is only responding to mentions and dms, no errors. was working perfectly before. anybody know whats up?

full basin
coral kindle
#

how can i change itt

full basin
#

When building the view instance

#

timeout keyword.

coral kindle
#

class View(discord.ui.View):

#

What should i change here

full basin
#

When building it

errant craneBOT
#

Here's the confirm example.

woeful spindle
errant craneBOT
#

examples/views/confirm.py lines 19 to 21

class Confirm(discord.ui.View):
    def __init__(self):
        super().__init__()```
full basin
#

on super().__init__() you'd provide timeout=

woeful spindle
rough fulcrum
#

Who knows why Discord UI (Buttons) message interaction doesn't work after a certain time? This is somewhat similar to the expired time, but the bot process did not stop

cyan quail
errant craneBOT
#

discord/ext/commands/bot.py line 154

async def on_command_error(self, context: Context, exception: errors.CommandError) -> None:```
bronze vector
cyan quail
#

Also note that if you do make a custom handler, it may be good practice to call the original handler at the end in case there's default behaviour that the custom handler doesn't catch

woeful spindle
cyan quail
fervent cradle
#

i have a question about timestamp
normally, in normal command we use this "timestamp= ctx.message.created_at"
but in slash_command wrong
anyway to fix it as well ?

#

i think the problem is ctx.message.created_at

cyan quail
cyan quail
#

you can set timeout=None to extend that indefinitely

fervent cradle
fervent cradle
cyan quail
#

maybe we could add interaction.created_at

fervent cradle
#

hummm

cyan quail
#

but i guess you generally don't need it since interactions are so short lived

rough fulcrum
cyan quail
#

allgood

fervent cradle
cyan quail
#

not that

#

that doesn't exist

#

the discord.utils solution i tagged you with should work fine

cyan quail
#

yes

#

what about it

fervent cradle
cyan quail
#

you have to define embed.timestamp yourself

#

using a datetime.datetime object

#

which you can get from discord.utils.snowflake_time

fervent cradle
#

time = datetime.datetime.utcnow()

#

maybe this gonna work

cyan quail
#

that works too

fervent cradle
cyan quail
#

just datetime.utcnow() then

fervent cradle
#

working very ell

#

well* and smoothy

tiny wagon
cyan quail
woeful spindle
cyan quail
#

then it will be ignored if your command has a custom handler

#

though honestly, instead of being a listener you should just override on_command_error in your main bot file

cyan quail
#

you've made a separate cog.listener to act as your global error handler, however it would probably make more sense to simply override the on_command_error method in commands.Bot (which is easier if you've subclassed, but can work without)

#

though this isn't too important, your current method still works

woeful spindle
#

I’m definitely willing to give this a try.

fervent cradle
#

hey, just a general questions: What is increasing the RAM usage of my bot "permanently"? Am I wrong in assuming that only global variables and objects can increase the RAM "permanently"?

obtuse vale
#

how do i register a slash command with a name with spaces in it?

cyan quail
cyan quail
cyan quail
# fervent cradle hey, just a general questions: What is increasing the RAM usage of my bot "perma...

i guess it could be a variety of reasons; for example, maybe your bot has a really large cache because it's exposed to so many servers and users. It could also be something the user's done; maybe they used a method that doesn't close things properly and leaves unused objects lying around indefinitely... however python's garbage collector makes this somewhat hard to achieve unless you're terribly negligent or doing it on purpose

#

(and yeah it's typically advised to not over-rely on global variables)

woeful spindle
fervent cradle
cyan quail
#

it will disappear yes

woeful spindle
cyan quail
#

ctx.command

woeful spindle
#

ty

cyan quail
#

same for cog i suppose

woeful spindle
#

alright will do

rain knot
#

is there a way to put text on a gif using the pillow module? any attempt i have tried just resulted in an error so i'm wondering if it is even possible.

cyan quail
#

what error

rain knot
#

ill check it out, thanks

fervent cradle
woeful spindle
rain knot
cyan quail
#

i guess

cyan quail
rain knot
#

alright ill see if that fixes it.

woeful spindle
#
/home/container/main.py:41: DeprecationWarning: The object should be created from async function
  self.session = aiohttp.ClientSession()

another issue I have is this error always comes up on my console when I run my bot. I’ve tried to put self.session = aiohttp.ClientSession() in a setup_hook but that doesn’t work, when I try to use self.session because it would say it’s not defined.

peak wing
#
    @discord.ui.button(label="yes", row=0, style=discord.ButtonStyle.green)
    async def button_callback(self, button, interaction):
        await interaction.response.send_message("You clicked the button")
    @discord.ui.button(label="no", row=1, style=discord.ButtonStyle.red)
    async def button_callback(self, button, interaction):
        await interaction.response.send_message("You clicked the button again")

@bot.command()
async def nuke(ctx):
    await ctx.send("This is a button!", view=View())
``` why is it only sending 1 button when i set 2?
cyan quail
#

function names...

peak wing
obsidian cargo
#

is there a maximum of options I can add to a select menu?

obsidian cargo
#

ok thx

rain knot
wild sequoia
cyan quail
rain knot
#

alright ill see if i can do something. thanks for the help.

balmy tangle
#

Hello How do install pycord?

wild sequoia
#

py -3 -m pip install -U pycord

wild sequoia
#

but it not working

bronze vector
#

try restarting vsc

prisma flicker
# wild sequoia

You need to fix your indentation and you have intents=intents

young bone
#

0.1.1 wtf

#

its py-cord not pycord

prisma flicker
#

lmao that too

peak wing
#
    @discord.ui.button(label="yes", style=discord.ButtonStyle.green)
    async def button_callback(self, button, interaction):

          channelthings = [interaction.channel.category, interaction.channel.position]
          await interaction.channel.clone()
          await interaction.channel.delete()
          nukedchannel = channelthings[0].text_channels[-1]
          await nukedchannel.edit(position=channelthings[1])

    @discord.ui.button(label="no", style=discord.ButtonStyle.red)
    async def button(self, button, interaction):
        await interaction.message.delete()

@bot.command()
@commands.has_guild_permissions(administrator=True)
async def nuke(ctx):
  embed = discord.Embed(description=f'{ctx.author.mention} are you sure you want to nuke this channel?', colour=0x303135)
  await ctx.send(embed=embed, view=View2())``` i made this, this command is admin only but if a admin sends ;nuke anyone can press yes or no to nuke the channel how do i prevent this?
peak wing
prisma flicker
smoky forge
prisma flicker
#

Another option is to move the logic from the callback into nuke and use wait_for

#

Or just make it ephemeral

peak wing
smoky forge
#

ephemeral is only for interactions so yes

prisma flicker
#

Oh yeah

balmy tangle
#

what error is this : ```
Could not install packages due to an OSError: [WinError 2] The system cannot find the file specified: 'C:\Python39\Scripts\normalizer.exe' -> 'C:\Python39\Scripts\normalizer.exe.deleteme'

woeful spindle
slim drum
#

whats wrong with my code? whenever i use hug command it doesnt do anything. doesnt even show any errors on the console

    @bridge.bridge_command(name="hug", description="Hugs a user.")
    async def hug(self, ctx, *, member: discord.Member):
        async with aiohttp.ClientSession() as session:
            request = await session.get('https://some-random-api.ml/animu/hug')
            hugjson = await request.json()
            author_name = ctx.message.author.name
        embed = discord.Embed(description=f"{author_name} hugs {member}!",
                              color=random.randint(0, 0xFFFFFF))
        embed.set_image(url=hugjson['link'])
        await ctx.respond(embed=embed)
stark walrus
#
try:
    #put all stuff here 
except Exception as e:
    print(e)```
prisma flicker
slim drum
#

i found the error:
NoneType' object has no attribute 'author'

#

referring to this:

author_name=ctx.message.author.name
prisma flicker
#

if it's an interaction there's not going to be a ctx.message

woeful spindle
slim drum
#

mhm thanks ill try that !!

slim drum
#

doesnt even show an error on console this time

stark walrus
#

I've not worked much with interactions but are you sure ctx takes place here or does it have to be interaction or something

stark walrus
#

so ctx is correct?

prisma flicker
#

yeah

stark walrus
#

also any idea #1007723579003109477

prisma flicker
#

well you can call it whatever you want

#

no I skimmed that, no idea, sorry

#

I just use classes 🤷

stark walrus
#

Oh

fervent cradle
#

im making a link button is there a way to get the server id from the view

#

class

prisma flicker
fervent cradle
prisma flicker
#

can you send what you have

fervent cradle
smoky forge
#

url buttons dont have callbacks

#

and you cant have it as a decorator cuz its not decorating anything

prisma flicker
#

was about to say that

fervent cradle
#

so how do I have it lead to a site

prisma flicker
#
class MyView(discord.ui.View): # please don't name your view class View
  def __init__(self, guild):
    button = discord.ui.Button(label="Click Here To Verify!", style=discord.ButtonStyle.link, url=f"http://127.0.0.1:5000/verify/{guild.id}")
    self.add_item(button)
fervent cradle
#

ill try this

fervent cradle
cyan quail
coral kindle
#

How can i make variables

#

so when someone use slash command

#

/add 1

#

it add's 1 to player's balance

#

or something

#

int/str

fervent cradle
cyan quail
#

what was the code

#

or perhaps did you subclass it? you likely forgot to super().__init__()

fervent cradle
#
class VerificationButton(discord.ui.View):
  def __init__(self, guild):
    Vbutton = discord.ui.Button(label="Click Here To Verify!", style=discord.ButtonStyle.link, url=f"http://127.0.0.1:5000/verify/{guild}")
    self.add_item(Vbutton)
cyan quail
#

yeah, inside __init__ and right above Vbutton you should super().__init__()

fervent cradle
#

Oh okay

#

thanks

coral kindle
#

Can Someone send me example bot with modal menu?

peak wing
#
  async def confess(self, ctx, confession: Option(str, "send your confession", required = True, default = '')):
  
    if '.gg' in ctx.message.content.lower():
      return await ctx.respond('sorry your confession cant have links')

    channel = self.bot.get_channel(1007483312639582208) # /kissed 
  
    embed = discord.Embed(description = f'{confession}', color=0x303135)
    embed.set_author(icon_url=self.bot.user.avatar.url, name='anonymous confession')
    embed.set_footer(text=f'type /confess to confess | .gg/woobaby')
    await channel.send(embed=embed)
  
    await ctx.respond(f"your confession was sent!", ephemeral=True)``` ```    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'content'
^C ``` how do i fix this?
cyan quail
peak wing
#

wanna see the error?

cyan quail
#

go on

peak wing
#
      return await ctx.respond('sorry your confession cant have links')``` ```    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'str' object has no attribute 'content'```
cyan quail
#

no... just confession

peak wing
#

oops

#

thank you

fiery tiger
#

can we flag a nsfw command?

cyan quail
#

not yet

fiery tiger
#

alright

#

when will it be added?

cyan quail
#

planned discord feature, for now you can only manually filter in integrations menu

#

who knows

peak wing
#

can you set a channel nsfw using command?

peak wing
#

how do i make a interaction check for drop down menu’s so only the command author can use the drop down menu?

woeful spindle
#

How do I make {error.retry_after} into milliseconds?

cyan quail
cyan quail
peak wing
cyan quail
#

...your callback has to respond at the very minimum

#

but yeah you can just check inside that

peak wing
peak wing
cyan quail
#

before you do anything else

peak wing
#

what does '=' equal to

cyan quail
#

nono

#

define a variable...

#

but i meant literally just check if interaction.user.id != ...

#

do something

peak wing
#
    select.disabled=True
     if interaction.user.id is not  ```
#

what do i use for is not

cyan quail
#

i literally just

prisma flicker
#

You should use != not is not

wild sequoia
prisma flicker
peak wing
peak wing
prisma flicker
#

If it's ephemeral you don't need to check it

#

Since only the person who sent the command can see it

peak wing
#

oh

#

no

#

thats ugly asf

prisma flicker
#

ugly?

peak wing
#

yes

prisma flicker
#

I don't understand

peak wing
#

it looks terrible

peak wing
peak wing
prisma flicker
#

like it would literally be the same message

prisma flicker
peak wing
#

would self.message.author work?

prisma flicker
#

no, the message was sent by the bot

#

so the author would be the bot

prisma flicker
peak wing
#

so whoever did ;help

prisma flicker
prisma flicker
obtuse juncoBOT
#
prisma flicker
#

I'm not writing your code for you

peak wing
#

do i define ctx

prisma flicker
#

but you just pass it in when you create the view, assign it in init, and then use it in the callback

peak wing
#

im using class MySelect(View)

prisma flicker
#

when did I say anything about a cog

peak wing
#

will class MySelect(View, ctx) work

prisma flicker
#

no, it would go in the init

#

you need to learn how classes and subclassing works

#

you don't need ctx, just the message author

peak wing
#

i don’t have init

#

already said that

prisma flicker
small ether
#

Hello, I would like to know how to code a bot of this kind which displays the profile of the person (created by the person and with the bot which takes this information)

prisma flicker
peak wing
peak wing
full basin
#

You really didn't take your time to read the website.

peak wing
prisma flicker
#

I can't help you if you're not going to help yourself.

full basin
#

And you expect help?...

smoky forge
#

Is it necessary for database connections to close when the bot shuts down/restarts or does the bot automatically handle that?

prisma flicker
#

if the process dies the connection will eventually time out

wild sequoia
#

what is wrong with this code?

full basin
#

?tag idw

obtuse juncoBOT
#

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.

wild sequoia
#
 @commands.Cog.listener()
    async def on_message(message):
        if message.author.bot:
            return
        elif message.content.startswith("<@!id my bot>"):
            b3 = Button(label="Strona Internetowa", style=discord.ButtonStyle.gray, url=f"{strona}", emoji=":345:")
            print("1")
            async def b3_callback():
                b3.callback = b3_callback
                view = View()
                view.add_item(b3)
                print("2")
                embed = discord.Embed(title=f"{name} Twoj serwer Rozrgrywki!", description=f"Serwer {name} jest jednym z najlepszych serwerow Minecraft, serwer jest od wersji: {wersja} administracja serwera stara sie aby gracze mogli cieszyc sie najlepsza jakoscia gry", color=0x1ABC9C)
                embed.timestamp=datetime.datetime.utcnow()
                print("3")
                await message.channel.send(embed=embed, view=View)```
smoky forge
prisma flicker
#

don't depend on the OS or whatever to close your connections

smoky forge
#

right now how my database is handled it's with a context manager in the main file

#

i was looking into implementing it in a different way

#

also cuz this way i can't put the database in the same loop as the bot

wild sequoia
#

;c

prisma flicker
# wild sequoia ;c

you want to tell us a little bit about your code and what you tried and what output you get?

wild sequoia
#

and yea idk why it not wokring

smoky forge
#
  1. the view cant't be initialized in the callback
#
  1. the on_message, if it's in a cog, must have self as first argument
#
  1. the button callback has to be declared outside of the callback
#
  1. not sure if it's discord having a bad codeblock thing but everything past the second print statement shouldn't be in the callback function
#
  1. the callback takes an interaction argument
#
  1. seems like bad indentation after the decorator
#

@wild sequoia please review all of these issues ^

wild sequoia
#

this too

#
@client.event
async def on_message(message):
    if message.author.bot:
        return
    elif message.content.startswith("@azure sail"):
        embed = discord.Embed(title=f"Twoj serwer Rozrgrywki!", description=f"Serwer jest jednym z najlepszych serwerow Minecraft, serwer jest od wersji: administracja serwera stara sie aby gracze mogli cieszyc sie najlepsza jakoscia gry")
        await message.channel.send(embed=embed)
    await client.process_commands(message)```
prisma flicker
spiral coyote
#

how would i check if a user has pressed a button before
Im pretty new to discord bot development, but I'm assuming i store the user that pressed that button and then check that every time someone presses the button.
im just having trouble figuring out how to store it on a per-command run basis

#
import discord
import os

bot = discord.Bot()
userIndex = 0


class View(discord.ui.View):
    @discord.ui.button(label="Join!", style=discord.ButtonStyle.green)
    async def button_callback(self, button, interaction):
        embed = interaction.message.embeds[0]
        field = embed.fields[userIndex]
        embed.set_field_at(index=0, value=field.value + " " + interaction.user.mention, name=field.name)
        await interaction.response.edit_message(embed=embed)


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


@bot.slash_command(name="embed", description="Say hello to the bot")
async def embedtest(ctx):
    embed = discord.Embed(title="Test", description="Embed test pog")
    embed.add_field(name="Users:", value="test")
    await ctx.respond("Ok", embed=embed, view=View())


bot.run(os.getenv('TOKEN'))  # run the bot with the token

just kind of threw this together to show what i have so far

cyan quail
#

it's just <@userid>

wild sequoia
#

that working not

cyan quail
#

did you set intents

prisma flicker
wild sequoia
cyan quail
#

message content

#

?tag intents

#

ohok

wild sequoia
#

yes

cyan quail
#

show your full file

spiral coyote
prisma flicker
spiral coyote
#

ah ok

prisma flicker
#

But it depends on how many times you're going to initialize this view

wild sequoia
#

i fixed

prisma flicker
#

If it's just once it makes sense to store it in the class

wild sequoia
#

thanks neloo<33

prisma flicker
#

But if it's multiple you'll want to store it outside

spiral coyote
#

something like this, where if i have multiple instances open they will each stay independent of each other?

cyan quail
#

yes

spiral coyote
#

and also, im a bit rough on python, but does

EmbedTestView(discord.ui.View)

mean its inheriting the discord View class.
and if so am i able to add other arguments as well that could be used?

cyan quail
#

that's inheritance yes, but additional arguments should be added in the overridden __init__ function

#

when you do override the __init__, make sure you super().__init__() first so it has all the necessary attributes from the parent class

spiral coyote
#

alr

wild sequoia
#
import discord
import os
import time
import random
import inspect
import datetime
import json
from discord.ui import Button, View
import sqlite3
from discord.utils import get
from discord.ext import commands
intents=intents=discord.Intents.all()

client = discord.Client(intents=intents)

class set(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    
with open('ustawienia.json') as f:
    data = json.load(f)
    name = data["NAME"]
    wersja = data["WERSJA"]
    strona = data["STRONA"]

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author.bot:
            return
        elif message.content.startswith("@azure sail"):
            b3 = Button(label="Strona Internetowa", style=discord.ButtonStyle.gray, emoji=":234:")
            async def b3_callback(interaction):
                b3.callback = b3_callback
                view = View()
                view.add_item(b3)
                embed = discord.Embed(title=f"{name} Twoj serwer Rozrgrywki!", description=f"Serwer {name} jest jednym z najlepszych serwerow Minecraft, serwer jest od wersji: {wersja} administracja serwera stara sie aby gracze mogli cieszyc sie najlepsza jakoscia gry")
                embed.timestamp=datetime.datetime.utcnow()
                await message.channel.send(embed=embed, view=View)

def setup(bot):
    bot.add_cog(set(bot))
    print("| Administracyjne | Załadowano ✅ |")```
wild sequoia
#

intents=intents=discord.Intents.all()

cyan quail
#

nono

#

indents

wild sequoia
#

?

cyan quail
#

like... tab spacing

prisma flicker
#

indents look fine

cyan quail
#

wys

wild sequoia
#

so what is wrong?

cyan quail
wild sequoia
#

json?

prisma flicker
#

oh right

cyan quail
#

you're opening a file in the middle of the class while unindented so it's split in half

prisma flicker
#

all of that is outside of the class the way it's written

wild sequoia
#

to how to repair?

prisma flicker
#

indent it so it's in the class

wild sequoia
#

oke

signal stratus
#

Does anyone know how I can make stats pages?
So that just the first 5 best people are displayed on the first page and on the second just so another 5 and always so on? So so zb:

Name1 - 20
Name2 - 13
Name3 - 11
Name4 - 8
Name5 - 5
  1. Page:
Name7 - 1
Name8 - 0
prisma flicker
spiral coyote
#

so im trying to add another button, but its causing a failed interaction error in discord.

@discord.ui.button(label="Leave", style=discord.ButtonStyle.red)
    async def leave_button_callback(self, button, interaction):
        if interaction.user in self.userList:
            self.userList.remove(interaction.user)

would i just make this not async?

spiral coyote
#
import discord
import os

bot = discord.Bot()
userIndex = 0


class EmbedTestView(discord.ui.View):

    def __init__(self):
        super().__init__()
        self.userList = []

    @discord.ui.button(label="Join", style=discord.ButtonStyle.green)
    async def join_button_callback(self, button, interaction):
        if interaction.user not in self.userList:
            self.userList.append(interaction.user)
        embed = interaction.message.embeds[0]
        user_str = " ".join([user.mention for user in self.userList])
        embed.set_field_at(index=userIndex, name="Users:", value=user_str)
        await interaction.response.edit_message(embed=embed)

    @discord.ui.button(label="Leave", style=discord.ButtonStyle.red)
    async def leave_button_callback(self, button, interaction):
        if interaction.user in self.userList:
            self.userList.remove(interaction.user)

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


@bot.slash_command(name="lobby", description="creates a simple lobby system")
async def embedtest(ctx, lobby_name: discord.Option(str), lobby_description: discord.Option(str)):
    embed = discord.Embed(title=lobby_name, description=lobby_description)
    embed.add_field(name="Users: ", value="*empty :(*")
    await ctx.respond("Ok", embed=embed, view=EmbedTestView())


bot.run(os.getenv('TOKEN'))  # run the bot with the token
rare ice
#

and how many buttons it sends

spiral coyote
#

after pressing red button

#

so on an active instance of the command, the green button works, before and after pressing the red button, however the red button will give that error

#

wait i just realized i need to update that text anyways, so that will probably fix it

#

yep that fixed it

#
@discord.ui.button(label="Join", style=discord.ButtonStyle.green)
    async def join_button_callback(self, button, interaction):
        if interaction.user not in self.userList:
            self.userList.append(interaction.user)
            
        embed = interaction.message.embeds[0]
        user_str = " ".join([user.mention for user in self.userList])
        embed.set_field_at(index=userIndex, name="Users:", value=user_str)
        await interaction.response.edit_message(embed=embed)

    @discord.ui.button(label="Leave", style=discord.ButtonStyle.red)
    async def leave_button_callback(self, button, interaction):
        if interaction.user in self.userList:
            self.userList.remove(interaction.user)
        embed = interaction.message.embeds[0]

        user_str = " ".join([user.mention for user in self.userList])
        if user_str == "":
            user_str = "*empty :(*"
        embed.set_field_at(index=userIndex, name="Users:", value=user_str)
        await interaction.response.edit_message(embed=embed)

i could probably format this differently but itll work for now

restive harbor
#

How can i respond to an interaction silently? So that the interaction doesn't fail and i don't have to send a new message into the channel? I got it, just edit nothing

fallen cove
#
Command raised an exception: RuntimeError: PyNaCl library needed in order to use voice```??
full basin
#

You need to install the library

fallen cove
#

it is installed tho

#

PyNaCl 1.5.0

prisma flicker
peak wing
#

does heroku hosting work for pycord?

smoky forge
#

it resets after being online for a bit so don't count on it being online 24/7

peak wing
#

and i can’t use repl its not reliable

smoky forge
#

i hosted a simple image posting twitter bot with it and it reset a lot

#

the bot was supposed to post every hour and it posted like twice an hour and sometimes even 30 minutes

#

so i think it might work if it's a small scale bot

rare ice
#

?tag norepl

obtuse juncoBOT
#

Why NOT to use Repl as a hosting platform

You should not use Repl.it to host your bot.
It may be a nice option as its "free" but you should use something else considering the major flaws.

  • The machines are super underpowered.
    • This means your bot will lag a lot as it gets bigger.
  • You'll need a web server alongside your bot to prevent it from being shut off.
    • This isn't a trivial task, and eats more of the machines power.
  • Repl.it uses an ephemeral file system.
    • This means any file you saved via your bot will be overwritten when you next launch.

IMPORTATNT

  • They use a shared IP for everything running on the service.
    This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.

Please avoid using repl.it to host your bot. It's not worth the trouble.

If you're looking for free options, consider using AWS/Google Cloud Platform/Azure and its respective free tiers or just pay for an actual VPS.

copper dew
# peak wing does heroku hosting work for pycord?

i personally wouldn't trust heroku for hosting bots imo. heroku often will reset and stop the bot after a certain amount of dynos have been used. so i would recommend either self-hosting the bot (which is what i do), or host it on something like AWS or Azure. you can use their free tiers if you would like to

prisma flicker
#

with heroku I ran two projects and just switched when I ran out of time

#

I think they give you like 20 days per month or something

round rivet
#

it's like 28 I thinkpain

peak wing
#

whats the best coding program? (vscode, pycharm, replit, etc)

copper dew
peak wing
fervent cradle
#
@client.slash_command(name="pinghost", description="Ping Host", guild_ids=[996254028893794325])
async def pinghost(ctx, host):
    url = "https://steakovercooked.com/api/ping/?host=" + host
    response = requests.get(url, verify=True)
    await ctx.respond(response.json())
#

hmmm

#

what wrong...

smoky forge
#

as well as defer the interaction at the beginning

obtuse juncoBOT
smoky forge
#

personally i use vscode and i added extensions to make it close to an ide

rigid sable
#
async def name(ctx, member: Option(discord.Member, description="Get the name of this user!",required=False)):
  await ctx.channel.trigger_typing()
  if member is None:
    member = ctx.author

  await ctx.send(member)

This is my code. The command shows up but the option parameter doesn't, anyone know why?

tiny wagon
#

installing py-cord[speed] automatically speedups the code or i need to edit something?

fallen cove
#

trying out the voice example from pycord githum page and it havving this isssue

raise BadArgument(f'Converting to "{name}" failed for parameter "{param.name}".') from exc
discord.ext.commands.errors.BadArgument: Converting to "Sinks" failed for parameter "sink".```
#

??

slim drum
#

line await def addwarn(ctx, reason, member) gives me a syntax error code all of a sudden. i imported this command into a cog since i accidentally wrote it in my main.py file, but after formatting it gives me a syntax error even though i dont see anything wrong with it

#

never mind?? the code works perfectly

#

just added self next to addwarn

prisma flicker
slim drum
#

ohh ty

slim drum
#

also kind of unrelated but an entire command doesnt show up as well

rough shuttle
#

I want to check if a user is online and perform a background tasks

errant craneBOT
#
:class:`str`: The member's overall status as a string value.

.. versionadded:: 1.5```
prisma flicker
young bone
#

@glacial pagoda

fallen cove
#

how do you set up ffmpeg for voice recording?

rocky stump
#

Is it possible to implement pagination via buttons with a discord.ui.Select dropdown? Since they have a limit of 25, I was wondering how I could implement buttons to scroll to the next "page" of dropdowns? Could anyone give me some example code of this?

cinder pilot
#

How do I make slash commands like this

#

When I give a space in the name it says I can't

rocky stump
cinder pilot
slim drum
#

im making a warn command inside a cog, and my warn command doesnt work because of this error addwarn() takes 4 positional arguments but 5 were given. i understand why the error happened but i still dont know how to fix it.

class Mod(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
      
    async def addwarn(self, ctx: commands.Context, reason, member: discord.Member): 
      async with bot.db.cursor() as cursor:    
       await cursor.execute("INSERT INTO warns (user, reason, time, guild) VALUES (?, ?, ? , ?)", (member.id, reason, int(datetime.datetime.now().timestamp()), ctx.guild.id))
      await bot.db.commit()

    @bridge.bridge_command(name="warn", description="Warns a user")
    @commands.has_permissions(manage_messages=True)
    async def warn(self, ctx: commands.Context, member: discord.Member, *, reason: str= "No reason provided"):
      try:
        await self.addwarn(self, ctx, reason, member)
        embed=discord.Embed(title="Warn successful", description=f"{member.mention} has been warned for: *{reason}*.")
        await ctx.respond(embed=embed)
      except Exception as e:
        print(e)
#

the command works outside of cogs

cyan quail
slim drum
#

ohh didnt know that tysm

coral kindle
#

how can i create channel by typing slash command

rocky stump
#

Is there a way to change the options of a discord.ui.Select ? e.g after a button press or something. I tried using super() again for a second time, but seemed to do nothing

rocky stump
# rocky stump Is there a way to change the `options` of a `discord.ui.Select` ? e.g after a bu...

code:

class Dropdown(discord.ui.Select):
    def __init__(self, bot_: discord.Bot):

        self.bot = bot_

        options = [
            discord.SelectOption(label=lang, description="Select this language") for lang in OCR_LANGS.keys()
        ]
        super().__init__(
            placeholder="Select A Language",
            min_values=1,
            max_values=1,
            options=options,
        )

    async def callback(self, interaction: discord.Interaction):
        super().__init__(
            placeholder="Select A Language",
            min_values=1,
            max_values=1,
            options=[discord.SelectOption(label="test123", description="Select this language")],
        )
        await interaction.response.send_message(f"test")```
#

^ I get the send_message, but the select options do not change after callback()

rocky stump
# cyan quail you didn't specify `view`
class DropdownView(discord.ui.View):
    def __init__(self, bot_: discord.Bot):
        self.bot = bot_
        super().__init__()

        # Adds the dropdown to our View object
        self.add_item(Dropdown(self.bot))```
cyan quail
#

yeah but it still isn't in that code is it

rocky stump
#

what do you mean

#

my select is displaying

cyan quail
#

check your last line

rocky stump
#

I don't know

cyan quail
#

you need to specify view= to send a new view

#

all you're doing is sending text, nothing else

rocky stump
#

I don't want to send a new view I want to edit the existing one

#

is that possible?

cyan quail
#

then use response.edit_message

#

you still need to specify view= either way

rocky stump
#

hmm okay, but what do I pass as the parameter

cyan quail
#

your view...

rocky stump
#

in the Dropdown class I do not have access in the scope

#

I'm confused

cyan quail
#

you can still access DropdownView

#

but instead of just trying to super your existing select, you're better off creating a new select menu

rocky stump
#

I see now

#

thx

cyan quail
#

allgood

signal stratus
#

Buttons doesn't work after bot restarts what can i do?

mental maple
#

can i do this for buttons?```py
@discord.ui.button(label="(", style=discord.ButtonStyle.green, x=0, y=0)
async def button_2(self, button: discord.ui.Button, interaction: discord.Interaction):
self.str += "("
self.label += "("

@discord.ui.button(label=")", style=discord.ButtonStyle.green, x=1, y=0)
async def button_3(self, button: discord.ui.Button, interaction: discord.Interaction):
    self.str += ")"
    self.label += ")"```
cyan quail
simple canopy
#

uh, probbaly... positioning?

mental maple
simple canopy
#

i don't think you can do this like that

mental maple
#

can i?

simple canopy
#

would be cool tho

#

im not sure 🤔

mental maple
#

should be on suggestion?

mental maple
cyan quail
#

you're meant to use actionrows

mental maple
cyan quail
#

being able to specify x and y positions for it would be far too vague

mental maple
#

im bad ad english weit

cyan quail
mental maple
#

hmm i see

#

uhhh so i need to construct x y by self

signal stratus
#

How can I add reactions to an interaction message?

vital blade
rare ice
cyan quail
# signal stratus

interaction.response.send_message returns an interaction object; in this scenario, you refer to message.message to get the actual message

rare ice
#

@dire spade

vital blade
#

u defined message twice

#

try changing the variable name for 2nd message thing

cyan quail
#

no... that entire 2nd line is unnecessary

vital blade
#

💀

cyan quail
near hollow
#

Trying to use SlashCommandGroup but commands aren't registering

queen prism
#

Hello, I'm trying to wait for the user input when running a command, and timing out the command if the user doesn't respond/doesn't give the correct response in 30 seconds. I'm using a module called arrow and a while loop to check if 30 seconds has passed since the user executed the command, the only problem is, it isn't timing out if the user doesn't respond in 30 seconds until someone types a message, here's my current code:

end_time = arrow.utcnow().shift(seconds = 30).timestamp()
while arrow.utcnow().timestamp() - end_time < 0:
  msg = await self.client.wait_for("message")
  if msg.content == "yes":
    #my code here
else:
  await ctx.send("Timeout!")

Does anyone know how I can make it so it times out after 30 seconds if the user didn't respond or if the user didn't respond with "yes" within 30 seconds?

#

I don't want to use something like msg = await self.client.wait_for("message", timeout = 30) because if for example the user responds with something else than "yes" after 20 seconds, it won't timeout after 10 seconds, it'll timeout after 30 seconds.

queen prism
#

I don't think that'd work neither.

cerulean drum
queen prism
#

If I use the check param ( I already use it but not to check for the timeout ), It'll just not respond to you at all after 30 seconds.

#

It won't send "Timeout!" after it times out.

mental maple
#

ummm, how to get ctx from discord.on_message_edit(before, after)

#

does it give ctx tho

queen prism
cerulean drum
#
@client.event
async def on_message(message):
    if message.content.startswith('$thumb'):
        channel = message.channel
        await channel.send('Send me that 👍 reaction, mate')

        def check(reaction, user):
            return user == message.author and str(reaction.emoji) == '👍'

        try:
            reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
        except asyncio.TimeoutError:
            await channel.send('👎')
        else:
            await channel.send('👍')
queen prism
#

You didn't get what I'm trying to do.

cerulean drum
#

did i?

cerulean drum
mental maple
queen prism
#

If the user sends a message after 20 seconds, it'll wait another 30 seconds to timeout instead of just 10 seconds.

cerulean drum
queen prism
#

Yeah, I tried that.

cerulean drum
# queen prism Yeah, I tried that.

wait lemme process all my pepega brain
so... you wanted to wait user message right

if user said 'yes':
    ...
if timeout or not 'yes'
    ...

you want the bot to keep waiting until timeout or force to timoeut even the message was not true/'yes'

queen prism
#

If user said "yes", the bot will do something
If the user didn't say "yes" or the user kept saying something else, the bot should timeout after 30 seconds.

#

Basically the bot should timeout after 30 seconds from running the command not 30 seconds after the last user message.

#

If that makes sense.

quick temple
#

Is it possible to click a button then have a slash command autofilled?

#

and shown

verbal gulch
#

How i can create a textchannel in a selected category? It will be via buttons.

cerulean drum
#

with check and try .. excpet

queen prism
cerulean drum
#

and do the content logic under else exception

queen prism
#

Still not what I'm looking for but thanks anyway.

coral kindle
#

How can i detect if someone joined specific voice channel

#

or left

proud pagoda
# queen prism I don't think that'd work neither.

It should:

try:
  msg = await self.bot.wait_for('message', timeout=30, check=lambda m: m.author == ctx.author and m.content.lower() == "yes")
except asyncio.TimeoutError:
  return await ctx.send("You've timed out!")
# Now do whatever else you needed to do
...
#

That'll send a message and return if it times out

#

And it will also do nothing if the author sends something other than "yes"

coral kindle
#

aLEGEND

#

i how can i dettect if someone joined or leftt specific voice channel

full basin
#

on_voice_state_update

coral kindle
#

just/

#

??

full basin
#

Run the checks on the event?..

coral kindle
#

example

coral kindle
#

bo

#

bot example

full basin
#

What

coral kindle
#

just

#

send me example code of it xd

#

using this

full basin
#

Make an attempt lmao.

#

I won't code for you nor have time

frank yew
#

Hi guys, how can I do something when someone reacts to any message? With something like this


@bot.listen()
async def on_message(message):
        #check reaction

``` ?

I don't know if this is the most effective way because I would only like to record the reactions of one channel.
full basin
#

on_message doesn't detect reaction add

#

on_reaction_add or on_raw_reaction_add

simple canopy
#

@bot.listen() its actually a thing, i never saw it

full basin
#

Lmao didn't notice

#

Oh is it

peak wing
#
  def __init__(self, bot):
    self.bot = bot

  @discord.ui.button(label="yes", style=discord.ButtonStyle.green)
  async def button_callback(self, button, interaction):
      if interaction.user.id != self.user.author.id:
        return await interaction.response.send_message('no')

      channelthings = [interaction.channel.category, interaction.channel.position]
      await interaction.channel.clone()
      await interaction.channel.delete()
      nukedchannel = channelthings[0].text_channels[-1]
      await nukedchannel.edit(position=channelthings[1])

  @discord.ui.button(label="no", style=discord.ButtonStyle.red)
  async def button(self, button, interaction):
      if interaction.user.id != self.user.author.id:
        return await interaction.response.send_message('no')
      await interaction.message.delete()

@bot.command()
@commands.has_guild_permissions(administrator=True)
async def nuke(ctx):
  embed = discord.Embed(description=f'{ctx.author.mention} are you sure you want to nuke this channel?', colour=0x303135)
  await ctx.send(embed=embed, view=View2())
``` ```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __init__() missing 1 required positional argument: 'bot'``` i get this error when i try to use the command huh?
true stump
#

Is it possible to make hidden slash commands?
When listing all commands, I got an error saying that SlashCommand doesn't have an attribute hidden

tulip bobcat
sonic lotus
#
async def testing(self, ctx):
    test_list = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
    await ctx.send(f"``{''.join(test_list)}``")
    # await ctx.send(f"``{'\n'.join(test_list)}``")

Why does the second line (Join on \n) completely disable my cog when enabled?
It doesn't load but also no error, just silently ignores the whole Cog

tulip bobcat
agile merlin
#

How do I get the url of a webhook, I have tried discord.Webhook.url but it returns this thing, <property object at 0x7f9c04f93a60>.

tulip bobcat
sonic lotus
prisma flicker
#

does .edit do nothing if the message doesn't actually change?

sonic lotus
#

😄

tulip bobcat
true stump
prisma flicker
tulip bobcat
#

because you don’t respond

tulip bobcat
#

I guess most you can do in terms of easter eggs, is specific inputs for the parameters

prisma flicker
tulip bobcat
#

it does?

prisma flicker
#

if the embed changes, it works as expected

#

yes

tulip bobcat
#

oh

#

i didn’t know

prisma flicker
#

it's only if it doesn't change it fails

true stump
#

Yeah, I guess I'll find a way. Most are owner-only or restricted to specific users anyway.

tulip bobcat
prisma flicker
#

actually I think something else is wrong now, now it doesn't work at all 😄

tulip bobcat
tulip bobcat
prisma flicker
#

I shouldn't change 2 things at once

true stump
#

Maybe I just keep them as prefixed commands, so they only work in dms or when you mention the bot. This would be pretty easter-eggly ig ^^

tulip bobcat
#

@true stump I had the issue with unregistereing commands 2 days ago, maybe the question could help you #1006918207703101440

#

or that way

prisma flicker
#

oh I forgot to return true in interaction_check facepalm

#

eh I guess deleting and re-sending works fine

#

I wanted to avoid that but 🤷

#
-                await queue_last_msg.edit(embed=embed, view=view)
+                if queue_last_msg:
+                    await queue_last_msg.delete()
+                queue_last_msg = await self.bot.get_channel(session.id).send(embed=embed, view=view)```
tulip bobcat
#

I'm sure there is a way around it

prisma flicker
#

if there is I don't know it

#

short of spamming the user with ephemeral messages

cyan quail
#

since it still sends the request

prisma flicker
cyan quail
#

from what i just tested it worked fine

prisma flicker
#

interesting

cyan quail
#

@prisma flicker nope, it's all raw permissions; any role that matches the permissions you pass in will also be able to use the command

#

or i guess any user

prisma flicker
#

thought so

#

so there's no way to programatically add roles to the integrations screen?

cyan quail
#

nope

#

discord doesn't let you add anything there without a bearer token now

prisma flicker
#

isn't the idea that integrations can bypass like discord.ext.commands.has_any_role

#

ah interesting

cyan quail
#

no

#

the ext.commands checks are internal

#

so integrations menu permissions can't bypass them

prisma flicker
#

internal to pycord?

cyan quail
#

yes, they're on the bot end

prisma flicker
#

so what decorators can integrations bypass

cyan quail
#

they don't

prisma flicker
#

I'm so confused lol

cyan quail
#

integrations menu stops commands from being shown at all to users who don't have the necessary permissions

#

and if they do somehow see it, they still can't run it

prisma flicker
#

so it's only to make it more restrictive, not less?

cyan quail
#

yes

#

ext.commands permissions will still let the command "execute", but it'll just raise a CheckFailure

prisma flicker
#

right, and let the user see it

cyan quail
#

yes

prisma flicker
#

where discord.commands.default_permissions hides it from the user

cyan quail
#

mhm

#

for owner-only/potentially dangerous commands, internal checks are basically a must have

prisma flicker
#

I do it in the actual code right now

cyan quail
#

that works too

prisma flicker
#
@commands.user_command(guild_ids=[717808299675877406], name="Gulag")
# @discord.commands.default_permissions(ban_members=True)
# @discord.ext.commands.has_permissions(ban_members=True)
async def gulag_ctx(self, ctx, member: discord.Member):
    """Sends the member to the gulag"""
    if not await check_access(ctx, "Gulag", mods_only=True):
        return```
cyan quail
#

and of course there were always used pre-slash command, and for example the lib would hide commands from the help command by default if the user didn't meet permissions

#

because of the can_run function

prisma flicker
#

can I do that with a custom help?

prisma flicker
#

so like this?

for command in self.bot.walk_application_commands():
    if not await command.can_run(ctx):
        continue```
cyan quail
#

yeah

prisma flicker
#

sweet

errant craneBOT
#

discord/ext/pages/pagination.py line 601

async def goto_page(self, page_number: int = 0, *, interaction: Optional[discord.Interaction] = None) -> None:```
cyan quail
#

it basically always defers if it's from an interaction

prisma flicker
cyan quail
#

oh right it raises an error oops

prisma flicker
#

ok cool

errant craneBOT
#

discord/ext/commands/help.py line 263

class HelpCommand:```
prisma flicker
#

I already have one, it just didn't have that check

cyan quail
#

ah right

prisma flicker
#

also have it set the number of elements depending on whether you're on mobile 😛

cyan quail
#

o nice

prisma flicker
#
if member.is_on_mobile():
    limit = 9
else:
    limit = 24```
cyan quail
prisma flicker
#

ah

cyan quail
#

yep pretty much

prisma flicker
#

what's the filter criteria

cyan quail
#

checks if the user can run it, and optionally checks if the command has hidden=True set

#

which i think is default

errant craneBOT
#

discord/ext/commands/help.py line 532

async def filter_commands(self, commands, *, sort=False, key=None):```
prisma flicker
#

hidden is False by default

cyan quail
#

i mean it by default checks if hidden

#

and if so hides it from help

prisma flicker
#

yeah

cyan quail
#

hey it even does default/custom sorting if you care

prisma flicker
#

hidden just hides it from the default help?

cyan quail
#

yes

prisma flicker
#

yeah I think they're sorted by... order loaded by default?