#Basic Pycord Help (Quick Questions Only)

1 messages · Page 3 of 1

fervent cradle
#

but how big bots send messages to dm?

silver moat
#

or this off

silver moat
tiny wagon
#

how to ask user for a list of channels from slash command input boxes

errant craneBOT
#

Here's the slash options example.

woeful spindle
#

print("An error occurred with the kick command:" + e) This should print my text with the variable e right?

woeful spindle
#

e is my err

silver moat
#

str(e) then

woeful spindle
#

i have except Exception as e:

woeful spindle
shrewd dome
#

would there be any reason at all for my slash commands to disappear right after I execute one them

shrewd dome
#

seriously?

#

smh.

#

I knew Discord had a few hiccups recently but come on this is a joke

silver moat
#

well try discord PTB or discord Canary

shrewd dome
#

😂

#

I'll just wait till they fix their shit

#

(if they do, probably wont)

#

discord y2k 😭

silver moat
#

Is there an update button?

#

Discord: switch to slash commands
Also Discord: Slash commands don't actually work btw

proud pagoda
#

I fixed it by using a separate bot for development

shrewd dome
#

I just add code when I need to, its just my personal bot

proud pagoda
shrewd dome
#

resetting the bot token fixed it

proud pagoda
#

Huh

shrewd dome
#

fuck you discord

#

kindly.

proud pagoda
#

Are you sure you're not running the bot elsewhere as well?

shrewd dome
#

positive

#

only instance running is the one I have open

proud pagoda
#

Alright

shrewd dome
#

oh well its fixed

#

so i dont really mind

worldly schooner
#

Is there any problem if I put all @bot.event in a cog called Events?

#

for example

proud pagoda
worldly schooner
#

oh alright

#

thanks

proud pagoda
#

Yeah, since bot will not be defined within the cog

proud pagoda
worldly schooner
proud pagoda
worldly schooner
proud pagoda
#

Send the code for it

#

Remove the await self.beppo.process_commands(message)

worldly schooner
#

alr

#

thanks

proud pagoda
#

You're welcome

dim blade
#

Are global commands also available in the bots private chat or only in guild text channels?

full basin
#

They're available in dms too

dim blade
full basin
#

You can make them guilf only

worldly schooner
#

is there a way to generalize commands.CommandError handling?

full basin
worldly schooner
full basin
#

Add a global error handler?

worldly schooner
#

thats what im asking, if this exists, like:

@commandError.error
async def commandError(self, ctx, error):
    if isinstance(error, commands.CommanError):
        await ctx.message.add_reaction("X")
full basin
#

@commands.Cog.listener
async def on_command_error

#

b!rtfm pyc on_command_error

worldly schooner
#

omg I forgot that on_command_error exists

#

thanks joe_pray

silver moat
#

required = True

#

if you already have that then comment out the command, run the bot, uncomment it, and run the bot

worldly schooner
#

whats the ( * ) meaning on:

 aysnc def command(ctx, *, arg)
```Nvm figured out
woeful spindle
#

How do I get str to post the full string instead of one word?

woeful spindle
#

oop ok ty

worldly schooner
#

is there a way to cast a string arg and transform it in a discord.Member type?

silver moat
#

what is the string

worldly schooner
#

he does not give me nothing after the args print

worldly schooner
silver moat
#

so you only want the 347498475031756802 part

worldly schooner
#

yea

silver moat
#

and then you can use bot.fetch_user(id)

#

to get a user object

worldly schooner
#

actually my last objective is get the id

#

i think im taking a hard way

#

i will just need the id so the thing is
im trying to catch the args but the guy can leave it none or just say a string that is not a ping cuz im doing a inventory search:

example:

Error: $inventory 213842 @ZaC#6588 
Success: $inventory @Zac#6588 121030
Success: $inventory 129839184 (bc its going to read the ctx.author)
Success: $inventory
silver moat
#

you can take a discord.Member object with type hinting to be discord.Member

#

it will take ID or name

#

or mention

worldly schooner
#

btw im using this to load the args

#

cuz i will use the split method

silver moat
#
async def command(ctx, member : discord.Member =None, *arg2=None):
  pass
worldly schooner
#

Hmmmmmm

#

alr i will try

#

thanks joe_pray

#

Its not working TohruWeary

silver moat
#

remove the astricks

worldly schooner
#

or dont ping

#

hold i will look for someway to extract only numbers from a string

silver moat
#

then put another one

hushed ledge
#

One message removed from a suspended account.

silver moat
hushed ledge
#

One message removed from a suspended account.

#

One message removed from a suspended account.

silver moat
hushed ledge
#

One message removed from a suspended account.

worldly schooner
worldly schooner
#

oh i did not saw that you have edited

#

sorry

worldly schooner
#

this one was not working either but I found something on stackoverflow about MemberConverter

#

I will try this one and i will tell

full basin
#

Full error

#

Traceback

silver moat
#

b!rtfm BanEntry

dire spadeBOT
# silver moat b!rtfm BanEntry

I couldn't find a documentation with the name banentry! Maybe you used to command wrong? Correct Usage: <prefix>rtfm <docs> [<term>] (eg. b!rtfm py cool)
List of Documentations you can search:
python
pycord
discord.py
yarsaw
nextcord
disnake

silver moat
#

b!rtfm pyc BanEntry

dire spadeBOT
silver moat
#

because users is a BanEntry object

#

please name your variables according to what they actually are

#

BanEntry is not a list of users

marsh moth
#

Completely forgot, how do you edit a aplication response

worldly schooner
# worldly schooner i will just need the id so the thing is im trying to catch the args but the guy ...

@silver moat i got it working now, i spent some hours figuring out a way to catch it, now it catch mentions and ids:

id = ""
symbol = None
if arguments!=None:
    arg=arguments.split()
    if len(arg) > 2:
        raise commands.CommandError
        return
    i=0
    for args in arg:
        if not args.isalpha():
            for s in arg[i]:
                if s.isnumeric(): id += s
                else: id += ""
        else:
            symbol = arg[i]
        if len(arg) == 2 and i==0: i=1
        else: break
auth_id = id
if auth_id == "":
    auth_id = str(ctx.author.id)
#

arguments are the (ctx, *, arguments)

gleaming falcon
#

General Python question.
Say I have a dict:

votes = {
  'For': 1,
  'Against': 2,
  'Abstain': 3
}

I'm using max(votes, key=votes.get) to give me the key associated with the largest value. But I want to exclude 'Abstain' votes from being considered.

I would've thought this would be a lambda function, e.g.

max(scores, key=lambda k, v: v if k != 'Abstain' else 0)

but I can only seem to get the dict keys out of the lambda, so it whines about v.

Is my only course of action filtering votes into a new dict, or is there some logic that I'm missing?

Edit: Ah-hah. Wasn't terribly far from the answer.

max(scores.items(), key=lambda x: x[1] if x[0] != 'Abstain' else 0)
near hollow
#
INFO:discord.client:Cleaning up tasks.
INFO:discord.client:Cleaning up after 15 tasks.

Getting this after my bot does a long function. And the bot crashes all shards

worldly schooner
# gleaming falcon General <:Python:881421088763047946> question. Say I have a dict: ```py votes ...

idk if this can help you but i have a method that basically returns a value in the dict:

