#Basic Pycord Help (Quick Questions Only)

1 messages · Page 71 of 1

proud mason
#

you cant do that in slash cmds

stark walrus
#

oh

proud mason
#

yeah

stark walrus
#

oof okay

proud mason
#

your only choices are accepting mentions as strings, or doing some fuckery with autocomplete

stark walrus
#

i recoded a bit of the command now it returns an error if role and channel both are given

stark walrus
proud mason
#

but that’s upto you

stark walrus
stark walrus
lethal hare
#
class Youtube_Cog(commands.Cog):
    

    def __init__(self, bot_: commands.Bot):
        self.bot = bot_
        self.command_group = self.bot.create_group("youtube", "Control youtube audio in voice chat")

    @self.command_group.command()
#

How can I do what I'm trying to do here with the @violet magnet decorator

#

since that obviously isnt valid

#

sorry guy I tagged lol

#

ah nvm

#

this does it

ornate current
#

permissions doesnt work on subgroups

#

what to do

lethal hare
#

anyone know how to make slash command groups inside a cog?

proud mason
stark walrus
#

how to make a filter for a valid integer which is between 1 and 100,000?

#
@option("level", Union[], description="The level at which a role should be rewarded.")```
#

Idk what to put inside the Union, idk if it's right so far

stark walrus
#

couldn't find anything relevant on stackoverflow ;o

proud mason
stark walrus
proud mason
#

In the option decorator

proud mason
stark walrus
#

oh

#

makes sense then tysm

#

and +-2^53 is the limit right?

proud mason
#

.tias

winter condorBOT
proud mason
#

Or find it in discord docs

stark walrus
#

alright!!

stark walrus
#

How to change the SlashCommandOptionType

#

oh nvm i figured it out

#

i forgot to put level:int in the typehint

merry dune
#

@stark walrus if this is a command, then the question is why do you make an exception for permisses in the "if"
if you can use ```py
@commands.#functions example has_any_role("role"),
@commands.has_permissions(administrator)

stark walrus
#

or have it respond to all such in the on_command_error event

#

right?

merry dune
fervent cradle
#

hey

#
@client.slash_command(guild_ids = servers, name="post-leaks", description="Postet einen Leak")
@commands.has_any_role(1073964313309614154)
async def postleak(ctx, channel: Option(discord.TextChannel, description="In welchem Channel soll der Leak gepostet werden?", required=True)):
    if channel is None:
        channel = ctx.channel

    await ctx.send_modal(PostLeakModal(title="✨ Leak Posten"))

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

        self.add_item(discord.ui.InputText(label="Name", placeholder="ws_hud"))
        self.add_item(discord.ui.InputText(label="Preview", placeholder="Placeholder"))
        self.add_item(discord.ui.InputText(label="Download", placeholder="Placeholder"))
        
    async def callback(self, interaction: discord.Interaction):
        embed = discord.Embed(title="\✨ Neuer Leak", color=0xff0000)
        embed.add_field(name="Name:", value=self.children[0].value, inline=False)
        embed.add_field(name="Preview:", value=self.children[1].value, inline=False)
        embed.add_field(name="Download:", value=self.children[2].value, inline=False)
        embed.set_author(name="FlareLeaks #2,0k", icon_url="https://cdn.discordapp.com/attachments/1073964316010758206/1079478593303875614/Founder.gif")
        embed.set_footer(text="Offizieller Bot by !Colin † ™ 🎾#0001 | FlareLeaks #2,0k", icon_url="https://cdn.discordapp.com/attachments/1073964316010758206/1079478593303875614/Founder.gif")
        embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/1073964316010758206/1079478593303875614/Founder.gif")
        await interaction.response.send_message("> Leak wurde erfolgreich gepostet!", ephemeral=True)
        await channel.send(embed=embed)```
#

how can i get the channel in the class that I have in the slash command?

fervent cradle
full basin
#

Using the init

young bone
full basin
#

You should know how to work with classes if you're coding with pycord

fervent cradle
fervent cradle
full basin
#

No

fervent cradle
#

idk how

#

pls

full basin
#

Then learn python

fervent cradle
#

amk

#

global channel?

full basin
#

?

fervent cradle
#

to pass it

#

google said me

#

idk

full basin
#

We won't help you

fervent cradle
#

why

#

then dont write in my thread

#

that a good helper can help me

full basin
#

No one will help you

#

#help-rules states you won't receive help if you don't know python

fervent cradle
#

i know py

#

shut up pls

full basin
#

If you knew python, you'd know how to pass a simple variable to a class

fervent cradle
#

idk where i can find it in the docs

#

!!!!!

full basin
#

¯_(ツ)_/¯

fervent cradle
#

idk

ocean pumice
#

Hello, i'm trying to send an embed through a webhook but I can't figure out where is the problem. This is the payload:

  "content": null,
  "embeds": [
    {
      "title": "Title",
      "description": "description",
      "color": 5814783,
      "fields": [
        {
          "name": "Field 1",
          "value": "Field description"
        },
        {
          "name": "Field 2",
          "value": "Field descriptions"
        }
      ]
    }
  ],
  "attachments": []
}``` 
and it's being sent through this line of code 
```py
response = requests.post(webhook, data=payload, files=files)```
#

Any wonders why it's not working?

#

Failed to send webhook: 400 {"embeds": ["0"]}

#

Oh I think I found the problem

#

i forgot the headers

proud mason
young bone
#

self.update_avatar()?

#

self.bot.fetch_user

spring hare
spring hare
young bone
#

what?

spring hare
#

from guide.pycord.dev

import discord
from discord.ext import commands

class Greetings(commands.Cog): # create a class for our cog that inherits from commands.Cog
    # this class is used to create a cog, which is a module that can be added to the bot

    def __init__(self, bot): # this is a special method that is called when the cog is loaded
        self.bot = bot

    ...

def setup(bot): # this is called by Pycord to setup the cog
    bot.add_cog(Greetings(bot)) # add the cog to the bot

Why not like that?

import discord
from discord.ext import commands

global_bot = None

class Greetings(commands.Cog): # create a class for our cog that inherits from commands.Cog
    # this class is used to create a cog, which is a module that can be added to the bot

    def __init__(self): # this is a special method that is called when the cog is loaded
        ...

    ...

def setup(bot): # this is called by Pycord to setup the cog
    global global_bot
    global_bot = bot
    bot.add_cog(Greetings()) # add the cog to the bot
silver moat
spring hare
#

Or every cog need to have self.bot?

silver moat
#

each cog needs a bot attribute

spring hare
#

Oh, okay. Thank you

merry dune
fervent cradle
#

How

merry dune
#

guys help, I want to prepare a little joke so that the bot would catch the user's messages, delete it and then write the entire text itselfpepehmm
Who faced a similar problem

fervent cradle
#

Idk pls help me

merry dune
#

@fervent cradle

chan = channel.id
send_ch = bot.guild.get_channel(chan)
await send_ch.send(message)
fervent cradle
#

Thanks

full basin
merry dune
#

@fervent cradle sorry i have mistake, automatic ctx write doggokek

fervent cradle
#

Okay

merry dune
#

@full basin so to speak, the muse escaped me and I’m thinking where to start using a static command without a prefix or a bot event, I don’t like messing around with events, although this is the simplest solution

#

I'm just looking for inspiration mostly, that's while chatting about x y conflicts, I created a code for checking messages but temporarily put it on the back burner because the hosting almost burned down at one moment doggokek

#

But unfortunately, I still can’t fix a technical flaw in the game timer, with a repeated or unreadable answer, it restarts the timer, I thought about creating an exception, but maybe it will kick again game

proud mason
#

bro why does this person sound like an ai to me