def timestamps(tempo):
    options = {
        1: "1h",
        24: "24h",
        7: "7d",
        30: "30d",
        60: "60d",
        90: "90d"
    }
    return options.get(tempo, "?")

so basically timestamps(1) == "1h" and if its not in the dict it returns me "?"
in your case I would do like:

def score(x):
    options = {
        "For": 1,
        "Against": 2,
    }
    return options.get(x, 0)

in other words it will return 0 if the x is not For and Against

abstract raven
#

how do I make a description for the args in a slash command

gleaming falcon
#

@commands.Cog.listener() takes an argument name, which is allegedly the event name.

Wouldn't @commands.Cog.listener('message') annotate any arbitrary method name to behave like on_message()?

Answering own question: The name argument has to be on_message 😬

fervent cradle
#

hey

#

how can i get the guild and guild owner without intents

#

using a for loop

#

like for guild in bot.guilds: print(guild) print(owner)

#

idk how to print the owner tho

#

without intents

#

nvm

fervent cradle
#

How can i give role to member, when member boost server

torpid wharf
#

There is a server booster role built in tho

fervent cradle
torpid wharf
# fervent cradle but i need to add another

then what you can do is, make an on_member_update event and if a member gets the default server booster role you can add another role or do whatever you want to do with it

fervent cradle
#
await ctx.send(f'https://discord.com/channels/{ctx.guild.id}/{ctx.channel.id}')
fervent cradle
#

you are welcome

spiral sail
#

How do you register slash command groups in cogs?

fervent cradle
spiral sail
tropic vortex
#

so umm... what is the name of this

woeful spindle
tropic vortex
#

oh ok, thx

tropic vortex
#

so I'm working on this modal and I've run into a problem.

I want to use ctx.guild but cuz I'm in a callback for the modal, I can't use ctx. How to I work around this?

#

oh wait so interaction is the replacement of ctx

#

ok intresting, problem solved by myself i guess

naive remnant
#

How can I make my bot read what is sent to his dms

full basin
#

on_message event

naive remnant
#

Or a channel

full basin
#

Get the channel and send the content?

#

Dms guild is None so you'd check If guild is none

fervent cradle
golden cairn
#

is there any way tp give extra arguments in a discord.ui.view class?
something like that

class VeryCoolView(ui.View, title: str):
proud pagoda
golden cairn
#
    def __init__(self, text: str):
        self.text = text
    

like thaT ?

proud pagoda
#

So something like this:

class MyView(discord.ui.View):
  def __init__(self, title: str):
    self.title = title
proud pagoda
#

You're welcome

golden cairn
# proud pagoda You're welcome
class SelectMenuSelfRoleView(ui.View):

    def __init__(self, optionsvar: list):
        self.optionvar = optionsvar


    @discord.ui.select(
        placeholder="Rollen auswählen",
        min_values=1,
        options=self.optionvar,
    )

why i am getting NameError: name 'optionvar' is not defined or with the self NameError: name 'self' is not defined error ?

proud pagoda
golden cairn
proud pagoda
proud pagoda
#

You're welcome

proud pagoda
#

Is it possible to make an arg required in slash commands if a specific option is selected without having to do a manual check in the command callback? (Ping on reply)

tardy kindle
#

hihi

#

yea so i came back to bot dev after long time and my bot is in like 75 or msth servers idk and no command is working, like the on_message thing works but no command

silver moat
#

?tag message-content

obtuse juncoBOT
#

As of Pycord Beta 5, Discord API v10 requires message content intent to receive message content. This affects the traditional commands. Not enabling this intent will result in the messages' content, embeds, and components being empty.

You will need to enable the intent on the developer portal, as well as in your code:

intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(intents=intents)

Docs: https://docs.pycord.dev/en/master/api.html#discord.Intents.message_content

silver moat
tardy kindle
#

it can see on message things

#

like supposed @bot it responds but like command doesnt work

silver moat
robust raptor
#

Will I be able to fetch a webhook that was created by another application or will it throw a 403 error?

silver moat
tardy kindle
#

it says command not found what 💀

#

oh wai only the one in cogs doesnt work

#

is there some new way of cog

silver moat
#

kinda of?

tardy kindle
#

oho

#

so the old one wont work?

silver moat
#

so how do you load your cog?

tardy kindle
silver moat
tardy kindle
silver moat
#

the actual loading part

tardy kindle
#

ignore the not miya part i was testing smth 👍

#

it says command not found for the one in cogs

silver moat
#

ok so they have this now:

bot.load_extensions("cogs", recursive = True)
tardy kindle
#

ohhhh

silver moat
#

this will load all the cogs in the /cogs directory

#

but cogs also don't raise errors. to fix this, add store = False

tardy kindle
#

okok

#

lemme see iph this works first

#

are u srue its extensions"s" or just extension

silver moat
#

I mean both exist

tardy kindle
#

one showed error

silver moat
#

b!rtfm pyc bot.load_extensions

dire spadeBOT
silver moat
#

b!rtfm pyc bot.load_extension

silver moat
#

extension then

tardy kindle
#

okie

#

bro 💀

#

unexpeted argument recursive

silver moat
#

did you update pycord?

#

?tag install

obtuse juncoBOT
#
  1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
    python -m pip uninstall discord.py discord -y

2a. Install py-cord
python -m pip install py-cord

2b. Update py-cord
python pip install -U py-cord

Installing other builds:
Note: You need to have git installed. Use !git to find out how to install git.

Updating the module to Alpha (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord

silver moat
#

2b

tardy kindle
#

ok i did

#

pip install -U pycord

#

lemme see now

#

okiee it worked

#

ty

silver moat
#

np

tardy kindle
#

what is up with this 💀

#

like literally only this cog the commands dont work

silver moat
#

what is your file structure and send the code of that cog?

proud pagoda
#

Send the entire cog

silver moat
tardy kindle
proud pagoda
#

Wait isn't it store=false

tardy kindle
#

i didnt set it yet

silver moat
tardy kindle
#

i mean all other cogs are working

#

only this is it some mongo problem

silver moat
#

so no errors were raised?

proud pagoda
#

Do you have an on_ready listener in the cog?

tardy kindle
proud pagoda
#

Is it triggering?

tardy kindle
#

wait no

proud pagoda
#

Add it then and add a print function inside to check whether the cog is even being loaded

tardy kindle
#

no no on ready

#

okay

#

error is leadrboard isnt foun d

#

now ill try to on ready wait

silver moat
#

If it doesn't work, try updating to master branch.
pip install -U git+https://github.com/Pycord-Development/pycord

tardy kindle
#

NOP

#

it isnt loading

tardy kindle
#

but ho wiwll that work

#

its only one cog

silver moat
#

it was a bug

#

they might've fixed it

tardy kindle
#

okie wait

spiral sail
tardy kindle
#

nope

spiral sail
naive remnant
#

How can I create a webhook using pycord is there a guide?

silver moat
silver moat
#

b!rtfm pyc Wehook

silver moat
tardy kindle
#

wait

#

nope

#

it isnt working

#

how annoying

silver moat
#

so all the cogs work except this one, correct?

tardy kindle
#

yes

naive remnant
spiral sail
#

Has anyone got a solution to slash command groups though?

#

SlashCommandGroup isn't registering in my cog

silver moat
spiral sail
#

sigh

#

I applied and got the message intent but can't actually deploy the moderation system I coded cos of this 😓

#

So, in summary, pycord version 2.0.0rc1 works better than 2.0.0

#

Alright goin' with that version for now then

#

Nevermind, the moderation system I coded doesn't work with the older versions of Pycord 😓
Am just gonna have to wait I guess

silver moat
#

just don't use cogs

spiral sail
#

If all my commands were in my main.py file

#

It'd look like chaos

silver moat
#

I didn't say all of them

#

just the SCG

spiral sail
#

SCG?

silver moat
#

Slash Command Groups

#

:)