full basin
#

I didn't understand a thing of those 3 paragraphs

merry dune
#

AI I am interestedblobpain looks like I've been exposed

proud mason
fervent cradle
#

So I sometimes host an bot in replit, not important. But is there any way I can change the server with the console

#

Server name I mean

#

So it asks me to what I want to change it

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.

merry dune
#

Heya, i have question, i want create fun command/event bot take my msg, delete original and send itself

and I think how to do it in interaction mode so that the bot does not delete, but removes the message by api and send

fervent cradle
slow panther
silver moat
#

?tag replit-install

obtuse juncoBOT
slow panther
slow panther
#

any other free platforms to host my bot ( i m newbie so cant spend money atm)

silver moat
#

if you are a student and have a school email, you can use microsoft azure

slow panther
#

how about github ? willl it work for hosting pycord bot ?

silver moat
#

github doesn't host python scripts, they only host websites.

slow panther
silver moat
#

If you have a credit card, you can use railway.app or oracle free tier

limber urchin
#

If you actually want a good host, you're going to have to spend money though. Railway or Oracle will work fine for early stages.

silver moat
limber urchin
#

Depends on what the bot is doing, but yeah, as long as the bot is small, a free host will be "good enough"

shut jasper
#
    async def callback(self, interaction: discord.Interaction):
        email = self.children[0].value
        donate_return = await donate(
            email, self.plan, interaction.user.id, type=self.type
        )
        await interaction.response.send_message(
            f"Please pay the invoice at the following URL: {donate_return}, the link has also been messaged to you.",
            ephemeral=True,
        )
        await interaction.user.send(
            f"Please pay the invoice at the following URL: {donate_return}."
        )```
#
'coroutine' object has no attribute 'id'
/Users/X/bot.py:222: RuntimeWarning: coroutine '_static_request_patch' was never awaited
  donate_return = await donate(
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
#

i did await it tho?

proud mason
#

i think python is trying to guess where to await

#

like if you had

async def func()
  return "Hello"

and you did

l = await func().upper()

then python might try calling func as a normal sync function, and thinking that upper is the async function, so it awaits that

merry dune
#

@shut jasper u use static slash with global variable?🧐

shut jasper
# proud mason full traceback?
'coroutine' object has no attribute 'id'
/Users/XXX/bot.py:224: RuntimeWarning: coroutine '_static_request_patch' was never awaited
  donate_return = await donate(
Object allocated at (most recent call last):
  File "/Users/XXX/venv/lib/python3.11/site-packages/stripe/api_resources/abstract/createable_api_resource.py", lineno 16
    return cls._static_request(```
#

good?

merry dune
#

Full errors traceback blobpain

shut jasper
merry dune
merry dune
merry dune
#

@shut jasper u donate_return can't see donate (vars<)

#

on it I had a question whether you use global variables in the code?

fervent cradle
#

What port does py-cord use?

limber urchin
#

???

#

why would pycord use a port?

fervent cradle
#

connect to network

limber urchin
#

It's a client that does HTTP communication, it doesn't use any port unless you're talking about 80 and 443, but that's literally any program that needs HTTP(s)

tired goblet
#

Is discord going to remove support for normal commands?

#

I mean ones we use without the slashes

limber urchin
#

What?

#

How would they do that?

tired goblet
#

Such as !help

limber urchin
#

That's literally impossible for them to do unless they completely block bots from reading message contents

tired goblet
limber urchin
#

They obviously want you to use slash commands, and it makes sense because they're way better

#

But they won't "remove support", because they don't have "support" for it in the first place. It's just the library parsing messages as commands and responding accordingly.

tired goblet
#

I see

#

Thanks. I was going to start writing a new bot and just future proofing it

limber urchin
#

You still need message content intents for normal commands to work though, so unless your bot has a good use case for that intent, you're doomed if you ever want to verify your bot.

tired goblet
limber urchin
#

You can apply for it, but if you don't have a good use case, they won't give it to you.

#

And no, commands is not a valid use case

tired goblet
#

I see

#

Thanks for the heads up

merry dune
tired goblet
#

Okay

proud mason
desert igloo
#

can someone PLEASE help me with the following error?:

File "main.py", line 31
    
                                ^
SyntaxError: unexpected EOF while parsing
#

my code only has 30 lines and yet this is happening

#

I'm not sure if this is a repl.it error or a pycord error

limber urchin
#

You have some weird whitespace character in your code. Nothing to do with pycord

#

My guess is that you copied the code from somewhere and when you pasted something tried to format it and failed

desert igloo
#

I didnt

#

its original code

#
import discord
import random
import os

bot = discord.Bot(command_prefix="cmd ")

@bot.event
async def on_ready():
    print(f"we have logged in as {bot.user}.")

@bot.slash_command(name='message')
async def message(ctx):
    await ctx.respond("alright: \n")
    rand = random.randint(1,3)
    if rand == 1:
        await ctx.respond(f"WHY DID YOU WAKE ME UP!")
    elif rand == 2:
        await ctx.respond(f"arrgh I was busy!")
    elif rand == 3:
        await ctx.respond(f"stop commanding me around!")

@bot.slash_command(name="thread",description="make a thread")
async def thread(ctx):
    message = await ctx.respond("alright but you could have done it yourself")

@bot.slash_command(name="thread",description="make a thread")
async def thread(ctx):
    message = await ctx.respond("alright but you could have done it yourself")