spiral sail
#

But the commands under those groups will also have to go under my main.py file

silver moat
#

surely not all of your commands are groups, right?

spiral sail
#

well no I separate my commands into cogs

spiral sail
#

I did a lazy dev move by moving all my commands to Bridge

#

And bridge commands do work properly which is good

#

But I do plan on using Slash command groups a lot more, so for now I guess I'll just put it in my main.py file

tiny wagon
silver moat
tiny wagon
naive remnant
#

But can I make the bot create a webhook by himself

tiny wagon
#

like the optional arguement

spiral sail
#
1|rimuru  | Traceback (most recent call last):
1|rimuru  |   File "/averycooldirectory/RIMURU/main.py", line 54, in <module>
1|rimuru  |     from pycord.discord.http import Route
1|rimuru  | ModuleNotFoundError: No module named 'pycord'

Little problem here ^

lone quail
#

I've made a bot with pycord and have another bot on the same ID (made in JDA) and both add slash commands, but only my slash commands are showing up. why is that? (they're both using server-id slash commands)

tiny wagon
silver moat
tiny wagon
proud pagoda
spiral sail
tiny wagon
#

or you cant multihost slash commands?

lone quail
spiral sail
silver moat
spiral sail
#

Thanks for telling me

silver moat
#

you just need the command itself (with options and all) and put pass in the callback

lone quail
#

so would that work in my case?

#

as i can't edit the JDA ones

silver moat
#

idk how JDA works internally

lone quail
#

I'll give it a go

silver moat
#

gl

lone quail
#

otherwise i'll just make another bot account

lone quail
silver moat
#
@slash_command()
async def thingy(ctx):
  pass
lone quail
#

ah, putting pass at the end

tiny wagon
naive remnant
silver moat
#

please show code ty

naive remnant
silver moat
#

yes

naive remnant
#

Wait

naive remnant
silver moat
naive remnant
#

lol

naive remnant
silver moat
naive remnant
#

ooo okayyy

silver moat
#

you can get a discord.TextChannel from ctx.channel

naive remnant
#

tnx it's solved

tiny wagon
#

@silver moat its not appending the list, just printing the first element

oblique sonnet
#

idk why but my slash commands are not registering, I tried to put it in both discord.Bot(debug_guilds=[...]) and in cog commands

tiny wagon
oblique sonnet
#

2.0.0b4 works?

tiny wagon
#

thats too old

#

go 2.0.0rc1

#

or b7

oblique sonnet
#

omk lol i was not active since a long time

silver moat
tiny wagon
#

and whole list can be seen

silver moat
#

what is ctx.guild.text_channels then

tiny wagon
#

general```
silver moat
#

lol

naive remnant
tiny wagon
#

so um

#

what can be the pblm

#

application dont responds then ofc

silver moat
#

wait you're saying it has all these elements and it just doesn't iterate?

silver moat
#

I don't see anything wrong with your code tbh

tiny wagon
silver moat
#

idk, did you spell channel wrong?

tiny wagon
#

sus

oblique sonnet
silver moat
#

How are you still using Permissions v1

tiny wagon
silver moat
#

no, nyu19

tiny wagon
#

hmm, he might be inactive since a month

oblique sonnet
#

Permissions v1 ??

#

it was over 2 months

tiny wagon
tiny wagon
silver moat
#

Pretty sure it's been like half a year

oblique sonnet
silver moat
#

Yeah April 27th

tiny wagon
#

so um, whats going on tbh. Confusion

#
@commands.slash_command(name='info', guild_ids=[934026380092530708])
    async def info(self, ctx):
        options = []
        for channel in ctx.guild.text_channels:
            print(ctx.guild.text_channels)
            print(channel.name)
            options.append(discord.SelectOption(label=str(channel.name), value=channel.id))

        view = View()
        view.add_item(Control_OCR_Channels(options))
        await ctx.respond(content='done', view=view)
silver moat
#

wait value takes a string you gave an int

oblique sonnet
#

was trying to learn djs but the docs.. 💀 those are real crappy

tiny wagon
#

ok so code freezes at append statement

silver moat
tiny wagon
#

brrrrrrr

#

was this b4 too?

silver moat
#

idk how anything works. I made a 3.3k line long dictionary earlier today

silver moat
tiny wagon
#

ok fine lmao its working now

#

but why it didnt log any error in console

silver moat
fervent cradle
#

i'want to make auto link delete, but on_message doesn't work

@discord.Cog.listener()
async def on_message(self, message):
    bad_words = ["https://discord.gg", "http://disord.gg", "discord.gg"]
    for word in bad_words:
        if word in message.content:
             await message.channel.purge(limit=1)```
#

and i've got message_content intent

silver moat
#

there is message intent which makes you receive on_message events and message_content intent which makes you receive message content

fervent cradle
#

i've got message_content event

#

and it doesn't work

marsh moth
silver moat
#

also check if cog loads or not

fervent cradle
fervent cradle
naive remnant
#

I tried to delete every webhook after creating it using the method delete()
But it doesn't work

fervent cradle
fervent cradle
naive remnant
#

No u can use on_message

#

Like

#

If message.content == "http:":

fervent cradle
#

but user can send not url, user can send text with link

naive remnant
#

Like this https:

fervent cradle
naive remnant
#

Yeah just add in your

#

Bad words list

#

The characters

cinder pilot
naive remnant
#

Used

#

Like | and `

fervent cradle
cinder pilot
fervent cradle
cinder pilot
#

Put await message.delete() and try

fervent cradle
cinder pilot
#

I have a similar command and it works for me

#

Try reinviting the bot

fervent cradle
naive remnant
cinder pilot
#

Does the bot have permission to delete messages?

naive remnant
fervent cradle
cinder pilot
#

What's your pycord version?

fervent cradle
cinder pilot
#

Hm

#

I'll run the command and check

fervent cradle
#

ok

lost lodge
#

hey how can i clear messages of a specific member?

naive remnant
#

Using on_message

lost lodge
#

and with await channel.purge()

naive remnant
#

Yes

cinder pilot
#

await message.delete()

#

Maybe something is wrong with your cog

#

Or maybe the bot doesn't have access to the channel

fervent cradle
#

this thing doesn't work without cogs and bot has admin access

cinder pilot
random finch
#

Can someone help me with some permission issues? i have a bot that should kick member with a specific role, but it keeps telling me that it does not have permission to do that. i gave it all the permissions in the world and still says the same thing

silver moat
random finch
silver moat
#

are they the server owner?

random finch
#

the bot ? or who ?

fervent cradle
cinder pilot
fervent cradle
# cinder pilot Send code of your cog
import discord
from discord.ui import *
from core import bd, ui
from loguru import logger


b = bd.HFD
logger.add("./main.log", rotation="500 MB")
bt = b.open(self=b)


class Bot(discord.Bot):
    def __init__(self):
        super().__init__(intents=discord.Intents.all(), status=discord.Status.idle, activity = discord.Activity(type=discord.ActivityType.playing, name = 'пальчики бекона'))
        intents = discord.Intents.all()
        intents.message_content = True
        intents.messages = True
        intents.dm_messages = True
        intents.members = True


        self.persistent_views_added = False
    
    async def on_ready(self):
        if not self.persistent_views_added:
            self.add_view(view=ui.PersistentView())
            self.add_view(view=ui.RolesUs())
            self.add_view(view=ui.RolesCst())
            self.add_view(view=ui.RolesBot())
            self.persistent_views_added = True

        print(f"Logged cog as {self.user} (ID: {self.user.id})")
        print("------")

bot = Bot()

cogs_list = [
    'events',
    'mod',
    'warns',
    'admin',
    'ctm_roles',
    'proles'
]

for cog in cogs_list:
    bot.load_extension(f'cogs.{cog}')


bot.run('.GD')
#--------------------------------------------------------------#```
#