bot.run((os.getenv("TOKEN"))
limber urchin
#

And how did you get it into replit?

desert igloo
#

ok wait there was an extra bracket

#

bot.run(**(**os.getenv("TOKEN"))

#

bot.run(os.getenv("TOKEN"))

slow panther
#

@limber urchin @proud mason can i dm any1 of u to help me with my bot stuff ?

limber urchin
#

no

#

read #help-rules

slow panther
#

I can dm for help if helpers are ok with that

waxen whale
#

no

slow panther
#
  1. Remember that
    You can't dm help people unless they allow you to do that even staff members
limber urchin
#

You cannot ping or DM people for help unless they allow you to do so, even if they are staff members.

#

What part of that rule didn't you understand?

slow panther
waxen whale
#

you don't have the perms for that

just ask here or create a new post

slow panther
#

& the reply was no from your side prayadge

slow panther
fervent cradle
clever hinge
#

I believe the new voice messages can be already read with pycord, right?

#

I was thinking of making a transcription command through whisper, not sure if that would work properly though

fervent cradle
#

I was on Aliucord on my phone earlier, I haven't updated it ever, I saw them as .ogg files.

#

They are just standard attachments, which pycord can handle.

clever hinge
#

I've seen on mobile that they're basically .ogg files, not sure if the api handles the voice messages the same way as basic files though

clever hinge
fervent cradle
#

One would assume they would just be standard file attachments.

#

I am not sure what you are trying to achieve, but you can just check if the attachment is an ogg

clever hinge
slow panther
fervent cradle
young bone
slow panther
#

Btw what u mean by basics

fervent cradle
#

...

#

the basics...

#

Do you know how to code in Python?

slow panther
#

Yes

fervent cradle
#

Alright. all you have to do is install pycord from pip and import it.

young bone
#

how you install stuff is basic stuff

fervent cradle
#

Reading documentation too! That's like basic computer knowledge kek

slow panther
#

My friend got alot of errors & stuff he had installed multiple libraries

fervent cradle
#

Alright, well is it working for u atleast

lethal nexus
#

Can I make a slash command alias or do I need to just duplicate the command code and change the name?

lethal nexus
#

like /lock and /close - but the command does the same thing

young bone
#

give it a new name

young bone
lethal nexus
young bone
#

ye

#

but why do you do that?

slow panther
#

how to host my bot code written in vs code

young bone
#

what?

young bone
#

VS Code is not for hosting a Bot

slow panther
#

i will use hosting provider

#

to host my bot

#

nbut how to host it like is it possible to link them or smh like that ?

glossy tusk
#

Hello, I have created a task loop in my bot. And I gave it a list with 4 hours as datetime object.
However, after the bot completed its task at the last hour (02:00) in the parameter, it put the loop into an endless loop and sent the message that should throw certain hours. Do you have information and suggestions about the reasons and precautions for this?

glossy tusk
solemn idol
# slow panther my code is written in vs code bruh

vscode is just an editor, with some really nice to have tools, but your bot is never hosted in vscode.
You can use the terminal provided in vscode to host your bot but that does not automatically mean it's hosted in vscode as it is still hosted on the machine you're using vscode on.

slow panther
#

@solemn idol @glossy tusk i m not saying that i will host my bot in vs code but i m asking that how to host my bot on hosting ( code is in vs code can i link them somehow ?)

glossy tusk
proud mason
#

but yea like the other guy said, upload code to github

slow panther
#

@limber urchin

young bone
slow panther
young bone
#

why are there spaces?

limber urchin
slow panther
slow panther
limber urchin
slow panther
limber urchin
#

Follow the rules or get out

limber urchin
#

You can't expect anyone to help you if you can't follow basic rules

waxen whale
#

more like watching this now

young bone
#

lul

slow panther
limber urchin
#

It's not that hard to read, is it?

waxen whale
#

y'all calm down

slow panther
#

i apologize

slow panther
young bone
#

that is not a vs code error

limber urchin
slow panther
#

i mean code error in vs code

proud mason
#

😂

silver moat
#

you can try asking the in python server (.gg/python). Their explanations should be much better than what we give here.

grizzled sentinel
#

(This server is for making discord bots in python)

cerulean halo
#
        print(f"Guild: {guild.name}")
        for member in guild.members:
            if not member.bot:
                print(member)```


Now It raises an error saying I must have server intent members on and it's on.
young bone
cerulean halo
#

I'm so fucking dumb ty

shut jasper
#

ok it works now but it keeps saying this, is the library im using bugged?

undone falcon
#

I put manage_role=True as a default permissions, but people without permisisosn cna still see them and use them

#

Do you know why the default_permissions dont work ?

#

( it was working before I put them in a slash group)

undone falcon
young bone
undone falcon
young bone
#

I mean at the command

#

not the group

undone falcon
#

I want to put a default_permissions

young bone
#

use both

undone falcon
#

the default permissions does not work

#

that is my problem

#

it works for single commands, but when I put in groups it is not working anymore

undone falcon
# undone falcon

see I have the default_permissions(manage_roles=True), but not working

#

I switch account to test, it is a member with no roles or permissions but i can still see and use the commands

#

and I just tested it, works perfectly when not in a slash group like that:

#

It is getting big gonna open a thread

queen raft
#

Does the on_message event count towards discord's rate limits?

young bone
silver moat
fervent cradle
#

what happened to spaxter?

#

Dude just left?

silver moat
#

¯_(ツ)_/¯

torpid wraith
#

How would I add an autocomplete option to a command in a cog, where the autocomplete function requires self as one of its parameters?

jaunty jewel
#

just add that function belong the class cog and async it, or make it like a normal command code (with the autocomplete function) in a new file and import that file in the main.py

#

however by talking about the autocomplete, as my knowledge if the ac function didn't returned anything within 3sec's and then it returns i will get 404

so how to make an exception for that error, i mean where even the expect logic will goes :\

torpid wraith
#

Here's my command in my cog (it's also in a slash command group of "character"):

@character.command(name = "view", description="Display basic info about one of your player characters")
async def create(
    self,
    ctx,
    name: discord.Option(str, autocomplete=discord.utils.basic_autocomplete(get_player_characters))
):```
#

I have this for the async ac function:

async def get_player_characters(self, ctx: discord.AutocompleteContext):```
#

Error:

TypeError("get_player_characters() missing 1 required positional argument: 'ctx'")>```
jaunty jewel
jaunty jewel
torpid wraith
proud mason
#

dont put the function in the cog class

#

define it above the cog class, in the global scope of the file

jaunty jewel
#

send the code to debug it (‾◡◝)

torpid wraith
#
# bot.py
# Database Initialization
db = SimpleMysql(
    host=DB_HOST,
    port=DB_PORT,
    db=DB_NAME,
    user=DB_USER,
    passwd=DB_PASSWORD,
    keep_alive=True
)

# Add cogs to bot
bot.add_cog(CogCharacters.CogCharacters(bot, db))```
#
# cogs/CogCharacters.py
class CogCharacters(discord.Cog, guild_ids=[GUILD_ID]):
    def __init__(self, bot, db):
        self.bot = bot
        self.db = db```
proud mason
#

ah

#

you can do ctx.command.cog or smth iirc

#

that returns the cog instance

#

let me just check

jaunty jewel
torpid wraith
#

Would the cog object hold the instance variables?

proud mason
proud mason
torpid wraith
proud mason
#

because it is the same instance which is returned

jaunty jewel
torpid wraith
#

I'm guessing the first...

jaunty jewel
#

:\

torpid wraith
#

Follow up question... How would I access the command author (caller) in this autocomplete function?

#

ctx.author doesn't work 😕

#

Because I confused AutocompleteContext with CommandContext

proud mason
torpid wraith
proud mason
#

it is

#

hint- ||check out the interaction attribute||

torpid wraith
#

Oh, I thought Interactions were something completely different from bots, my b. Tyvm

#

Am still noob, sry 😅

torpid wraith
#

Is there any way for Option choices to be dynamic like autocomplete?

#

I could cheap out and just return an error if the value given is not in the DB, but it'd be cooler if invalid values were prevented in the first place

haughty sluice
#

how do I get an interface like this for the user variable? 👀

torpid wraith
haughty sluice
#

yep like the list that shows up

torpid wraith
#

You'll see a Type it accepts is discord.Member

haughty sluice
#

o.O

#

tysm

jaunty jewel
soft girder
#

Hello .How to fix this problem.

fast badger
#

how can i give an edited message a view, message and a file?
when i try to it throws

          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: InteractionResponse.edit_message() takes 1 positional argument but 2 positional arguments (and 2 keyword-only arguments) were given```
soft girder
#

In my opinion it is better to use "intr" ,a "interaction" .Although you can do it like this😓

soft girder
wary kernel
#

That's my code doesn't seem to work:

async def ban_marked_users():
    await bot.wait_until_ready()
    while not bot.is_closed():
        banned_users = []
        with open("marked.txt", "r") as f:
            marked_ids = [line.strip() for line in f.readlines()]
        for guild in bot.guilds:
            for member in guild.members:
                member_id = member.id
                if member_id in marked_ids:
                    await guild.ban(member, reason="User is marked.")
                    banned_users.append(member.id)
        if banned_users:
            print(f"Banned users: {', '.join(banned_users)}")
        else:
            print("No marked users were found in any server.")
        await asyncio.sleep(5)
safe stirrup
#

What is the recommended way in bridge extension to restrict commands to owner only

fast badger
proud mason
#

You just need to pass content as a kwarg instead of a positional arg

fervent cradle
#

If I used commands.Bot instance, will I still be able to create a slash command?

blissful hazel
fervent cradle
#

Hey very stupid qeustion but how to get guild id?

young bone
fervent cradle
#

But u need id

#

to get the id?

young bone
fervent cradle
#

to save guild specific info

#

get_guild(id, /)?

#

U need the id to fetch the guild object

young bone
#

at a command?

fervent cradle
#

yes

young bone
#

you already get the guild with ctx.guild

cerulean halo
#

@bot.event
async def on_ready():
for guild in bot.guilds:
print(f"Connected to server: {guild.id}")

#

For example

fervent cradle
#

Yes

cerulean halo
#

That's the same.

fervent cradle
#

of all the guild my bot is in

cerulean halo
#

Yes. Do you want a specific guild?

cerulean halo
fervent cradle
#

The one the command was excecuted in

#

K i fixed

cerulean halo
#

@bot.command()
async def guildid(ctx):
guild = ctx.guild
guild_id = guild.id
await ctx.send(f"The ID of this guild is {guild_id}.")

fervent cradle
#

thx a lot

cerulean halo
#

Sure.

#

Ofc you can do it just in one line but just in order to make it clear.

cerulean halo
#

Sure.

#

If you need anything else don't be afraid to ask!

drifting birch
#

I want to set an image to an embed. I have a discord.File object of the image, but embed.set_image() only supports HTTP(S) urls. How can I send that image through an embed?

full basin
#

?tag localfile

obtuse juncoBOT
#
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
full basin
#

@drifting birch

drifting birch
#

thanks ❤️

hallow oriole
#

What is the best way to trigger a the bot when AutoMod flagged a message? Is there a dedicated event or do I must filter via on_message?

full basin
#

.rtfm on_automod

winter condorBOT
#

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

full basin
#

There's probably some event.

#

on_message won't trigger iirc, because no message I sent

proud mason
#

Check the actual docs. The rtfm cmd can be outdated

cursive heron
#

how can i create a modal in pycord

tired goblet
#

hi, when my bot responds with a link, there is an embed that discord automatically generates, possible to turn it off?

errant craneBOT
#

Here's the modal dialogs example.

full basin
#

@cursive heron

tired goblet
torpid wraith
#

How would I pass extra arguments to a View class that will display buttons? For learning purposes, I want to make a Poll command that takes in several options and displays a button for each.

proud mason
torpid wraith
#

I should probably go learn about Python subclassing and overriding... 😅 Sry. At least I know what direction to head now, thx.

proud mason
#

It is also necessary to properly use dpy

torpid wraith
#

I love OOP, but I'm so used to it in other languages and Python is growing pains for me, haha

#

dpy?

proud mason
#

Ah lol

#

Py-cord my bad

torpid wraith
#

ahh

proud mason
#

💀

silver moat
#

💀

proud mason
#

Both are largely the same lol

#

💀💀

silver moat
#

true

torpid wraith
#

I won't have to do anything special if I put this in a Cog, right? Just make the view a nested class and proceed as normal?

silver moat
#

You don't even need to put it inside of a cog

#

you can put it outside of the cog

torpid wraith
# silver moat You don't even need to put it inside of a cog

Ok, I keep hearing this, and I have to ask... What's the deal with Cogs? I was given the impression that Cogs should be used to organize your larger code projects by splitting up the code into different modules/files. Is there a better way to do this?

silver moat
#

cog could be ambiguious: it could refer to the actual file, or the actual class in the file.

#

here, I'm referring to cog as the class

torpid wraith
#

Ohhhh, so when you said to put it outside the cog, you meant the cog class within the cog file?

#

ohhhhhh

silver moat
#

yes

torpid wraith
#

Forgive my ignorance, but can you call a class while inside a different class?

torpid wraith
#

So, the View class is just, I guess, within the global space of the file?

silver moat
#

yeah

torpid wraith
#

Is this true with Java too?... I'm so used to only having one class per file with my Java projects that all this Python craziness is giving me a run for my money, lol

silver moat
#

java literally only allows you to have one global class per file.

#

But you can have inner-classes in java, but not really standard practice

torpid wraith
#

Ahh, okay, I'm not crazy then 😅 haha. Just need to get used to Python then. Thx!

silver moat
#

yw

waxen whale
#

hmm

solemn idol
#

Hmmm

coarse cargo
#

Hi guys, i have a code that get some options from a yml file and creates an option for a dropdown menu with them it works fine but i dont know how to make a callback for every option. The callback should change the channel name and it is also specified in the configuration file.

This is my yaml file

dropdown:
#You can create as many options as you want, Max is 25 (Discord Limitation)
 option1:
  name: "Account"
  description: "For issues regarding your in-game account."
  emoji: ":bust_in_silhouette:"
  ticket_name: ":bust_in_silhouette:┃account-{interaction.user.name}"
 option2:
  name: "Store Support"
  description: "For issues regarding the store and payments."
  emoji: ":money_with_wings:"
  ticket_name: ":money_with_wings:┃store-{interaction.user.name}"

This is how i get the values:

menu_options = [
        discord.SelectOption(label=dropdown[option_key]['name'], description=dropdown[option_key]['description'],
                             emoji=dropdown[option_key]['emoji'])
        for option_key in dropdown
    ]

And this is my dropdown:

@discord.ui.select(placeholder=ticketchannel['dropdown_placeholder'], min_values=1, max_values=1, options=menu_options,
                       custom_id=f"menu")
woeful skiff
#

My code:

@bot.listen()
async def on_message(message):
ms = message.content.lower()
if "hello" in ms:
    await message.reply("Hey!")
elif ".gg/" in ms:
    await message.delete()

The above one works, that one with hello!
But the .gg doesn’t work, why?

silver moat
#

.idw

winter condorBOT
#

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

woeful skiff
#

I want to delete all msgs with .gg/ in it

silver moat
silver moat
woeful skiff
#

I know, the "Hey!" Shouldn’t get deleted. Only the ones with .gg/ in it

silver moat
#

did you re-run the bot prior to testing

woeful skiff
#

yes

silver moat
#

is the indentation correct?

woeful skiff
#

wdym

#

oh yes it is correct

#

i've got no errors

silver moat
#

I'm assuming it's just discord formatting.

woeful skiff
#

So it should work?

silver moat
#

have you tried logging what the actual message content is?

woeful skiff
#

No

#

I could try that

#

It isn't even printing

#

The content

#
elif ".gg/" in msg_cnt:
    await message.delete()
    print(msg_cnt)
silver moat
#

Is the event firing or is the content None

silver moat
woeful skiff
#

wdym, sorry I ain’t a good English speaker :/

silver moat
woeful skiff
#

Oh ok

#

Do I have to global the msg_cnt?

#

?

lime moss
#

is there any way for me to detect if a channel or thread with a certain name already exists?

lime moss
#

wdym? im pretty new to this

young bone
#

Do you know basic python?

lime moss
#

yes

young bone
#

so?

lime moss
#

there isnt any api stuff i need to call?

young bone
#

.rtfm channel

young bone
#

.rtfm thread

lime moss
#

Thank you

fallen cove
#

gat a tuple of ids from a db but getting the category returns None

#
category = self.bot.get_channel(res[0])```
#

(1088104344806756442, 1088104170369863790, 1088104378549928036, 665380862568955935, 673602588972941323, 665384487357513741, 731520984170889236, 673619055961178132, 665380774941556759)

silver moat
#

try fetching it

fallen cove
silver moat
#

.rtfm fetch_channel

silver moat
#

fetch it

fallen cove
#

hmmmnever used fetch before

silver moat
#

i mean only fetch it if the channel is None

fallen cove
silver moat
fallen cove
fallen cove
# silver moat get is cache fetch is api call

Traceback (most recent call last):
File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "c:\Users\philc\Desktop\Artemis-2.0\bot\src\cogs\medbayV2.py", line 161, in nffc_callback
nffcticket = await interaction.guild.create_text_channel(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\guild.py", line 1263, in create_text_channel
data = await self._create_channel(
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\philc\Desktop\venvs\BotDev\Lib\site-packages\discord\guild.py", line 1152, in _create_channel
parent_id = category.id if category else None
^^^^^^^^^^^
AttributeError: 'coroutine' object has no attribute 'id'

#
res = await get_ids(interaction.guild.name)
        # get the first word of the guild name
        



        # squadNames = platoon_search(platoonName)
        print(res)
        NFFC_category = interaction.guild.fetch_channel(res[0])
        print(NFFC_category)
silver moat
#

await it

fallen cove
#

shouldnt have missed that

young bone
#

its only 1:43 am for me

fallen cove
#

something im about to become acquainted too

fallen cove
lime moss
#

how would i do subcommands (like /queue dungeons)?

lime moss
#

thanks again

remote cove
#

Hi there, I just started and I am following the Quickstart guide. Is there a way to find all of the guild_id's in Python?

remote cove
#

Over here, there is the guild_ids argument for the decorator but how do I find all of the guild_ids that my bot currently has?

young bone
#

did you read?

silver moat
remote cove
#

@young bone Yes, I did read. From what I understand is that it is asking me to put a list of guild_ids where I want the command to work. But HOW do I find these guild_ids?

@silver moat I know but I want to know how to make it specific to certain guilds.

Hence, I want to find out HOW to find the guild_ids

young bone
#

right click at the server and copy the id

remote cove
#

Yes I know that exists. Is there a way to do it in Python where I don't have to individually go to every server where the bot is in?

silver moat
remote cove
#

Maybe I phrased it wrongly. I don't want a global command.
I want to:

  1. Find the guild_ids for which the bot has (find out what server(s) the bot is in)
  2. Use the guild_ids argument so that I can only allow certain guilds to use the command

My problem is that I don't know how to do (1) via Python. I know that it can be done manually by copying the id in Discord.

young bone
#

but you know the basic´s of Python?

silver moat
#

do you not want the bot to work in DMs or something?

#

Global commands work in every guild.

remote cove
#

@young bone I'm still learning but I think I know the basics.

@silver moat I just want to limit the commands to certain guilds not all guilds.

silver moat
#
for guild in bot,guilds:
  guild.id # the guild ID
young bone
#

bot.guilds*

#

;3

remote cove
round rivet
#

it's a list of discord.Guild

remote cove
#

ah ok, so i was looking at the wrong place. thanks!

round rivet
#

i'm unsure why the type of that isn't documented

#

it should be

rare ice
#

What are the arguments for raising CommandNotFound to get the command and context for the error handler to use? Might be confusing but I want to raise that error since something my error handler does for that error I need to use.

spring hare
#

Is there any way to send voice messages using Discord bots? (Perhaps webhooks?)

spring hare
#

Sad blobpain

spring hare
silver moat
gaunt bane
#

message.author.color gives black

#

How to get banner color

#

message.author.accent_color gives none

green hinge
#

Is it possible to change the color of a select menu or is there only the default gray color?

proud mason
#

Nope. Can't change

#

Discord limitation

green hinge
# proud mason Nope. Can't change

Okay too bad.
Do you have an idea how to make it visible that you have to select something? So that it is a mandatory information?
My original idea was to make the select menus red and when everything is filled in make them green but that doesn't work.

grizzled sentinel
#

You could send a red image that points to the select.

green hinge
#

Good idea I will test it as it looks 🙂

drowsy python
#
class buttons(discord.ui.View):
    def __init__(self, bot):
        self.bot = bot
        super().__init__(
            timeout=None
        )

    @discord.ui.button(label="Reject", custom_id='reject_button', style=discord.ButtonStyle.red)
    @discord.ui.button(label="Accept", custom_id='accept_button', style=discord.ButtonStyle.green)
    @discord.ui.button(label="Publish", custom_id='publish_button', style=discord.ButtonStyle.blurple)
    async def button_callback(self, button, interaction):
        if button.label == "Reject":
            oldEmbed = interaction.message.embed  # pull data from old embed
            embed = discord.Embed(title="Question Rejected",
                                  description=oldEmbed.description,
                                  color=discord.Color.red(),
                                  timestamp=datetime.datetime.utcnow())  # create new embed with old data + edits
            embed.set_author(name=oldEmbed.author.name + oldEmbed.author.discriminator,
                             icon_url=oldEmbed.author.avatar)  # i still have to include this
            return await interaction.message.edit(embed=embed)  # edits original message
        else:
            def check(m):
                return m.author.id == interaction.user.id

            uTimeRemaining = time.time()+120  # represents a unix time 2 minutes into the future
            await interaction.response.send_message(f"What is your response to the question {interaction.user.mention}?"
                                                    f"Time remaining: <t:{uTimeRemaining}:R>")
            test = await interaction.client.change_presence(activity=discord.Game('Test'), status=discord.Status.online)
            message = await interaction.client.wait_for('message', check=check)

have this code to try and make a multi button message but it only adds one, what have i done wrong and how do i fix it?

#

checked examples but i didnt see anything that uses multiple buttons

#

now realizing this means i shouldnt actually be doing this style of stuff

#

oops

cyan quail
# drowsy python ```py class buttons(discord.ui.View): def __init__(self, bot): self....

2 main ways

  1. have separate functions; each function should have a single button decorator, and you handle the logic for that specific button instead of all of them ```py
    @button(label="Reject")
    async def reject_button(self, button interaction):
    ...

@button(label="Accept")
async def accept_button(self, button interaction):
...2) Define more buttons inside `init` and assign the callbackspy
def init(self, bot):
reject = discord.ui.Button(...)
accept = discord.ui.Button(...)
reject.callback = self.callback
accept.callback = self.callback
super().init(reject, accept, ...)

async def callback(self, interaction):
...```

drowsy python
#

ok this is actually insanely helpful, tysm

cyan quail
#

or 3) create interaction_check inside your view which will act as a "callback" for the entire view

#

this isn't exactly intended and so some people recommend against it but it works...

drowsy python
#

i'll do the second one you suggested, seems cleanest

#

ty for the aid!

cyan quail
#

allgood

#

though be cautious; a standard callback without the decorator doesn't have a button argument, only interaction. in this case you should either:

  • use interaction.custom_id to identify what was pressed
  • if you need the button object itself, use self.get_item(custom_id)
drowsy python
#

gotcha

drowsy python
cyan quail
#

your original placement was fine

#

i just did it like that as an example since you can initialize a view with items with that format instead of using add_item

drowsy python
#

ahh ok

#

since i just did it blindly and well

cyan quail
#

timeout should be last

#

(general python rule: positionals have to be first)

drowsy python
#

icic

#

i am getting a separate issue though now

#

sorry if this is getting old i've never worked with buttons

#

very confusing

cyan quail
#

did you use button or Button

#

button is the decorator while Button is for usage as a regular item

drowsy python
#

OH

#

now its flawless

cyan quail
#

nice

drowsy python
#

oops lol, tyty

#

giving you the credit in the script for this lol, this made my life way easier

cyan quail
#

haha you don't need to, ultimately we're always learning stuff from others

#

stackoverflow is so famous for a reason

drowsy python
#

both famous and infamous lol

-1

quasi stratus
#

Hey, i got a quick question. Is it "bad" to use intents.all() even if we don't need all of them ?
In my case i use the none() then i enable the ones i need, but i see a lot of people enabling all of them even for basic bots, so i question myself xD

grizzled sentinel
quasi stratus
#

Thanks for the answer !
But message content is needed for commands no ?

grizzled sentinel
#

Prefix commands yes, slash commands no

quasi stratus
#

👌

proud mason
#

that is the only correct way

cyan quail
#

That's what I already suggested

#

Oh wait

#

Who the hell subclasses button

proud mason
cyan quail
#

I mean I guess you can but they were like 90% of the way there with the decorator

proud mason
#

subclassing button is much better than doing button.callback = some_func ngl

cyan quail
#

Not really

proud mason
#

Especially when you have 3 buttons which do the same thing

cyan quail
#

You can subclass but ultimately it's accomplishing the same thing without making too many jumps

proud mason
#

cleaner to read imo shrug

plush moat
#

heyhey
I get a message from a slash command, and in response I want to send a file and nothing else.
my current code is

                await ctx.send(file=discord.File(f"showorder.txt"))
                return

But right now it keeps saying "waiting for bot to respond" (which makes sense because I'm not doing a ctx.respond)
Is there a way to e.g. respond with an empty message, or let discord know I've sent a response but not to respond with a message?

proud mason
plush moat
#

Yeah, makes sense. Just wanted to check. Thanks!

proud mason
#

👍

cyan quail
#

that counts as a response...

plush moat
cyan quail
#

all good, sending a file still counts as a message so it works

plush moat
#

that's even better than what I wanted dogekek

cerulean halo
#

Unrelated to pycord where do you guys host you bots?

young bone
glossy forum
#

It's more out of curiosity than necessity, as I could do this without type-checking - but still:
Any idea why query: str | int lead to the error? I'm on Python 3.11.2 and Pycord 2.4.0

discord.errors.ExtensionFailed: Extension 'cogs.dbadmin' raised an error: TypeError: Invalid usage of typing.Union

Edit: Ah, It's because Slash commands don't accept this type, gotcha
#1047345278631559279 message

cerulean halo
solemn idol
cerulean halo
#

@solemn idolBut where which website?

quasi stratus
#

Hi ! Is there a way to create ForumTag in a ForumChannel ?
We have access to get_tag() and all the available tags but i don't see a method to create one as we have to create textchannel, thread etc...

Also, in the docs there's not hypertext link to ForumTag, idk if it's known

solemn idol
cyan quail
# quasi stratus Hi ! Is there a way to create ForumTag in a ForumChannel ? We have access to `ge...

so it's kind of weird, but it's in ForumChannel.edit under available_tags
https://docs.pycord.dev/en/master/api/models.html#discord.ForumChannel.edit
this takes a list of discord.ForumTag objects, however it seems they were forgotten in the docs. That being said, here's the main documentation for it py class ForumTag(Hashable): """Represents a forum tag that can be added to a thread inside a :class:`ForumChannel` Attributes ---------- id: :class:`int` The tag ID. Note that if the object was created manually then this will be ``0``. name: :class:`str` The name of the tag. Can only be up to 20 characters. moderated: :class:`bool` Whether this tag can only be added or removed by a moderator with the :attr:`~Permissions.manage_threads` permission. emoji: :class:`PartialEmoji` The emoji that is used to represent this tag. Note that if the emoji is a custom emoji, it will *not* have name information. """

#

(it's designed this way because that's how it's done on the API)

quasi stratus
#

Yeah i saw that, but how do i create a forum tag ?
I thought of the solution create tag + append to available tags but i need to create one before, and i can't generate ids etc...

cyan quail
#

that is how you make them

quasi stratus
#

It's not an issue if its created manually ?
Like the id is going to be 0

cyan quail
#

it'll get a proper ID when it's sent to discord

quasi stratus
#

Ho i see

#

Thansk for the answers

cyan quail
#

that being said it would be more convenient if we created our own methods to make this easier

quasi stratus
#

yup

full basin
#

Can we pass custom members to an user select?

full basin
#

how? 😭 the docs aint doc'ing

full basin
#

ok, makes more sense ty

young bone
#

I was testing it

#

x3

young bone
full basin
#

Yeah, I will. User selects were prettier

novel jay
silver moat
novel jay
silver moat
#

and I don't think I only want my app to be running for 60 hours a month

novel jay
#

true

red geyser
#

I'm trying to get my bot to join the vc but it wont

@commands.command()
    async def connect(self, ctx):
        if not ctx.author.voice:
            await ctx.send("You are not connected to a voice channel.")
            return
        channel = ctx.message.author.voice.channel
        await channel.connect()```
red geyser
#

py-cord==2.0.0rc1

young bone
#

oof

#

That is a really old version

young bone
red geyser
#

Bruh, i should really keep up with updates lol

young bone
#

Yes

red geyser
#

I've just updated and still no luck

full basin
#

Does it error or sum?

red geyser
#

nope

full basin
#

Have you tried debugging using prints

#

To see where it stops

red geyser
#

yeah, I add print(channel.id) right before the await channel.connect() and it gets the channel Id

red geyser
#
intents = discord.Intents.all()

client = commands.Bot(command_prefix='!', intents=intents)```
young bone
#

Anything else installed?

red geyser
#

What do you mean?

young bone
red geyser
#

no

#

Im guessing its syntax doesnt change if its in a cog?

young bone
#

Why should it change?

red geyser
#

idk, just didnt know if i needed to put self. in front of it

young bone
#

Does the bot has the permission to join a vc?

red geyser
#

yeah, it has administrator

#

so it should

fervent cradle
#

can a bot get webhook links'

#

like can i get all the webhooks in a channel and then use a random one to send a message

#

cuz i keep getting https://discord.com/api/webhooks/[webhook id goes here]/None

#

nvm i fixed

red geyser
red geyser
#

Okok

#

Works now

rare ice
#

This happens when I do: bot.dispatch('command_error', context=ctx, exception=commands.CommandNotFound)
I want to dispatch a command error since my command handler handles something important.

#

.rtfm discord.ext.commands.on_command_error

winter condorBOT
#

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

rare ice
#

.rtfm discord.ext.on_command_error

winter condorBOT
#

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

rare ice
#

.rtfm discord.ext.commands.Bot.on_command_error

winter condorBOT
rare ice
#

Says exception is a valid argument

cyan quail
#

they're positional

rare ice
#

Oh

cyan quail
#

(pretty sure all events only use positional args)

knotty brook
#

I want the buttons associated with the embed to be randomized

#

here are the buttons

proud mason
#

Are you trying to do like, random 1 of the 4 buttons is the right one?

knotty brook
proud mason
#

Ah

#

1 way would be to add buttons using view.add_item instead of the decorator

#

Oh wait there is a better way

knotty brook
proud mason
#

Try using random.shuffle on self.children

knotty brook
#

Im trying to use this

#

ah it aint workin

#

its same sequence everytime

proud mason
#

I'm not sure if this would work

#

So try it and see

knotty brook
knotty brook
#

i had another query

#

can i ask if u dont mind ?

proud mason
proud mason
knotty brook
# proud mason Sure

Ok so i want to fetch for the button if its the correct one pressed and display "You choose the correct one"

#

in this case

#

And random fruit is defined in slash command

#

It generates a random fruit name everytime as expected

proud mason
#

If yes then you should subclass Button

knotty brook
fast badger
#

how can i replace a file when editing a message?

green hinge
#

Why do I always get this error when I want to edit my interaction?

await message.edit_original_response('This is a Test', view=await View(self.bot, data, False))```
Error:

Interaction.edit_original_response() takes 1 positional argument but 2 positional arguments (and 1 keyword-only argument) were given```

proud mason
#

content="..."

proud mason
#

that is an example of subclassed Button

green hinge
proud mason
#

i would do smth like

class MyButton(discord.ui.Button):
  async def callback(...):
    if self.label == self.view.correct_label:
        ...

class MyView(discord.ui.View):
  def __init__(...):
    super().__init__(...)
    label_list = [...]
    random.shuffle(label_list)

    for label in label_list:
      self.add_item(MyButton(label=label))
#

@knotty brook ^

proud mason
knotty brook
#

Can i have a fix for this ?

#
    return await ctx.respond(embed = wrong)
                 ^^^^^^^^^^^
AttributeError: 'Interaction' object has no attribute 'respond'```
#

yes i have given ctx as and attribute

quasi stratus
proud mason
knotty brook
#

OR maybe wait i need to send_message

#

cuz buttons

#

How do i disable the buttons after certain period ?

quasi stratus
#

If you don't mind disabling all the children after a period you can give a timeout to your view

knotty brook
#

or like this

quasi stratus
#

Yeah

#

You can give it as a parameter

knotty brook
#

i can still click the buttons

full basin
#

It's on_timeout and it's a method

quasi stratus
#

The disable_on_timeout is set to False by default

knotty brook
knotty brook
full basin
#

I said it's a method

#

A funtion

#

Do you know basic python?

knotty brook
fast badger
#

how can i remove a file when editing a message? file = None just throws an error

proud mason
knotty brook
#

On interaction with the buttons ofc

proud mason
knotty brook
proud mason
#

.tias

winter condorBOT
proud mason
#

depends on when and where you are doing it

knotty brook
proud mason
#

if you havent used the library before, i suggest checking out the guide

#

.guide

winter condorBOT
fast badger
marble nova
#

how can i get a user's description? i dont see it in the docs

young bone
marble nova
#

Member then looking thru attributes? I didnt see anything matching

#

theres status and activities and everything but no description

full basin
#

I think the api doesn't provide the user's bio

gaunt bane
#
cmd = bot.get_command(cmdName)
print(f"{prefix or slash  here} {cmd.name}: {cmd.description}

How to get command is prefix or slash command

grizzled sentinel
#

Are you using bridge?

lime moss
#

How can I do sub options like /command option1 option1sub but not have option1sub appear on option2

gaunt bane
grizzled sentinel
#

Show me your bot = line

grizzled sentinel
errant craneBOT
#

Here's the slash autocomplete example.

gaunt bane
#

bot = commands.Bot(command_prefix='!',intents=discord.Intents.all(),help_command=MyHelp(),activity=discord.Activity(type=discord.ActivityType.listening,name='!help'))

grizzled sentinel
#

All you commands will be prefix.

silver moat
gaunt bane
#

i have slash command too

grizzled sentinel
#

Wait nvm, I forgot slash were backwards compatible.

silver moat
gaunt bane
#

hmk thx

proud mason
cold hamlet
#

Are messages automatically evicted from the cached_messages once they're deleted?

gaunt bane
#

Why
bot.get_command(command)
Gives none
But commands that are in main.py works

gaunt bane
#

Nope commands in cogs gives None

cyan quail
#

can you show an example of it not working

#

seems fine with cogs to me

gaunt bane
#

Wiat

#
    async def Help_command(self,command):
        cmd = self.bot.get_command(command)
        print(cmd)
        if isinstance(cmd,discord.SlashCommand):
            prefix = "/"
        else:
            prefix = self.bot.command_prefix
        embed = discord.Embed(title=f"Viewing {cmd} command", description=f"{prefix}{cmd} : {cmd.description}")
        embed.set_author(name=self.bot.user.name, icon_url=self.bot.user.avatar)```
output: 
None
None
chat
cyan quail
#

slash commands use get_application_command

#

also if it's a slash command, you can use command.mention to have a mention-style output of the command

#

like </example:1009144375709814896>

gaunt bane
#

I'm using it in a custom help command

cyan quail
#

yes that's why im suggesting it

cyan quail
#

you might find it looks better in the embed

gaunt bane
#

Ohk

cyan quail
#

and then users can easily click it to use the command

cold hamlet
gaunt bane
#
cmd = bot.get_application_command(name="link")
print(cmd)

still gives None

cyan quail
cold hamlet
#

Yeah that's true

#

cheers

gaunt bane
#
    async def Help_cog(self,cog):
        cogs = self.bot.get_cog(cog)
        embed = discord.Embed(title=f"Viewing {cogs.__cog_name__} Category" , description=cogs.description)
        command_list = []
        for cmd in cogs.get_commands():
            if isinstance(cmd,discord.SlashCommand):
                prefix = "/"
            else:
                prefix = self.bot.command_prefix
            command_list.append(f"`{prefix}`**{cmd}**: {cmd.description}")
        embed.add_field(name="Commands",value=f"".join([f"{x}\n" for x in command_list]))
        embed.set_author(name=self.bot.user.name,icon_url=self.bot.user.avatar)
        return embed

commands are showing when i call them from cog

real frost
#

sup, how to fetch other defered interaction from others bots like a bump?

#

.rtfm message.interaction

real frost
#

oh i got it

woeful skiff
#

Hello, so i want my bot to delete invites. The first one works (hello) but the second doesn't.

@bot.listen()
async def on_message(message):
    msg_cnt = message.content.lower()
    if "@lucid tinsel" in msg_cnt:
        await message.reply("hello!")
    elif ".gg/" in msg_cnt:
        await message.delete()
        print(msg_cnt)
#

the .gg/ doesnt delete the messages

#

(the bot doesnt lol)

young bone
#

and what are the permissions?

woeful skiff
woeful skiff
woeful skiff
#

oh, sorry. it was discord messing around

#

it's all fine

young bone
#

discord.ext

novel jay
#

Just double checking, i can't make it so you can select more then 1 role per parameter in a slash command, correct?

young bone
novel jay
young bone
#

Im not really sure if this is possible

novel jay
#

Yeah i didn't think so either

proud mason
#

You would need to parse it in your code

#

A better wya would be to send a role select menu

green hinge
#

Why can't I make my Paginator (the buttons of it) persistent like this?
What is the right way to do it?

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

class PaginatorInfoView(Paginator):   
    async def __new__(cls, *args, **kwargs):
        obj = super().__new__(cls)
        await obj.__init__(*args, **kwargs)
        return obj
    
    async def __init__(self, bot: discord.Bot):
        self.bot = bot
        self.pages = await self.update_pages()
        view = await self.generate_view()
        custom_buttons = [
            discord.ext.pages.PaginatorButton("first", label="<<", style=discord.ButtonStyle.primary, custom_id="first_button"),
            discord.ext.pages.PaginatorButton("prev", label="<", style=discord.ButtonStyle.red, custom_id="prev_button"),
            discord.ext.pages.PaginatorButton("page_indicator", style=discord.ButtonStyle.gray, disabled=True, custom_id="page_indicator_button"),
            discord.ext.pages.PaginatorButton("next", label=">", style=discord.ButtonStyle.green, custom_id="next_button"),
            discord.ext.pages.PaginatorButton("last", label=">>", style=discord.ButtonStyle.primary, custom_id="last_button")]
        super().__init__(pages=self.pages, use_default_buttons=False, custom_buttons=custom_buttons, custom_view=view, timeout=None, author_check=False)```
warm spire
#

My try except block isnt working. its in a Cogs.listener on_guild_join. I try to read the audit logs, but if i cant, i want it do something. But when it fails, it just logs the error in the terminal like normal "Ignoring exception...". Any ideas how to activate the except block?

warm spire
#

i see that errors in events go to on_error handler. any way to override this on a case-by-case basis?

#

nevermind^

#

any quick way to see who invited the bot to a server in on_guild_join?

silver moat
warm spire
silver moat
#

unless you want to use OAuth2 and store the user somewhere...

#

which I don't recommend unless this is a very important feature of your bot

warm spire
#

Bet thanks

orchid pebble
#

I have a class that extends discord.Bot and has ivars that I need to access upon interaction with a button, but with the button being its own class, I'm not sure how to do this. Any ideas?

silver moat
orchid pebble
#

how do I resolve a button callback?

cyan quail
#

respond?

orchid pebble
#

maybe?

#

I just want it to do a thing, and not say anything back

cyan quail
#

defer with invisible=True

#

...i think, if it doesn't work then idk use interaction.response.edit_message

proud mason
#

Just do a simple defer

#

interaction.response.defer()

#

That is a valid response for buttons

silent meadow
#

hey, how do I send a mention along with a embed? like together in one single message?

proud mason
fervent cradle
#

I get this error:

discord.errors.ExtensionFailed: Extension 'cogs.commands.Test' raised an error: TypeError: button() got an unexpected keyword argument 'url'

and this is my code:

@discord.ui.button(style=discord.ButtonStyle.link, url="https://example.org", label="Test")

my IDE and the error says that the url argument is an unexpected argument, but the docs say that there is an argument called url

proud mason
#

because url buttons cant have callbacks

fervent cradle
#

oh ok

#

how would I do it then?

proud mason
#

you need to add them using view.add_item

errant craneBOT
#

Here's the link example.

fervent cradle
#

ok thanks

proud mason
#

np

soft girder
#

How fix this problem?

chrome skiff
#

Or it doesent exists anymore

ocean pumice
#

Hey, I was running a bot using pycord for some times and it seems like for a period of time, guild_ids were kinda... broken. Where it was supposed to end with 360, the bot was reading 300. And now, he's reading it correctly again but the problem is that my db is now kinda broken.
What causes that?

proud mason
# soft girder .

Yea you are taking too long to respond. Defer at the start of the code and then send followup

soft girder
proud mason
soft girder
#

Ok thanks 😁

soft girder
cyan quail
# soft girder

wrong method, should be interaction.edit_original_response in this instance

soft girder
#

Ouuu ok

untold terrace
#

hey, just wondering, is it possible to create subgroups in bridge commands? couldn't figure out how to do that

proud mason
#

1st

untold terrace
#

ye, i could do that for the slash variant, but it's not going to work the same way in the ext variant?
thanks anyways

proud mason
#

bridge was made so that it would work the same with slash and prefix

untold terrace
#

say i wanna have command structure such as this:

group1
  -subcmd1
  -subgroup1
    -subcmd2

is it possible to have this structure both in slash and ext? the methods you linked me are from the slash variant. do i understand correctly that if i'll make a subgroup here, it won't be reflected in the ext variant? (i won't be able to type say !group1 subgroup1 subcmd2)
or am i being crazy and if i'll add a subgroup in the BridgeSlashGroup it's actually going to work in the message command magically?

#

sorry if im being stupid or smth

proud mason
#

there is decorator for the groups

#

i forgot bout that

#

stupid me 💀

#

also see if the github example has it

errant craneBOT
#

Here's the bridge commands example.

untold terrace
#

but how to use that decorator to actually make subgroups? i figured how to make regular groups, but still no idea how to implement a structure i provided above

proud mason
#

omg im even more stupid 💀

#

i should really get that sleep man

untold terrace
#

i think its kinda impossible. i looked through ext.commands and there's just nothing on subgroups.

#

but thanks for your help still, and have a good sleep XD

proud mason
#

it should be a relatively simple pr imo

untold terrace
#

yup. thinking about that

proud mason
#

lol would be cool

novel jay
#

What's this?

full basin
#

Member screening

#

If you click that it'll show you what it is

novel jay
#

Ohhh

vapid pumice
#

Curious how to allow multiple selections from slash command options

silver moat
#

definitely clucky tho

vapid pumice
gaunt bane
#
class HelpView(discord.ui.View):
    def __init__(self,bot,*args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.bot = bot
        self.helpembed = HelpEmbed(bot)
        options = [discord.SelectOption(label=info['cog'], description=info['cmds'][:99]) for info in self.helpembed.Help_list()] 
        self.select = (discord.ui.Select(placeholder="Select a option", min_values=1, max_values=1, options=options))
        self.add_item(self.select)
        self.select.callback = self.on_select

    async def on_select(self, interaction: discord.Interaction):
        select = self.select
        cog = select.values[0]
        if cog == "Main Manu":
            embed = await self.helpembed.HelpMain()
        else:
            embed = await self.helpembed.Help_cog(cog)
        await interaction.response.edit_message(embed=embed)
#

how to show selected option in place holder

fervent cradle
#

Whenever someone creates a forum thread in a specific forum, how do I check who created it?

silk spindle
#

hello I always get discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message when I do channel.fetch_message(id) from a very old message

silent meadow
#

why isnt the bot able to ping the role?

I have checked the follwing things: I have the role, The channel perms are correct, The bot has an admin role ✅

#
@discord.slash_command(name ='test1', description="this is a test command :D")
    async def test(self, ctx):
        embed = discord.Embed(title = "Friendly Reminder!", description = "Please do bump this server by using the command : `/bump`")
        await ctx.respond("<@&1083433733857755269>", embed=embed)
#

(please ping for reply)

slate cedar
#

How can i can be staff

young bone
grizzled sentinel
fervent cradle
#

Hi, in my button callback from a button (the message has two buttons) I want to access the other button and change the label. this is how I do it:

                for row in components:
                    if isinstance(row, ActionRow):
                        for button in row.children:
                            if button.custom_id == "no_button":
                                current_label = button.label

                                match = re.search(r'\d+', current_label)
                                number2 = int(match.group())
                                print("nummer 3: " + str(number2))

                                button.label = f"No ({str(number2 - 1)})"
                                print("nummer 4: " + str(number2 - 1))
``` the problem is that my IDE says this in the line `if button.custom_id == "no_button`: `Unresolved attribute reference 'custom_id' for class 'Component'`

and this: `'Component' object attribute 'label' is read-only, 'Component' object has no attribute 'label' ` in this line: `button.label = f"No ({str(number2 - 1)})` 

how can I solve this?
full basin
#

View.children returns a list with the buttons or whatever you have in your view

#

Just index it and change the label

fervent cradle
#

ok, I will try it

cyan quail
slate cedar
cyan quail
proud mason
cyan quail
#

Which is why I suggested the latter

proud mason
#

yea

#

so 1 isnt even a possible solution

cyan quail
#

Well it is if you don't care about the callbacks

#

E.g disabling

#

But otherwise yeah

sick surge
#

how do i edit a button label while using a class view like the docs?

fervent cradle
#

hey im looking for a suggestion, how can i make a modal dialog have like a boolean value for the question ( i wanted to integrate a select menu inside a modal but found that, that it is not supported) for example if the question is something like "Are you homeless?" and i want the users to have like two options to choose from "yes" or "no" , if you can give me any suggestion how can i make this as user friendly as possible i would appreciate it

young bone
fervent cradle
#

i think asking the question and having the user input the value is too problematic

#

when it's a yes or no question

young bone
#

I dont know which Library is supporting it

#

Py-cord is not supporting it

fervent cradle
#

no no, i do understand that discord does not support the menus in modals, but i am asking if you have somewhat of an idea

#

of implementing that

young bone
#

No, sorry

fervent cradle
#

alright tnx for the reply tho gn

young bone
fervent cradle
#

hmmm, actually yes

#

thanks

copper pine
#

Hi, does anyone know how to add descriptions to the arguments of slash commands? I mean not the description of the command itself, but rather the description of the argument.

young bone
torpid wraith
#

Is there a clever way to sanitize a user string input that will eventually be used with Embed.set_image(url=str)? I noticed inputing something simple like "test" will crash the Embed routine.

torpid wraith
#

My leading idea is a regular expression, but I wasn't sure if there was an easier object based approach or something...

cyan quail
#

image urls come in many formats, discord itself doesn't validate anything