but on_member_join work

cinder pilot
fervent cradle
#
from datetime import timedelta
import discord
from loguru import logger


ban_link = ["https://discord.gg"]

class Events(discord.Cog):

    def __init__(self, bot):
        self.bot = bot
    
    @discord.Cog.listener()
    async def on_message(self, message):
        bad_words = ["https://discord.gg", "http://disord.gg", "discord.gg"]
        for word in bad_words:
            if word in message.content:
                await message.delete()
    
    @discord.Cog.listener()
    async def on_member_join(self, member):
        age = member.joined_at - member.created_at
        if age.days < 1:
            until = timedelta(hours=12) + member.joined_at
            await member.timeout(
                until, reason=f"АвтоМод: Недавно созданный аккаунт ({age.days} дней)"
            )

            await member.send(
                    f""
                )
        else:
            roleJoin = member.guild.get_role(863696255224643605)
            await member.add_roles(roleJoin, reason=f'{member} (ID: {member.id}) зашёл на сервер')
    

    @discord.Cog.listener()
    async def on_member_remove(self, member):
        try:
            await member.send('')
        except:
            print(f'{member} (ID: {member.id}) покинул сервер и не получил сообщение')

    @discord.Cog.listener()
    async def on_message(self, message):
        if message.content.startswith('@loud glade'):
            
            await message.channel.send('Привет! Я мульти бот для сервера **HFD**. Мой префикс `/`')     
        else:
            pass
    
    

def setup(bot):
    bot.add_cog(Events(bot))```
cinder pilot
#

I think it's because you have two on_message listeners

fervent cradle
cinder pilot
#

Probably that's why

fervent cradle
#

but 2 another work

#

hm

cinder pilot
#

try doing something like

@discord.Cog.listener('on_message')
async def on_invite_link(self, message):

fervent cradle
#

oh, thank you very much

cinder pilot
#

It works?

fervent cradle
#

yes

cinder pilot
#

welcome :)

naive remnant
#

How do I get the username + avatar of who used the slash command

cinder pilot
naive remnant
iron halo
#

when i do py await ctx.respond(embed=embed) it sometimes says ```
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

is this like a bug or something i would have done wrong
#

its not always just sometimes so i dont think ive done smoething wrong

iron halo
#

yea

gleaming falcon
#

Can slash command permissions be applied to command group children, or just the parent?

gleaming falcon
#

Darn. Understood -- and actually I see @tiny wagon mentioned this a week or two ago. Thank you for confirming

silver moat
#

yw

naive remnant
#

Option in my slash_comand are not showing, I did everything correctly

silver moat
naive remnant
#

Wt is that

silver moat
#
# this is a comment
naive remnant
#

Yes I know this

silver moat
#

just comment the slash command

naive remnant
#

Tnx working

naive remnant
rare ice
dire spadeBOT
rare ice
#

b!rtfm pyc discord.Member.display_avatar

dire spadeBOT
rare ice
naive remnant
rare ice
round aspen
#

is it possible to join a stage channel as a speaker w a bot?

rare ice
#

b!rtfm pyc StageChannel

round aspen
#

it just connects

silver moat
#

It doesn't seem like bots can become speakers

round aspen
#

pain.

hallow oriole
#

Hey 👋 One little question:
How can I import a View from another file into my file? Or is that even possible?

Example: I have command.py with a slash command. When the command is executed, the bot should respond with the class MyView, which is written down in views.py. How can I use the class MyView from views.py in the command.py file? Because currently, if I try to import the MyView Class into the command.py file, all commands from the command.py file disappear on discord (I'm using Cogs btw).

fervent cradle
hallow oriole
#

Sure, sec...

cyan quail
round aspen
cyan quail
#

i think it depends on the bot's perms

hallow oriole
round aspen
#

i see

cyan quail
#

at least through the UI, when i moved a speaking music bot into the stage it was automatically a speaker because it was considered a stage mod

round aspen
#

ah ight ill try that

final fractal
#

what is the ctx.message.author for slash commands?

cyan quail
restive harbor
#

Can i still use command groups when i want to use bridge commands?

fervent cradle
#

Is there a example for models in pycord?

errant craneBOT
#

Here's the modal dialogs example.

silver moat
#

^ @fervent cradle

fervent cradle
#

Thanks

near hollow
#

So the Option(Discord.role) displays all of discord roles in the server. Would it be possible to get the same select options with a list of role ids?

dreamy raft
#

internal message cache is not meant for storing large amounts of messages right? It seems like when I delete a message that is cached, from a very long time ago, it tries to retrieve that message from cache as a blocking call, so the bot doesn't respond to anything for like 10 seconds until it finds that message and sends the log

dawn berry
#

is it possible to set a default embed color so that I don't have to set it all the time?

amber shale
#
        if isinstance(ctx, discord.ApplicationContext):
            await ctx.respond("Pong!")
        elif isinstance(ctx, commands.Context):
            await ctx.send("Pong!")```
#

is this the correct way to reply in a bridge command?

sly oak
#

Does this import exist?

graceful nebula
naive remnant
young bone
copper dew
wicked helm
#

I'm trying to make a / command that brings up a set of pages you can cycle through with buttons.. But I get this errors:

TypeError: expected Item not <class 'src.button_views.server_button_view.ServerButtonView'>

Code:

class ServerButtonView(View):
    """
    Server Button View
    """

    def __init__(self, pages: list, user: Optional[discord.Member] = None):
        super().__init__(self)
        self.current_page: int = 0
        self.pages = pages
        self.user = user
        self.length: int = len(self.pages) -1
        self.children[0].disabled = True    
    @commands.has_permissions(administrator=True)
    @commands.slash_command(name = "server-setup", description="Used to set up the server, adding it to the DB.")
    async def server_setup(self, interaction:discord.Interaction):
        """
        Sets up the server!
        """
        pages = [
            discord.Embed(title = "page 1/5", color = discord.Color.blue()),
            discord.Embed(title = "page 2/5", color = discord.Color.blue()),
            discord.Embed(title = "page 3/5", color = discord.Color.blue()),
            discord.Embed(title = "page 4/5", color = discord.Color.blue()),
            discord.Embed(title = "page 5/5", color = discord.Color.blue())
        ]

        await interaction.response.send_message(embeds = pages[0] if isinstance(pages[0], list) else [pages[0]],
                                                    view = ServerButtonView(pages, interaction.user))

I followed a YT tutorial - but I may have done something wrong

sly oak
#

sorry my english bad

naive remnant
#

Not like that @sly oak

#

Just create a class

copper dew
# sly oak (

more than likely you'll want to create a class

#

it's on the docs somewhere

sly oak
#

0-0

sly oak
#

@naive remnant@copper dew

naive remnant
#

?tag guide

obtuse juncoBOT
naive remnant
fervent cradle
#
Ignoring exception in on_application_command_error
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 127, in wrapped
    ret = await coro(arg)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 877, in _invoke
    await self.callback(self.cog, ctx, **kwargs)
  File "d:\Code\t2e-alpha\cogs\user.py", line 67, in stats
    await ctx.defer(ephemeral=True)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 556, in defer
    await self._locked_response(
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 956, in _locked_response
    await coro
  File "C:\Users\User\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
``` how could ctx be an unknown interaction??? its only happens after some messages
fervent cradle
iron halo
#

i keep getting this error but i dont know where in my code it is coming from ```Traceback (most recent call last):
File "bot.py", line 1561, in <module>
bot.run(token)
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/client.py", line 715, in run
return future.result()
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/client.py", line 694, in runner
await self.start(*args, **kwargs)
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/client.py", line 658, in start
await self.connect(reconnect=reconnect)
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/client.py", line 553, in connect
await self.ws.poll_event()
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/gateway.py", line 589, in poll_event
await self.received_message(msg.data)
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/gateway.py", line 539, in received_message
func(data)
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/state.py", line 635, in parse_auto_moderation_action_execution
event = AutoModActionExecutionEvent(self, data)
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/raw_models.py", line 462, in init
self.content: str = data["content"]
KeyError: 'content'

fervent cradle
#

and some other operations

fallen cove
#

is there a list of all the listeners in pycord?

fervent cradle
grizzled sentinel
# fervent cradle sends an sql query and then format it into embed

If your code can sometimes take longer than 3 seconds to respond you need to defer the response. Discord only allows 3 seconds for your bot to respond, sometimes SQL can be slow so by adding ctx.defer() to the beginning of your command callback discord will allow you up to 15 min.

fervent cradle
#

its not working

#

i do the defer thing, it throws up the error

cyan quail
#

code?

cyan quail
errant craneBOT
cyan quail
#

we should really have incremental 2.0.x releases for major bugs

fervent cradle
# grizzled sentinel Please elaborate.

i want you to do a certain thing in 2 channels. Now how can I make it so that a selection menu appears for example kanal1 and kanal2, if you select kanal1 a message will be sent to kanal1

grizzled sentinel
#

So in the option there will only be 2 options. You could get the channel names and pass them to choices=["name1", "name2"] in the option

fervent cradle
fervent cradle
fervent cradle
grizzled sentinel
fervent cradle
grizzled sentinel
#

choices is an argument for Option
discord.Option(choices=["1", "2",])

cyan quail
grizzled sentinel
#

95% of the time the defer should be the first thing you call in the command callback

cyan quail
#

also you're responding at the top without stopping the command

#

so even if you do something wrong it'll still try to continue

#

...and that isinstance setup at the top is a complete mess, just make the option type discord.Member

fervent cradle
grizzled sentinel
#

what does your command callback look like?

fervent cradle
full basin
grizzled sentinel
#

When specifying the option like that the first argument should be the name of the argument.

#

Than you need to have the argument stated after ctx

cyan quail
#

i think he want's to convert the channel name to a channel object

fervent cradle
#

Noo 😣

storm geode
#

with the commands.cooldown is it possible to have users have a 60s delay but if they have a role its reduced to 30s?

fervent cradle
cyan quail
#

ok

#

so you take channel 1

#

convert it to the channel object

#

then await channel.send

cyan quail
pallid trench
#

theres dynamic cooldowns

#

though i have no idea how those work

cyan quail
#

dynamic cooldown is completely automatic

fervent cradle
# cyan quail convert it to the channel object

So

@bot.slash_command()
@option(choices=["Channel1", "Channel2"])
async def choice_test(ctx):
    channel = bot.get_channel(939551193145950258)
    Channel1: channel
    await Channel1.send("skasl")

?

cyan quail
#

idk how it works either but it's not really what you'd think

fervent cradle
near hollow
pallid trench
iron halo
#
async def info(ctx: discord.ApplicationContext, name: Union[discord.Member, str]):

TypeError: Invalid usage of typing.Union am i being stupid or is this not how it's used in the example

fervent cradle
cyan quail
grizzled sentinel
pallid trench
fervent cradle
#

Okay

cyan quail
#

if you just pass in discord.Member it lets you search members or input a member ID

grizzled sentinel
#
@option(
    "channel",
    description="Select a channel",)
async def select_channel(
    ctx: discord.ApplicationContext,
    channel: Union[discord.TextChannel, discord.VoiceChannel],
):
cyan quail
#

im pretty sure union would break there too? you have to input the separate channel_types kwarg

fervent cradle
cyan quail
#

or maybe it works idk, options have gone through a lot

iron halo
#

im trying to do either member or a name or something i have as a variable not an id

fervent cradle
#

is that right?

grizzled sentinel
#

that ist the code you should use its an example of what you have to do. notice the channel arg

cyan quail
#

you'd have to use str then, discord only supports a single type at a time

pallid trench
fervent cradle
cyan quail
#

though i think you could use MemberConverter but i haven't experimented with it myself

grizzled sentinel
cyan quail
#

this is painful

iron halo
#

ill have to do two options and have neither required then

fervent cradle
pallid trench
#

you will also have to provide the id as a string since the ids are too long for int type

grizzled sentinel
fervent cradle
#

Anyway I'll just leave it thanks anyway notlikethis

fervent cradle
#
    async def idee(ctx, idee: Option(str, "Give your idea on.")):
  File "C:\Program Files\Python310\lib\optparse.py", line 570, in __init__
    self._set_opt_strings(opts)
  File "C:\Program Files\Python310\lib\optparse.py", line 594, in _set_opt_strings
    if len(opt) < 2:
TypeError: object of type 'type' has no len()

Why is that not working ? Huhhhhh ??? ha

@bot.slash_command()
async def idee(ctx, idee: Option(str, "Give your idea on.")):
#

Option(str, "Give your idea on.") is not working

amber shale
#

is there any way to get both application and text commands error with one event handler?

full basin
fervent cradle
amber shale
#

ok

full basin
#

And that won't even work if you select channel2

fervent cradle
plucky anchor
#

Would there be a way to stop the paginator from within a custom view?

full basin
#

You can paginator.stop iirc?

vital blade
#

1st: create your embed
example:

embed = discord.Embed(color=int("hex code", 10), title="embed title", description="embed description")
embed.set_image(url=image url)
embed.set_thumbnail(url=thumbnail url)
embed.set_footer(text="embed footer")
embed.set_author(name="embed author")
embed.add_field(name="a field", value="embed field")

then you can send using send thing await ctx.send whatever then inside the () put embed=embed

amber shale
#

is it ok to shutdown my bot using exit()?

#

is there any better way?

#

color = discord.Color.green()

vital blade
#

yea

#

for default green

amber shale
#

discord.Color.from_rgb()

vital blade
#

if u want a custom color u can find a hex and replace the hex code thing with the hex code

amber shale
#

might want to put emb inside that def (i dont know about other part)

#

it should work

#

oh sorry

#

ok

fervent cradle
#

How do I get a modal to close once submited

fervent cradle
fervent cradle
#

View is not persistent. Items need to have a custom_id set and View must have no timeout

client.add_view(LoginView(ctx=discord.ApplicationContext))

#

😟

#

also how do i make them not have a timeout

unkempt talon
fervent cradle
# fervent cradle also how do i make them not have a timeout
class LoginView(discord.ui.View):
    def __init__(self, ctx):
        super().__init__()
        self.value = None
    
        AuthLink = discord.ui.Button(
          label="Fun",
          style=discord.ButtonStyle.gray,
          emoji="funny emoji here",
          url="https://rebrand.ly/"
        )
        self.add_item(AuthLink)
      
        SubmitButton = discord.ui.Button(
          label="Submit",
          style=discord.ButtonStyle.green,
          emoji="🔒",
          custom_id="Submit"
        )
        self.add_item(SubmitButton)```
unkempt talon
near hollow
#

Great !

fervent cradle
#

i keep getting ValueError: View is not persistent. Items need to have a custom_id set and View must have no timeout

#

for
client.add_view(LoginView(ctx=discord.ApplicationContext))

near hollow
fervent cradle
#

i know

#

oh wait

#

timeout=None

#

im stupid

near hollow
#

WIll pages.Page automatically create a new page if I reach the max amount of fields in a embed?

near hollow
#

Hmm alright thanks

plucky anchor
#

My paginator's custom buttons aren't working, it just says this interaction failed

#

I can send my code in about 20 minutes

sly oak
#

what is the 4th argument that can be given?

proud pagoda
#

Is it possible to use converters with slash commands?

#

Basically what I want to do is parse a str argument using a converter and remove some unnecessary text using a converter

silver moat
fervent cradle
#
Ignoring exception in on_voice_state_update
Traceback (most recent call last):
  File "", line 382, in _run_event
    await coro(*args, **kwargs)
  File "", line 154, in on_voice_state_update
    if member in channel:
TypeError: argument of type 'VoiceChannel' is not iterable

@bot.event
async def on_voice_state_update(member, before, after):
    channel = bot.get_channel(1002189083927396412)
    if member in channel:
        kanaL = bot.get_channel(1002189165380763689)
        await kanaL.send(f"tst") 

why is that not working?

proud pagoda
sly oak
proud pagoda
fervent cradle
proud pagoda
#

You're welcome

silver moat
sly oak
silver moat
restive harbor
#

My slash command from my bridge command disappears after I use it once. It works the one time I can use it. What could be the problem?

sly oak
silver moat
sly oak
#

How can I do this, I have been trying for hours

#

In help

silver moat
#

the information here will probably be suffice

plucky anchor
#

Hey my paginator isnt working when I use await paginator.edit(msg, suppress=True)

#

Anyone know why that might not be working? I can't switch pages

plucky anchor
#

alr one sec

#
games[f"{ctx.author.id}{player.id}"] = False
page_buttons = [
    pages.PaginatorButton(
        "first", emoji="⏪", style=discord.ButtonStyle.green
    ),
    pages.PaginatorButton("prev", emoji="⬅", style=discord.ButtonStyle.green),
    pages.PaginatorButton(
        "page_indicator", style=discord.ButtonStyle.gray, disabled=True
    ),
    pages.PaginatorButton("next", emoji="➡", style=discord.ButtonStyle.green),
    pages.PaginatorButton("last", emoji="⏩", style=discord.ButtonStyle.green),
]
if turn == 1:
    person = ctx.author
    otherperson = player
    while len(p1hand) < 3:
        p1hand.append(random.choice(p1cards))
    hand = p1hand
else:
    person = player
    otherperson = ctx.author
    while len(p2hand) < 3:
        p2hand.append(random.choice(p2cards))
    hand = p2hand
await thread.send(f"Make your move {person.mention}!")
mainmsg = await thread.send("Loading....")
cardpages = []
for card in hand:
    origcard = list(carddict.keys())[list(carddict.values()).index(card[0])] + f"-{card[1]}"
    cardobj = card[0]
    rarity = int(card[1])
    cardcost = cardobj["powers"]["cost"] * round(rarity/2) if round(rarity/2) != 0 else cardobj["powers"]["cost"]
    carddmg = cardobj["powers"]["dmg"] * rarity
    filename = f"{cardobj['name']}-{rarity}-{random.randint(0, 10)}"
    cardimg = discord.File(f"cardoutput/{origcard}.png", filename=f"{filename}.png")
    view = discord.ui.View()
    view.add_item(PlayCardButton(person, otherperson, cardobj))
    cardpages.append(pages.Page(content="What will you play?", files=[cardimg], custom_view=view))
paginator = pages.Paginator(
    pages=cardpages,
    show_disabled=True,
    show_indicator=True,
    use_default_buttons=False,
    custom_buttons=page_buttons,
    loop_pages=True
)
paginator.user = person
mainmsg = await paginator.edit(mainmsg, suppress=True)
playedcard = None
while not paginator.is_finished():
    if games[f"{ctx.author.id}{player.id}"] == True:
        playedcard = cardpages[paginator.current_page].custom_view.cardobj
        print('stopped idiot')
        paginator.stop()
    await asyncio.sleep(0.1)
#

it's all in a command, so ignore the indentation

#
games = {}
class PlayCardButton(discord.ui.Button):
    def __init__(self, user, otheruser, cardobj):
        self.user = user
        self.user2 = otheruser
        self.cardobj = cardobj
        super().__init__(label="Select")
    async def callback(self, interaction: discord.Interaction):
        if interaction.user != self.user:
            return
        games[f"{self.user.id}{self.user2.id}"] = True
        msg = await interaction.response.send_message("Great choice!")
        await asyncio.sleep(5)
        await msg.delete()
#

Then the custom button I have

#

but yeah, the paginator isn't working, I can't change pages or anything

silver moat
#

you should use paginator.send

plucky anchor
#

Yeah but it needs ctx, and I'm using a slash command, meaning it would have a ctx type of ApplicationContext I think

#

But I'll try

silver moat
plucky anchor
#

Here's the thing

#

I already responded, and I'm trying to send it in a thread

silver moat
#

it sends as a followup

plucky anchor
#

Wait really?

silver moat
#

yes

plucky anchor
#

Application Command raised an exception: InteractionResponded: This interaction has already been responded to before

#

I'm using await paginator.respond(ctx.interaction, target=thread)

silver moat
#

why is this being sent in a thread again?

plucky anchor
#

So what I'm doing is I don't want to clog up the commands channel with text from my game, so I'm making a thread that contains all the cards played

#

Pretty much I don't want to clog up a channel, so I'm using a thread

#

Any thoughts?

cyan quail
plucky anchor
#

I might be misunderstanding, but doesn't "send" require a prefix command context? And not a ApplicationContext?

cyan quail
#

hmmm true... but if im not mistaken there's a util to create a context from a message? i wonder if i can find it

plucky anchor
#

Oh thank you so much!

#

Nope

#

I'm using discord.Bot, should I switch to commands.Bot?

cyan quail
#

ah.. if you want i guess

#

but idk paginator.respond should be using followup anyway

#

what version are you on?

plucky anchor
#

Still doesnt seem to work

#

how do I check?

cyan quail
#

print discord.__version__

plucky anchor
errant craneBOT
#

discord/ext/pages/pagination.py lines 1060 to 1070

if isinstance(interaction, discord.Interaction):
    self.user = interaction.user

    if target:
        await interaction.response.send_message(target_message, ephemeral=ephemeral)
        msg = await target.send(
            content=page_content.content,
            embeds=page_content.embeds,
            files=page_content.files,
            view=self,
        )```
plucky anchor
#

should I install from git?

cyan quail
#

oh so because they're specifying target

silver moat
#

setting a target makes it respond with a message

cyan quail
#

and target doesn't check for is_done

plucky anchor
#

Did I just find a bug? lol

#

if so, should I edit pycord manually?

cyan quail
#

maybe check interaction.response.is_done() further up and change the function based on that, which would avoid cluttering this section with more if/elses

plucky anchor
#

??

sly oak
#

Why do I always get 0 when using this

silver moat
#

you should get 0 if you didn't enable members intent

sly oak
cyan quail
#

fetch_guild doesn't return members anyway

plucky anchor
sly oak
silver moat
#

get_guild

cyan quail
#

use get_guild

plucky anchor
#

I changed line 1050's if to
if target and not interaction.response.is_done():

silver moat
#

and enable guild intents as well if you haven't already

sly oak
silver moat
cyan quail
#

not awaited

silver moat
#

it's not a coro

sly oak
#

thx very much

cyan quail
#

because then target isn't used at all

plucky anchor
#

oh lol

errant craneBOT
#

discord/ext/pages/pagination.py line 1050

)```
cyan quail
#

2.0 is probably a bit different from master

silver moat
#

true

plucky anchor
#

should I use the master branch?

cyan quail
#

a bit messy but what about this?

method = interaction.followup.send if interaction.response.is_done() else interaction.response.send_message
if target:
    await method(target_message, ephemeral=ephemeral)
    ...```
plucky anchor
#

trying

daring tendon
#

how do i get all the channel names of a specific guild

cyan quail
#

guild.channels

#

or i guess [c.name for c in guild.channels]

plucky anchor
#

nope, "this interaction has already been responded to before"

cyan quail
#

ok but HOW

daring tendon
#

alr thx

silver moat
#

probably use try-except then

cyan quail
#

i guess

silver moat
#

it's how appctx.respond handles that

#

if the if-else fails

plucky anchor
#

OH IK THE PROBLEM, me being dumb and not adding await method(target_message, ephemeral=ephemeral)

cyan quail
#

oops

#

make sure that's replacing the old line btw

plucky anchor
#

yep, fixed! Thanks so much

cyan quail
#

ey nice

silver moat
cyan quail
#

yeah, i'll go eat first

#

and also the implementation kinda sucks because of the rest of that block

plucky anchor
#

it's official, I found a bug lol

cyan quail
#

i guess i'll refine it later

plucky anchor
#

One more question, I don't want it to send a target_message, but it needs to send a string, what should i do?

#

shouldn't target_message be optional?

#

as in the paginator.respond target_message

#

the one that defaults to "Paginator Sent!" or something

#

changed it to this for now

#

nope that doesnt work

silver moat
#

None?

daring tendon
#

How do I set the permissions of an already existing channel

silver moat
daring tendon
#

thx

cyan quail
plucky anchor
#

True, but I already responded, so I don't want to respond again

#

I want it to ONLY send a message to the target, and not to the interaction's channel

#

Better?

#

*not interaction.response.is_done():

fervent cradle
#

guys I'm having a super weird issue that I've seen happen to more. trying to self.client.get_guild or self.client.get_channel returns None no matter what

fervent cradle
silver moat
#

in your code

fervent cradle
#

intents = discord.Intents.all()
I think so.

silver moat
#

what's the actual bot instance

fervent cradle
cyan quail
#

version?

#

and what happens if you print self.client.guilds

fervent cradle
#

I'll try to print self.client.guilds 1s

cyan quail
#

pycord version

#

get by printing discord.__version__

amber shale
#

why is error not showing up in terminal?

cyan quail
#

for what

amber shale
#

while using cog

cyan quail
#

loading cogs?

#

in load_extension, add store=False

silver moat
#

store = False, error will show up

fervent cradle
cyan quail
#

will be fixed in 2.1 i think

amber shale
#

ok

fervent cradle
# cyan quail loading cogs?

[<Guild id=894902529039687720 name='Moonball Network' shard_id=0 chunked=True member_count=238>, <Guild id=951055432833695764 name='Bot Emojis' shard_id=0 chunked=True member_count=10>, <Guild id=984859985534136350 name='Bot Emojis' shard_id=0 chunked=True member_count=4>]

cyan quail
#

did you convert your IDs to int before using get_guild/get_channel

amber shale
#

to me?

cyan quail
#

no raj

amber shale
#

ok

fervent cradle
#

await self.client.get_guild(int(guild_id)).get_channel(int(general_channel)).send(f"Hey {user.mention}! Couldn't DM you your reminder.", embed=r_embed)

silver moat
#

huh?

fervent cradle
#

i meant, i added int() to them now

#

didnt solve the issue

#

wait, its prob running before the bot ready's up

silver moat
#

that would be the reason

fervent cradle
#

my 2nd issue

     @check_reminders.before_loop
     @check_for_birthday.before_loop
     @check_giveaway.before_loop
     async def before_my_task(self):
         await self.wait_until_ready()  # Wait until the bot logs in

functions don't even run when i do this

#

the 3 functions

cyan quail
#

yeah it has to be after on_ready

fervent cradle
#

yep, but then when I try to do this it stops the functions from running entirely

cyan quail
#

can you use decorators like that to assign the same coro to several tasks? im not sure if that works

#

also should be self.client.wait_until_ready

fervent cradle
cyan quail
fervent cradle
cyan quail
#

if you're doing it in a cog, it would be self.client or self.bot, whatever your bot object is

fervent cradle
#

thanks a lot! yep

cyan quail
#

allgood

celest vessel
#

Hey, I'm trying to write a function that enables users to edit one of my bot's messages. I'm using a MessageCommand and I would like some kind of check that the message from which the command has been used is from the bot.

  1. Should I use discord.MessageCommand.checks for that?
  2. If so, I dont get how to retrieve the message author's ID within the callable. I tried with some of the discord.ApplicationContext properties but either the message object was None, or the id wasn't the author's
cyan quail
#

uhh can you explain a bit more

amber shale
#

is there any way to get list of banned members?

silver moat
#

b!rtfm pyc guild.ban

celest vessel
# celest vessel Hey, I'm trying to write a function that enables users to edit one of my bot's m...

Say I used my bot to send a message with another command I wrote, I want the bot to edit its own message, so I would want to use a MessageCommand on that message. But that command would only work if the bot is the author of that message (since the bot can't edit another user's message). So I'm trying to understand where I should check that and if discord.MessageCommand.checks is a correct way to do that

cyan quail
#

i'd say at the start of the command, just check message.author == ctx.me

#

ctx.me will always be the bot's member object

silver moat
#

or ClientUser

#

if in DMs

cyan quail
#

you could create your own check but it's not really necessary

celest vessel
#

Okok! Also, it's not really possible to only show the command in the UI if this condition is met is it?

silver moat
cyan quail
#

no, you can only filter it in the UI by user/channel via the integrations menu

celest vessel
#

Thanks a lot!

cyan quail
#

allgood

rough shuttle
#

my issue my bot is like registering a wrong embed

cyan quail
#

elaborate?

rough shuttle
#

this is my code

#

but this is the output

cyan quail
#

doesn't include slash commands?

rough shuttle
#

like the help command is broken or smth idk

cyan quail
#

i wonder

silver moat
#

description is Embed.Empty by default if I'm not mistaken

rough shuttle
#

ok so?

cyan quail
#

bridge commands don't have their own type do they...?

silver moat
#

oh wait that's the wrong description I'm stupid

silver moat
cyan quail
#

hmm

#

i think both walk_commands and walk_application_commands would straight up ignore them then

#

lemme check

rough shuttle
#

ok hmmm should i add a field for a command without a for loop

cyan quail
#

hm nope they do seem to include bridge

cyan quail
# rough shuttle

remove the line checking if not description... and prefill the add_field description with another value instead

rough shuttle
#

ok

#

lemme see

rough shuttle
#

got another help error Ignoring exception in on_connect Traceback (most recent call last): File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 382, in _run_event await coro(*args, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1040, in on_connect await self.sync_commands() File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 647, in sync_commands registered_guild_commands[guild_id] = await self.register_commands( File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 476, in register_commands prefetched_commands = await self.http.get_guild_commands(self.user.id, guild_id) File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 353, in request raise Forbidden(response, data) discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access

lofty falcon
#

Hey, I am migrating my bot from emoji reactions to buttons... the only problem is I am too dumb to figure out how to await a button click in the main program, and then run other code. I know I can do it in a callback, the only problem is, it is horrible long...
I would rather just pass the list and let them handle everything.

In short, here is the working code, but I want to await it in the register function.

async def npc_reaction_message(msg, embed, buttonlist):
    view=View()
    i = 0
    res = []
    for button in buttonlist:
        thisbutton = Button(label=button, style=discord.ButtonStyle.secondary, custom_id=f'btn_{i}')
        print(thisbutton)
        res.append(thisbutton)
        view.add_item(thisbutton)
        i += 1
    await msg.send(embed=embed,view=view)
    return res

async def on_interaction(interaction: discord.Interaction):
    await interaction.response.send_message(f"Button: {interaction.data['custom_id']}\npressed by: {interaction.user}")
    #I dont want to code it here, I want to wait for the button click in #register

#OnCommand
@bot.command()
async def register(msg):
    buttonlist = ["YES", "NO"]
    embed=discord.Embed(title="**Welcome to the Adventurer's Guild!**", description="**Marie & Anne**: Do you perhaps want to go on an **Adventure**?", color=0xfbe8d2)
    gotback = await npc_reaction_message(msg, embed, buttonlist)
    for btn in gotback:
        btn.callback=on_interaction
    #wait here for the button click and do something

bot.run(token)

I would appreciate it, if someone knows the answer, discord-components does not work for me. I am using discord.py and pycord.

worldly schooner
#

wtf is happening

#

nvm figured out that i had a function named users...
and i was trying to reach a object users too

lofty falcon
#

mhmm

fervent cradle
#

In general discord, there is a text limit of 2k charakters, what´s the limit of the embed? I read something like 4096?

and is that the right way to check the length, and cut it to the right lenght?

            if len(post.get_text()) < 4096:
                embed = discord.Embed(title=f"New Post:",
                                  description=f"{post.get_text()}")
            else:
                embed = discord.Embed(title=f"New Post:",
                                  description=f"{post.get_text()[:4096]}")
            embed.set_thumbnail(
                url='https://c.tenor.com/WCE5JUszKGMAAAAC/tenor.gif')
            file = discord.File("xxx.png")
            embed.set_image(url='attachment://xxx.png')
            await channel.send(file=file, embed=embed)
#

i am not sure about this

{post.get_text()[:4096]}

is this right? found it on stackoverflow

lofty falcon
#

if the variable is str

#

len(str(variable)) then it returns the amount of characters, so yes

#

oh wait, I should read to the end

fervent cradle
#

it´s a str

lofty falcon
#

Do you have anything coded yet?

#

you just want to trim it right ? to the right size

fervent cradle
#

it´s all coded yet except the check for lenght and the trim

#

i know i could improve the code 😄

#

now it´s better

lofty falcon
#

post.get_text()[:4096], thats right

#

it cuts everything after 4096

fervent cradle
#

ok so my code should work

#

thanks for your help !

lofty falcon
#

but you dont need if else

#

just do it like that:

fervent cradle
#

yeah

#

you are right lol

lofty falcon
#

just use else

fervent cradle
#

if i trim it there is no need for the check

lofty falcon
#

if it is shorter than 4096, nothing will change

fervent cradle
#

somethimes you are brain busted 😄

#

but yeah. you are right, did not think about this 😄

lofty falcon
#

I also code without thinking a lot

#

and then I am like... wait

fervent cradle
#

😄

#

ok thanks for your help 🙂

#

have a nice day 🙂

fervent cradle
#

Is there an example for the select menues?

errant craneBOT
#

Here's the dropdown example.

fervent cradle
#

Alr thanks 👍

sleek arch
#

A simple issue but I cant seem to get it to work, how do I make a bot send a user a DM from a button click, I think that its possible

lofty falcon
#
async def on_interaction(interaction: discord.Interaction):
    await interaction.response.send_message(f"Button Custom ID: {interaction.data['custom_id']}\npressed by: {interaction.user}")
    user=await client.get_user_info(interaction.user)
    await client.send_message(user, "Your message goes here")
#

@sleek arch

#
import discord
from discord.ext import commands
from discord.ui import View, Button
from discord.ext import commands

bot = discord.Client(intents=discord.Intents.all())
bot = commands.Bot(intents=discord.Intents.all(),command_prefix="!")

async def create_message_with_button(msg, embed):
    view=View()
    thisbutton = Button(label="button", style=discord.ButtonStyle.secondary, custom_id='mybutton1')
    thisbutton.callback=on_interaction
    view.add_item(thisbutton)
    await msg.send(embed=embed,view=view)

async def on_interaction(interaction: discord.Interaction):
    await interaction.response.send_message(f"Button: {interaction.data['custom_id']}\npressed by: {interaction.user}")
    user=await bot.fetch_user(interaction.user.id)
    await user.send("Your private message goes here")
#OnCommand
@bot.command()
async def hello(msg):
    embed=discord.Embed(title="**Welcome!**", description="**Press this button to recieve a DM**?", color=0xfbe8d2)
    await create_message_with_button(msg, embed)
bot.run(token)
#

whole code

storm geode
#

ohnvm

lofty falcon
silver moat
#

that just conflicts

lofty falcon
#

never had a problem

#

if it really does, then just install pycord

#

the way I code is weird, but it works

silver moat
#

Not sure how it still works

lofty falcon
#

by getting the button id and user id, I can process the things further depending on my needs

silver moat
lofty falcon
#

#1002289194544136323

#

if someone knows my problem, I would appreciate it

#

I don't want to make a

->
  ->
    ->
      ->
        ->

code blocks

#

I have lots of lists and data and follow ups

silver moat
#

message has a send method?

#

b!rtfm pyc message.send

lofty falcon
#

hmm ?

silver moat
#

well, you use await msg.send(embed=embed,view=view)

lofty falcon
#

yes

#

you can also use msg.channel.send

silver moat
#

oh ic, msg is a Context

lofty falcon