#Basic Pycord Help

1 messages · Page 55 of 1

hexed herald
#

just ping me when I can help you!

proven valley
#

@hexed herald

#

I'm avaliable now if you are

hexed herald
proven valley
#

the thread closed, that's fine. I just want to seperate my subcommands into seperate files, do you know how to do it with the plugin?

hexed herald
#

sure, first I've created a cog that's loaded before all other cogs to create a subgroup -> relevant if you want to use contexts
after that you just import pycord.multicog (I've imported it as pycog to have a shorter decorator
and then you prefix your normal slash command with

@pycog.subcommand("name_of_the_SlashCommandGroup")
@commands.slashcommand()
async def command():
    pass
#

if you do not want to use the command contexts, or other SlashCommandGroup features you can also add to the subcommand independent=True then it creates a command group with the given name for you

proven valley
#

currently in my subcommand decerator I'm doing subcommandground.command(...), you're saying I should use the pycog.subcommand and then just use the normal commands.slashcommand decerator?

hexed herald
#

could you show me your current code? the way I write is the only that I know pepesweat

sage tendon
#

what they do is the normal pycord way

hexed herald
#

ohh, okay I just didn't understand it xD

hexed herald
proven valley
#

This is my subcommand file```py
import pycord.multicog as pycog
from discord.ext import commands
from discord import option
import discord.member
import Confirm
import aiosqlite

class mm1v1(commands.Cog):

@pycog.subcommand("mm")
@commands.slash_command(name="1v1", description="test")
async def command(self, ctx):
    pass ```

Then my main cog file that the command belongs to is setup like this,

import discord
from discord.ext import commands
from discord.ext.pages import Paginator, Page
from discord import option
from pycord.multicog import Bot
import aiosqlite
import discord.member
import asyncio
import uuid

class MM(commands.Cog):
    def __init__(self,bot):
        self.bot = Bot()
    mm = discord.SlashCommandGroup("mm", "test")```
The command currently isn't being loaded, what should I do different?
proven valley
#

Great question, a tutorial I was watch said to do it that way, I don't know enough to question it.

tidal vessel
proven valley
#

So I should just get of that line then

sage tendon
#

you do self.bot = bot

proven valley
#

the reason I changed bot to Bot() is because multicog says to use it, it's subclass of discord.bot that supports splitting command groups into multiple cogs.

proven valley
#

i see my error now

elfin inlet
#

how do I make my choices a list of the channels in the server

#

choices=discord.ApplicationContext.guild.channels doesnt work

little cobalt
elfin inlet
#

mhm

little cobalt
#

voice channels?

little cobalt
elfin inlet
#

is that not a list?

#

the issue it had was this

elfin inlet
#

so how do I fix it

#

I know im stupid just tell me so we can get it over with

little cobalt
#

I wonder which channel do you want

elfin inlet
little cobalt
#

so

#

ctx, channel: discord.TextChannel

little cobalt
#

Its 2:17 am for me and Im sick

#

;3

little cobalt
#

is it working?

elfin inlet
#

no

rugged lodgeBOT
#

Here's the slash options example.

elfin inlet
#

oh I found the problem

atomic fern
#

how to handle DiscordServerError for task.loop? the task stopped if that exception occurs

fresh sierra
atomic fern
#

wdym?

opal swan
#

I think a thing like that

atomic fern
#

i just need to restart the task? or stop/start

echo wraith
#

Btw is there a reason for that?

fresh sierra
#

so you can log the error, to a if insistance ... : pass else stop etc etc

#

its as u want

fossil valve
#

Anyone know why I can't access the embeds or content from a webhook message? It's all coming back as None, even though the webhook message contains an embed.

Code:

@Cog.listener()
async def on_message(self, message: discord.Message):
    if message.channel.id != ADMIN_CHANNEL_ID or not message.webhook_id:
        return
    target_channel = await self._get_deal_channel(message.channel)
    forwarded_message = await target_channel.send(
        content=message.content,
        embeds=message.embeds,
        files=message.attachments,
    )
fresh sierra
echo wraith
#

.tag intents

sly karmaBOT
#

Pycord Docs - Intents
Discord API Docs - Gateway Intents

import discord
from discord.ext import commands

# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True 
...
# Get all non-priveliged intents; this excludes presences, members and message_content 
intents = discord.Intents.default()

# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True  # Required for prefix commands >= 2.0.0b5

# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()

# Apply intents when creating your bot
bot = commands.Bot(prefix="?", intents=intents)
fossil valve
austere cliff
#

how to code a callback function for a select menu

lofty parcel
austere cliff
lofty parcel
austere cliff
#

whats the diff

lofty parcel
#

Pycord is a different library.

austere cliff
#

syntax looks the same

lofty parcel
#

Because it is a fork of d.py.

austere cliff
#

ammmm

lofty parcel
#

From interactions and then the layout is different.

#

If you use d.py, join their server and ask there.

austere cliff
#

u have link?

lofty parcel
#

Google is free.

austere cliff
#

i dont think they have one

lofty parcel
#

Yes they do.

little cobalt
austere cliff
austere cliff
deft kestrel
#

if my laptop doesnt have wifi/Ethernet, the code can still send messages/webhooks?
probably not

fresh sierra
#

...

#

the code will just dont work

lofty parcel
#

Can you turn on a lamp if you cut the wire?

deft kestrel
#

yes if its with batteries

lofty parcel
#

A lamp with batteries doesn't have a wire to plug it in first off.

deft kestrel
#

yes it is if its rechargeable batteries

lofty parcel
#

Can you charge the batteries if you cut the charging cable?

deft kestrel
echo wraith
#

Is there a .tag explaining blocking code, apart from .tag rie

fresh sierra
echo wraith
#

That would be nice

shell radish
#

.tag blocking

sly karmaBOT
#

Tag not found.

echo wraith
#

Like smth that gives an example with time.sleep vs asyncio.sleep and explains a bit the difference

edgy nest
tawny prism
#

Does doing get_emoji on an application emoji not return the emoji, im trying to do a check if an emoji im getting from a list is animated or not but it just returns none if I use an application emoji id

#

the emoji is associated with my bot so i thought it would work

tidal vessel
#

If you need to use emojis from your app, just copy the markdown

tawny prism
tidal vessel
#

I'm not sure

tawny prism
#

idk discord is weird

fresh sierra
#

does someone has a small script to make the bot talk in voice ?, just to test if it works because none of my experiement works

#

(preference without anything to install)

rugged lodgeBOT
#

Here's the basic voice example.

echo wraith
#

wait no not that

fresh sierra
#

found my issue

#

inside my decorator

#

i was doing
ctx.voice_client = ...

#

but i cant do that

#

is there a way for i can do that:

    @staticmethod
    def valid_music():
        async def wrapper(ctx: LumabotContext):
            if not ctx.author.voice:
                await ctx.respond(ctx.translator.music.error.not_connected)
            elif not ctx.voice_client:
                ctx.voice_client = await ctx.author.voice.channel.connect(
                    cls=wavelink.Player
                )
                return True
            elif ctx.author.voice.channel != ctx.voice_client.channel:
                await ctx.respond(ctx.translator.music.error.not_same_voice)

            else:
                return True

            return False

        return commands.check(wrapper)
inner vessel
#

I have a question, I removed some commands from my bot, why do they still exist in my discord channel?

echo wraith
#

it's the opposite of

#

.tag slashnoshow

sly karmaBOT
#

Application Commands Not Showing Up?

  • Refresh Discord by restarting or pressing Ctrl+R (or Command ⌘ + R)
  • Uninstall libraries that conflict with the discord namespace (e.g. discord.py).
  • Invite your bot with the application.commands scope.
  • Load cogs before bot.run() (e.g. not in on_ready).
  • Do not override on_connect.
  • Update to the newest version of py-cord (see ?tag install).
  • Turn off User Settings > Accessibility > Chat Input > Use legacy chat input.
  • Share your code and errors.
inner vessel
#

ty

heavy inlet
#

When to use get_x() and when to use fetch_x() (where x is just the placeholder of something like user, channel etc)?

heavy inlet
#

when should I use fetch instead of get

little cobalt
#

uh

#

that is pretty rare when you only use fetch

#

you check for get_x if None and if None you use fetch_x

#

value = client.get_x()
if value == None:
  value = client.fetch_x()
#

you dont want to do every time a API call to Discord because of rate limits

heavy inlet
#

yeah, plus get retrieves data from the bot's cache, right?

little cobalt
#
get = tries to find the data at the Bot Cache

fetch = Does a API call to the discord API
heavy inlet
#

alr thanks for the help

fluid storm
#

How do you retrieve the user who interacted with the select menu?

async def select_callback(self, select, interaction):
        await interaction.response.send_message(f"The selection that was made was {select.values[0]}")

I wish to say The selection that was made by {user} was {select.values[0]}

lapis dock
fluid storm
#

thanks

halcyon steppe
#

hi, is there a way to somehow get the total number of user installs?

sage tendon
#

shows in the dev portal

halcyon steppe
sage tendon
#

not yet in pycord, but it does exist in the API

halcyon steppe
sage tendon
halcyon steppe
#

thanks

red mist
#

Is it possible to disable a button on a message that is an ephemeral?

I tried this;

@ui.button(label="Cancel Deletion", custom_id="button-cancel-deletion-ticket", style=discord.ButtonStyle.gray)
async def cancel_button_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
    button.disabled = True
    await interaction.message.edit(view=self)
    await interaction.response.send_message("Deletion cancelled!", ephemeral=True)

(even expanded the entire thing with an error log etc. and whenever I try to edit the latest message it says there was no message, so it raises a discord.NotFound)
So again, is this possible on a message that has view components but is an ephemeral?

#

(ping me if you respond)

edgy nest
ivory wind
#

is there an example of making a custom help command that lists the bot's commands? i managed to do it but i feel like it's janky

sage tendon
#

show it

ivory wind
rugged lodgeBOT
sage tendon
#

i might be remembering wrong but doesnt the paginator come with navigation by default

ivory wind
#

i think the button colors weren't what i wanted

#

im in the middle of rewriting everything

late slate
#

I need some quick advice if you guys don't mind...

  • I have a task loop scheduled to run every 30 min that acts as a "message queue processor". It essentially checks a database for queued messages and sends them to a 3rd party API.
  • Each message has to be a separate API call, so I use a for loop to process all the messages. However, I only want to make these calls once every second to avoid overloading the API.
  • I tried placing await asyncio.sleep(1) within the loop, which kinda works... But if a user calls a slash command with await ctx.defer(ephemeral=True) in it while this for loop is running I get the following error: discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction. I'm assuming this is because the bot is sleeping and not replying to Discord's request?

What would be the "proper" way to go about doing this?

obsidian blaze
#

#1130595287078015027 message

As per advaith it is documented and he made it seem it is intended to use. So it this something that could be added to pycord?

proven valley
#

I have a view setup to edit the embed of a message when you press a certain button, but it says interaction failed even though everything works fine, is there something I did wrong for it to be like that?

tidal vessel
proven valley
#

yeah

#

but the message gets edited

#

and all other logic carries out

tidal vessel
proven valley
#

no, what's that?

tidal vessel
# proven valley no, what's that?

In simple terms, you are telling Discord to wait longer for the interaction to respond, sometimes it can take a little longer than 3 seconds for Discord to receive the interaction and discord says failed.

proven valley
#

I see, thank you.

#

would I just add that before the response?

#

or edit in my case

tidal vessel
proven valley
#

the specific interactioin I assume, so for each callback?

tidal vessel
#

Or you can put it in each callback if you prefer that

proven valley
#

okay, I'll give it a shot, thanks.

undone shale
#

Is there a way to, when I get a message, see what other users are in the channel?

I tried message.guild.members but it's only showing my bot in that list which is incorrect.

Do I need the members intent for that?

#

Ah yep, looks like that was it

opal swan
undone shale
#

Uh... It is correct in that it works for me?

I don't need all intents

#

And it seems like bad practice to just... Add all of them in case I need a few of them

sage tendon
opal swan
sage tendon
#

No.

#

You cannot access guild.members without members intents

#

e.g. itll only be the bot, or at most, the command user + the bot

opal swan
#

so he need to activate it.

#

(intents member)

sage tendon
#

he already did

#

he said that before you responded as well

opal swan
#

so idk

daring valve
#

Is there any other way to send personal user messages except dm (dm can be closed)
Like send a message if they get banned, so they can see the ban reason

proven valley
#

is there a way to make it so that an element of my description for a slash command is pulled from a database?

sly karmaBOT
#

Tag not found.

echo wraith
echo wraith
#

You iterate over theese before running your bot and you can set the description and other thigns

proven valley
#

I see, I don't know if that would work, because it would have to change while the bot is running

echo wraith
proven valley
#

everytime a event in the queue gets moved up so like every 15-20 minutes or so

#

I don't need it tbh, but it would be cool

echo wraith
proven valley
#

it'll only ever be in one

echo wraith
proven valley
#

I'll take a look into it, thanks

#

I don't know if I mentioned that it's for a paramter of the applicaiton command not the description of the actual applicaiton command, I don't know if that changes anyhting

lapis dock
#

You could also open an issue or PR so that is is more visible

obsidian blaze
#

Okay! Will do that later

elfin inlet
#

hey guys does defer() just extend the timer or does it count as a response

sage tendon
#

both, really

elfin inlet
#

I have a command that makes the bot say something via send (I dont want people to know who used it) and it works, but also always ends an ephemeral that says "application did not respond"

sage tendon
#

yea you still have to respond something to the actual interaction

#

and dont defer unless you really have to

elfin inlet
#

from what I read it extends by 15 minutes, which is good but if theres one that makes a response happen without a msg that would be best

sage tendon
#

not possible

elfin inlet
#

like I could always do ctx.respond("message sent successfully", ephemeral=True) but id rther not

sage tendon
#

you have to

#

and its better to give the user feedback

#

if i just sent a command and there was nothing in response i'd assume it failed
which is why discord is forcing a response

elfin inlet
#

all it does is clutter the channel

sage tendon
#

it doesnt

#

since its ephemeral

elfin inlet
#

well it clutters for you until you dismiss it

#

its unecessary is all

#

maybe im nitpicking

#

guh

sage tendon
#

a single message..

sage tendon
#

why did i see that GIF in two seperate servers within 5m now wtf

elfin inlet
#

are you in wunkcord

sage tendon
#

no

nova epoch
#

Looking for a method for my bot to get and run commands from other apps. Anyone got any ideas? TIA

Things I have tried (these are all in a commands.Cog context):

  • self.bot.get_application_command() with both a name and/or ID
  • Getting the other app's user with app = self.bot.get_or_fetch_user() then using app.get_application_command(), again with both a name and/or ID.
lean garnet
#

Hi, I'm trying to add a premium subscription using the API to my testing server.

I have this error : Erreur: 401, {"message": "401: Unauthorized", "code": 0}

import requests

url = f"https://discord.com/api/v10/applications/
964234492078350398/entitlements"
headers = {
    "Authorization": " my bot token was here",
    "Content-Type": "application/json"
}

server_id = input("Entrez l'ID du serveur : ")
server_id = int(server_id)

data = {
    "sku_id": "1282072278582169641", 
    "guild_id": 

response = requests.post(url, headers=headers, json=data)

if response.status_code == 200:
    print("Test entitlement créé avec succès.")
else:
    print(f"Erreur: {response.status_code}, {response.text}")
#

can anyone help ? thanks in advance

torn barn
#

Auth should be Bot {TOKEN_HERE}, are you following that structure?

little cobalt
#

you dont need a running bot to use py-cord

fresh sierra
little cobalt
fresh sierra
#

but yeah Unauthorized should be cos because of the missing BOT

torn barn
lean garnet
# torn barn Auth should be ``Bot {TOKEN_HERE}``, are you following that structure?

Thanks I edited this and with the help of some other peoples from Discord Devs server

import requests

url = "https://discord.com/api/v10/applications/964234492078350398/entitlements"
headers = {
    "Authorization": "Bot MyBotTokenHere",  
    "Content-Type": "application/json"
}

server_id = input("Entrez l'ID du serveur : ")
server_id = int(server_id)

data = {
    "sku_id": "1282072278582169641",  # ID du SKU premium
    "guild_id": server_id,  
    "owner_id": "1282090850804957294",  # me
    "owner_type": 1  # user 
}

response = requests.post(url, headers=headers, json=data)

if response.status_code == 200:
    print("Test entitlement créé avec succès.")
else:
    print(f"Erreur: {response.status_code}, {response.text}")

Now I have this error : Erreur: 400, {"message": "Unknown Guild", "code": 10004}.

torn barn
fresh sierra
#

so its Bot and not BOT

torn barn
fresh sierra
#

thanks for the clarification

torn barn
lean garnet
torn barn
#

ids are strings

#

not ints

lean garnet
#

Ohh okay

torn barn
#

py-cord casts them to ints for better usage

lean garnet
#

still not

#

"guild_id": str(server_id),

torn barn
#

so why not just use py-cord as stated before

#
  • create a discord.Client instance, no need for more
  • create an async function:
    • call client.login() (needs await)
    • get or fetch the guild you want to create a test entitlement to
    • create test entitlement using guild.create_test_entitlement (needs await)
  • call asyncio.run on async function
errant trout
#

if you're using the raw api, you would be better off asking in ddevs

lean garnet
#

yes

#

thanks yall it works now

loud kayak
#

.jsk py
type(_author.id)

sly karmaBOT
#

<class 'int'>

edgy nest
autumn narwhal
#

why user can type another word in the autocomplete and use the command
like autocomplete return 1, 2, 3
but if user type 4 in the option
it can still normally to use the command

little cobalt
#

they can type anything they want into it

#

you have to check it at your own

autumn narwhal
#

ok... Alright thanks

little cobalt
#

its not like choices

#

but choices is a hard coded list what you cannot change without a bot restart

edgy nest
#

autocomplete is exactly that- auto complete

little cobalt
#

^

deft bronze
#

Link to startup guide?

#

I didn't use PyCord in like a year and i used it in bridge mode

shell radish
deft bronze
#

thx

deft bronze
shell radish
#

no

glad bone
#

Any idea why this might be happening? My welcome command at the bottom calls "self._create_channel_selection_view":

callback = lambda i: self._handle_welcome_channel_selection(i, ctx)
            print("CALLED3")
            embed, view = await self._create_channel_selection_view(ctx, embed, callback)
            await ctx.respond(embed=embed, view=view, ephemeral=False)

Here it is defined:

    async def _create_channel_selection_view(self, ctx, embed, callback):
        print("CALLED5")
        select = await self._get_text_channel_select(ctx)
        select.callback = callback

        view = discord.ui.View()
        view.add_item(select)

        return embed, view

self._create_channel_selection_view is called, yet after this point, the bot does not respond. and I do not see "called5"

glad bone
#

All the code works, but not when it is called with "self."

torn barn
opal swan
#

un bot fr

lean garnet
opal swan
lean garnet
eternal kite
#

do you have to await task.start() method rn? because it used to work fine back in a year

#
  File "C:\Developments\main.py", line 840, in <module>
    blockedtimeout.start()
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\tasks\__init__.py", line 398, in start
    self._task = asyncio.create_task(self._loop(*args, **kwargs))
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\asyncio\tasks.py", line 371, in create_task
    loop = events.get_running_loop()
           ^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: no running event loop
sys:1: RuntimeWarning: coroutine 'Loop._loop' was never awaited
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
mighty garnet
#

how do i send 2 embeds at once with a response

#

kindof like this

await interaction.respond(embed=[embed1, embed2])```
eternal kite
#

this is the code

@tasks.loop(seconds=2)
async def blockedtimeout():
  # some code

loop = asyncio.new_event_loop()
loop.run_until_complete(get_server_info())
blockedtimeout.start()
bot.run(key)
eternal kite
lapis dock
#

^ just add a s

mighty garnet
#

thx

sage tendon
#

await it

eternal kite
#

its not an asynchronous method

sage tendon
#

oh wait
can you show your code

sage tendon
#

ah
do you use cogs?

eternal kite
#

yeah

sage tendon
#

just put it in a cog then, and not your main file

#

and then start it from the __init__

eternal kite
#

oh let me try

#

bot.run too?

sage tendon
#

no lol

lapis dock
#

No, leave bot.runcwhere it is

sage tendon
#

if you use cogs, your main file ideally has nothing bu the bot setup + start, and on_ready, and cog loading

eternal kite
sage tendon
eternal kite
#

no

sage tendon
#

can you show your entire main file

eternal kite
eternal kite
sage tendon
#

just the cog loading really

sage tendon
# eternal kite

(also i recommend just using the pypi package as requirement instead of the github unless you really need all in-dev features)

lapis dock
little cobalt
sage tendon
#

already said :)

eternal kite
#
a bunch of imports here

extensions = ["cogs.maincog", "cogs.utilitiescog", "cogs.devcog"]

async def get_server_info():
    cluster = motor.motor_asyncio.AsyncIOMotorClient(db_url, serverSelectionTimeoutMS=5000)
    try:
        await cluster.server_info()
        print(" * Connected to the Database server.")
    except Exception:
        print("Unable to connect to the server.")

@tasks.loop(seconds=2)
async def blockedtimeout():
  # some code

if __name__ == '__main__':
    for extension in extensions:
        bot.load_extension(extension)
        print(f"Loaded {extension[5:].capitalize()} extension")
    loop = asyncio.new_event_loop()
    loop.run_until_complete(get_server_info())
    blockedtimeout.start()
bot.run(key)
little cobalt
#

requests uh

eternal kite
#

thats a part of the bot feature

little cobalt
#

do you use a new runner for it?

sage tendon
#

requests is built in lol

eternal kite
#

is it? i dont remember lol this project used to work in about a year ago

#

i didnt touch anything and it's not working rn

sage tendon
#

either way first of all please replace the pycord dependency with py-cord==2.6.0 to make sure there isnt any issue with the master branch rn
and of course uninstall and reinstall py-cord accordingly

#

then we can look further

#

also you still didnt put this in a cog lol

eternal kite
#

but the function is in my main.py file ._.

sage tendon
#

move it to a cog

#

you have cogs for a reason

eternal kite
#

is that the best practice? to run tasks in cogs

sage tendon
#

yes (imo)

eternal kite
#

also what are the factors that makes it longer for your bot to ready?

#

i kinda forgotten all these stuff

lapis dock
#

Loading members to the cache

#

I think you can disable this with the chunk_guilds_on_startup=False kwarg to bot

eternal kite
#

but my bot is not readying

lapis dock
#

And logging in as a sharded bot but I dont think you can make this faster

eternal kite
#

wait i guess my bot isn't sharded

lapis dock
#

How many guilds is it in

eternal kite
#

it's probably not sharded its only in a few hundred servers i assume

#

i dont remember coding sharding system for the bot

lapis dock
#

Yeah sharding is recommended above 1000 guilds required at 2500. Under 1000 not recommended because it will actually slow things down

eternal kite
#

so there must be another reason that my bot is not readying

lapis dock
#

can you comment out, and see

loop = asyncio.new_event_loop()
loop.run_until_complete(get_server_info())
eternal kite
lapis dock
#

hmm strange

eternal kite
#

i came back to this project because i received a message from discord saying my bot verification is going to expire in about two months 😂

#

there's so much i have to revise

lapis dock
eternal kite
#

also how big of a difference is pycord and discordpy rn?

sage tendon
#

slash commands? quite

#

prefix? barely if at all

lapis dock
#

Discord API support they are essentially identical but implementation is quite different

eternal kite
#

yes, i migrated to pycord when slash commands are enforced

sage tendon
#

yea many did, since the dpy guy basically rage quit when slash commands were announced lol

eternal kite
sage tendon
#

well for one, dpy doesnt use like @bot.command, but uses a weird (overcomplicated) tree system for commands
dont ask me, i dont know much more either, just that pycord is considerably easier

eternal kite
lapis dock
#

Everything new is named slightly different. Very little overlap.

#

you might get some functions to work but it would work differently and create a lot of hidden bugs

sage tendon
#

but core library basics like idfk guild.channels and guild.get_channel, you name it, are overall really similar if not 90% the same

#

because it was just taken from dpy and never (needed to) change

eternal kite
#

it took me 2 weeks to migrate from discordpy to pycord and rewrite everything in slash command, im not spending another 2 weeks to migrate back again

sage tendon
#

yea there's no point to do that

#

its more work

#

for no gain

eternal kite
#

yea as long as bob is keeping up with the updates

sage tendon
#

ah you missed the bob situation lol

eternal kite
#

what was it?

lapis dock
#

Well bob does not do alot of the development anymore but other people are

eternal kite
#

oh yeah i can tell

sage tendon
#

a relatively big update was ready but bob was gone for quite some time which meant the pypi package couldn't be updated

eternal kite
#

i used to play clashofcode with him

sage tendon
#

but i think control of that was transferred to someone else? but i dont remember exactly

eternal kite
#

welp that was quite a bad news

#

what about dorukyum?

sage tendon
eternal kite
#

man it'll be a pain if i have to migrate back to discordpy some day

sage tendon
#

you wont

#

IF pycord ever was to stop development, there'd just be another fork, and business as usual

eternal kite
#

im planning to rewrite the whole bot during december because after a year i look back at my code and it's ugly af

sage tendon
#

ikr

lapis dock
#

Yeah, I dont see py-cord dying at any point.

eternal kite
#

smh 20k lines of code of gibberish

sage tendon
eternal kite
#

no lol

#

my main.py is the only clean file i have

#

although it still has around 1k lines of code

#

oh yeah my cogs are pretty clean too

sage tendon
#

bruh mine has like 28

eternal kite
sage tendon
#

yea you should really consider splitting it up

eternal kite
#

i implemented a dynamic cooldown for my bot

sage tendon
#

e.g. this is how i structured my bot

#

especially the helper classes cut down on a lot

#

and utils in general ofc

sage tendon
eternal kite
#

lol i dont even wanna look at mine

#

every file is a disaster

sage tendon
#

dynamic cooldowns

eternal kite
#

wait what was the feature of this again?

sage tendon
#

well
dynamic cooldowns lol

eternal kite
#

because i remember i implemented this back in 2021 or 2022 because its not flexible enough to achieve what i wanted

sage tendon
#

i mean you can do a ton with it

eternal kite
#

yeah right, it says a command can only have one cooldown

#

what i wanted is, check for a condition, if true the cooldown will be longer, otherwise it will be shorter

#

i dont think dynamic cooldown provides this feature, and that's probably the reason i rewrote the whole thing

sage tendon
eternal kite
eternal kite
sage tendon
#

yea thats exactly what dynamic cooldowns let you do lol

eternal kite
#

i am 100% sure back in the days they dont provide this feature

#

so i had to implement it myself

little cobalt
#

It was even at 2018?

eternal kite
#

its in 2021 or 2022

#

ok so how would you use it in my case

sage tendon
#

look at the docs, its well described

eternal kite
#

it says it takes discord.Message as a parameter but i have literally no idea how it works

#

i probably just forgotten everything it's been at least a year since i last touched bot development

sage tendon
#

message.author and you have all you need

eternal kite
sage tendon
#

you can return any cooldown you want

#

as per the docs lol

eternal kite
#

because this is how i used the cooldown

#

referring to the custom cooldown i implemented above, it will give the user a 900s cooldown if they are not a donator, and 600s cooldown for a donator

#

is this possible with the built-in dynamic cooldown?

sage tendon
#

yes.

eternal kite
#

huh.

#

theres no way

#

i mean it takes a discord.Message as a parameter how is it possible

sage tendon
#

message.author

#

again

eternal kite
#

yeah but where do i add the condition

#

are there examples?

sage tendon
#

in the function

eternal kite
#

oh wait wtf

#

im dead rn 💀

#

nah i swear this wasn't implemented back in the days

sage tendon
#

added in version 2.0

#

2.0 came out in 2022

eternal kite
#

yeah i joined before v.20 came out

#

i still have the v2.0 tester role

#

i just realised how terrible is my code

#

12 database read write in the on_application_comand event, and a bunch of if else statement checks

sage tendon
#

wtf

eternal kite
#

yeah i have a database that traces what's the last time the user used a command, and the command they used etc

#

also check if they are userbotting like using the same command again and again, and check if they are banned/temporary blocked from using the bot

#

also checks if the bot is currently under maintenance, or if there's new updates that should inform the user for the first time they use a command

sage tendon
#

damn

eternal kite
#

there's going to be a bunch of work for the revamp

fresh sierra
sage tendon
#

always?

#

okay apparently im wrong wtf
i never ever installed it

#

:> oops

shut fox
#

hi guys! my button stops working after 5-10 minutes (no error)
code:
class FormButton(View):
@discord.ui.button(label = 'Send request', style = discord.ButtonStyle.green, custom_id="fmbt")
async def button_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
modal = RoleModal(title = 'Request')
await interaction.response.send_modal(modal)
print(123)

rugged lodgeBOT
#

Here's the persistent example.

sage tendon
#

you nneed this

shut fox
sage tendon
#

mainly this in the on ready, and making your view have no timeout

nova epoch
#

Is there a way for a bot to add, remove, enable & disable automod rules? Can't seem to find much anywhere...

sage tendon
#

create and delete yes
enable and disable, not sure

nova epoch
#

Any chance you can point me toward some docs regarding creating/deleting? I've had a look on https://docs.pycord.dev/en/stable/api/models.html#automod but it doesn't seem to help much lol

nova epoch
#

Awesome, thanks :D

gaunt light
#

I'm currently testing changes for a bot on a test server and although I've limited all commands from that bot to be executed within one channel (in the server integrations) on the test server I can still see and successfully execute the commands in other channels as well (restarted the bot and reloaded discord already)
Is that a thing because I'm also the owner of the test server?
I'm on version 2.3

shell radish
#

Is that a thing because I'm also the owner of the test server?
yes

gaunt light
#

ah ok
thanks!

dense summit
dense summit
errant trout
dense summit
errant trout
#

yes

dense summit
#

alright tomorrow i'll try ty

dense summit
#

worked ty

shut fox
#

can i'm attach variable to member?

sage tendon
#

can you explain in a full sentence

edgy nest
#

member has __slots__

shut fox
shut fox
edgy nest
#

can store elsewhere and refer to it with member id

#

cannot store in member

stable yarrow
#

I am trying to make User Installed App but it doest seem to be working, am i doing something wrong?

#

bot logs in but doesnt show cmd , I tried reloading discord for cache, it didnt work

#

i think i found it

#

it would be default_command_integration_types and not default_integration_types

stable yarrow
#

salute thnx

cosmic thunder
#

hey guys, I THINK i've been looking at this too long, but i'm getting a NoneType error telling me serverrole doesn't have the members attribute, yet in debug every part of the right side of the assignment resolves?

                           profession: discord.Option(str, choices=['Alchemy', 'Blacksmithing', 'Enchanting', 'Engineering', 'Inscription', 'Jewelcrafting', 'Leatherworking','Tailoring'])
                          ,):
    if profession == 'Alchemy':
        serverrole= discord.utils.get(ctx.guild.roles, name=profession)
fresh sierra
cosmic thunder
#

i'm forcing the user to select a prof though?

fresh sierra
sage tendon
#

the role just isn't cached then

#

or doesn't exist

cosmic thunder
#

ok, so in debug serverrole is reporting as none

#

how do I cache the role?

fresh sierra
#

by fetching it

sage tendon
#

make sure the role exists with that name first of all

#

it should be cached

cosmic thunder
#

oh my god. I never saved it in my test server. If this works i'm headbutting a wall.

#

I am officially an idiot. Thank you for rubber ducking

cosmic thunder
#

okay next question (SORRY) - using the same block of code, it now executes fine but with multiple users added to the role only returns the first into the serverrole variable

sage tendon
#

show the code

cosmic thunder
#
                           profession: discord.Option(str, choices=['Alchemy', 'Blacksmithing', 'Enchanting', 'Engineering', 'Inscription', 'Jewelcrafting', 'Leatherworking','Tailoring'])
                          ,):
    if profession == 'Alchemy':
        serverrole= discord.utils.get(ctx.guild.roles, name=profession)
        if serverrole.members:
          members_list = "\n".join(str(member.mention) for member in serverrole.members)
          await ctx.respond(f"The users in the {profession} role are: \n{members_list}", ephemeral=True)
        else:
          await ctx.respond(f"No members in the {profession} role", ephemeral=True) ```
#

When Alchemy is selected, only one user is returned

#

yet it has two users

#

that's the output

little cobalt
#

Can you show the bot intents

cosmic thunder
#

in the codebase? or in the discord dev panel

little cobalt
#

the bot

cosmic thunder
#
intents.message_content = True``` is what i'm running in the code
#

(not indented)

little cobalt
#

did you also added it to the bot?

cosmic thunder
#

do I check that in the dev panel in discord?

little cobalt
#

I mean at bot = discord.Bot

cosmic thunder
fresh sierra
little cobalt
#

so you dont have any role intents

fresh sierra
#

for me it need member intents

cosmic thunder
#

[<Member id=202471364454514689 name='.igglepiggle' global_name='IgglePiggle' bot=False nick=None guild=<Guild id=1276103481287249990 name='MyBotFarm' shard_id=0 chunked=False member_count=5>>] is the print

#

only returns one member

fresh sierra
#

try with adding member intents

cosmic thunder
cosmic thunder
#

(very VERY new to python)

sage tendon
#

intents.members = True

#

check the docs

cosmic thunder
#

aah okay my mistake thank you

#

That has fixed it. Thank you very much. I'll read up on member intents now so I understand why.

lean garnet
#

Hi, I have an issue with my premium button

        button = Button(
            style=discord.ButtonStyle.premium, 
            sku_id= 1282125623967354920
        )

It says : discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body

I checked and 1282125623967354920 is my sku ID. Anyone knows what I have this error ?

#

it says the same if I try with str

jolly shuttle
lean garnet
lean garnet
#

this style is quite new

edgy nest
lean garnet
edgy nest
#

no like, your error should look like this

#

with a bit detailing what's invalid

lean garnet
#

Oh yes I forgot

#

one sc

#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.sku_id: Invalid SKU

#

but as I said I double checked

sage tendon
#

try to pass it as string

#

and remove the leading space infront of the id

lofty parcel
sage tendon
#

ah

#

are you trying it in the correct server?

shut fox
#

guys, how to use __slots__?

sage tendon
obsidian blaze
#

Is it possible to have an issue reopened on github once someone has closed it?

shell radish
#

yes

obsidian blaze
shell radish
#

in this case, this issue is closed for good

obsidian blaze
#

oh, so should I just open another one then since there is more info now?

shell radish
#

if you believe that should be the case, go ahead

rare marlin
#
The issue is that the full name is no longer displayed, and only the first letter is shown. Originally, the entire name was supposed to appear, but now it doesn't work anymore. It's unclear where the problem lies; it might be related to the database


class CreateTicketSelect(discord.ui.View):
    def __init__(self, guild_id):
        super().__init__(timeout=None)
        self.guild_id = guild_id

    async def generate_select_options(self):
        options = await db.get_options(self.guild_id)
        return [discord.SelectOption(label=option, value=option) for option in options]

    @discord.ui.select(
        custom_id="ticket_select",
        placeholder="👆 | CLICK ME!",
        options=[],
    )
    async def select_callback(self, select, interaction):
        try:
            options = await self.generate_select_options()
            select.options = options
            await interaction.response.edit_message(view=self)
        except discord.errors.InteractionResponded:
            await interaction.followup.edit_message(message_id=interaction.message.id, view=self)``` ```py
async def get_options(self, guild_id):
        options = await self.all("SELECT option_name FROM ticket_options WHERE guild_id = ?", (guild_id,))
        return [option[0] for option in options]```
sage tendon
#

why do you not fill the options when creating the select?

rare marlin
fresh sierra
#

Just do return option for option in options

#

Else check ur db to see if there is full name

fresh sierra
fresh sierra
sage tendon
fresh sierra
#

I mean in the code u shared this only appeared once

rare marlin
fresh sierra
#

sage tendon
#

remove the [0]

rare marlin
#

i have

fresh sierra
#

Then test

sage tendon
#

yea then try again

#

also, why are you on a commit of 2.5

rare marlin
sage tendon
#

go to 2.6

fresh sierra
#

He is using ezcord

sage tendon
fresh sierra
#

For options you should use

rare marlin
rare marlin
fresh sierra
#

Well first

#

Czn you show us rhe fonctikn that ur using to crzte the option ?

rare marlin
#

ya

#
@ticket.command(description="add a ticket Select Option")
    async def add(self, ctx, name: Option(str)): # type: ignore
        guild_id = ctx.guild.id
        if await db.name_exists(guild_id, name):
            await ctx.respond("The option already exists.", ephemeral=True)
            return
        await db.add_option(guild_id, name)
        await ctx.respond("The option was added successfully.", ephemeral=True)

        
        ticket_message_id = await db.get_message(guild_id)
        if ticket_message_id:
            channel = ctx.guild.get_channel(await db.get_channel(guild_id))
            if channel:
                try:
                    message = await channel.fetch_message(ticket_message_id)
                    view = CreateTicketSelect(guild_id)
                    await message.edit(view=view)
                except discord.NotFound:
                    print(f"Ticket message not found for guild {guild_id}")```
#

@fresh sierra

fresh sierra
#

Let me grab my computer to see

#

can you only send us a screenshot of the issue

sage tendon
#

if the value prints correctly, there is no way this only returns the first letter as the option name unless you're doing something else

fresh sierra
#

like what you see in the thing

shell radish
#

how is the select menu being created

fresh sierra
#

according to ur code after you click on the dropdown it should edit the option right @rare marlin

#

but my question is how can they click on the dropdown if there is no option ?

sage tendon
#

yea i still am confused why they initialise the menu with no options selected

fresh sierra
#

is that even possible ?

sage tendon
#

apparently

fresh sierra
#

well

#

i cant do what he is doing

#

Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0.options: Must be between 1 and 25 in length.

#

@rare marlin can you actually send the dropdown ?

deft kestrel
#

with discord modals is possible to select some users?

sage tendon
#

modals are text only

fresh sierra
#

like send it from 0

rare marlin
fresh sierra
#

no like send it again

#

so see if it works

rare marlin
#

@fresh sierra

fresh sierra
#

as i said

#

send the dropdown click me

#

again to see if its work

#

because i explain to u my thing

#

u should not be able to send an empty dropdown

#

what i think u should use it creating option dynamically

rare marlin
#

@fresh sierra Can I send you the whole code? @sage tendon

fresh sierra
#

u cant create a dropdown without issue

#

that why ur code was not updating

rare marlin
fresh sierra
rare marlin
fresh sierra
#

to be able to pass the option as the creation dynamically

red mist
#

What's the difference between category.id and category_id ? (Ping me on reply)

#

oh wait

#

category_id is to specify where a new channel should belong to

#

answered my own question

shut fox
#

why are they needed Cogs?

echo wraith
shut fox
echo wraith
lapis dock
# shut fox why are they needed Cogs?

They are somewhat of a leftover from prefix commands as you could reload your cogs and the commands would change. I think you can still reload the cogs as long as you do not change the command definition. It gets weird when you want to hot reload a command definition

sage tendon
#

cogs are all but leftovers

echo wraith
#

Cogs are a feature for me

broken pivot
#

how can I perform each task in turn (sequentially, one after the other). I am using aiosqlite and my database is being blocked due to multiple tasks

hexed herald
#

my attempt would be to start each task after the one before finished, maybe you could use custom events for that?

sage tendon
#

your database connector should handle concurrent access

#

it might block but only for a few milliseconds

lapis dock
#

You might need to look into connection pools

modern trail
#

I'm seeing a weird issue with paginators, where if I have two paginators that were invoked by different commands both active at the same time, I get an index error when trying to page through the first one. If i invoke the same command twice to get 2 of the same paginator though, they both happily work. Am I doing something wrong?

lapis dock
#

Are you editing a list or dict in your callback that could be shared between paginators

modern trail
#

hmm, no. This is the full error:

Traceback (most recent call last):
  File "/Users/derek/Code/pzsd-bot/.venv/lib/python3.10/site-packages/discord/ui/view.py", line 426, in _scheduled_task
    await item.callback(interaction)
  File "/Users/derek/Code/pzsd-bot/.venv/lib/python3.10/site-packages/discord/ext/pages/pagination.py", line 121, in callback
    await self.paginator.goto_page(
  File "/Users/derek/Code/pzsd-bot/.venv/lib/python3.10/site-packages/discord/ext/pages/pagination.py", line 691, in goto_page
    page = self.pages[page_number]
IndexError: list index out of range

Each paginator gets its own new list of pages, even when invoking the same command twice

lapis dock
#

Strange, you should open a thread with your code

#

I'm not on PC so I can't test right now tho

round heart
#

Asking again in case I am just dumb:
Is there a way to pre-emptively restrict SlashCommandGroups to specific Roles or at least flags (e.g. kick_members or whatever) so I don't have to manually go into Integrations?

#

I see there's commands.has_role(...)... can I use that to specify a specific Role? Or would there not be enough context to enforce that by the time it registers the commands with Discord?

lapis dock
#

All checks are performed by the bot. So the bot will still receive the command and throw an error if the check is not met.

Default Permissions and the integrations menu are the only way to hide the command from users

IE you cant restrict a command based on a role or user via your code

round heart
sage tendon
#

If you set default permissions to admin ONLY admins can see the command at all

lapis dock
#

More general to what toothy said
If you set default permissions to something the user can only see that command if they have those permissions. If integration settings are set they will override the default permissions

#

So for example a ban command can have the default permissions of ban_members and that will make it so that when the bot is first added to the guild only people who are allowed to ban can use it until the owner customizes the integration settings to their needs

round heart
frail basin
#

Is there any way to make "single guild" bots more redundant?

#

Essentially I want to run two instances in different DCs

sage tendon
#

for what purpose

frail basin
#

redundancy..

#

If network drops in DC1 but works in DC2 then the bot should stay online.

#

Not quite familiar with sharding, however I believe a guild can only "belong" to one shard.

sage tendon
#

yea

#

p sure

#

running it twice would work except for events i think

frail basin
#

Wouldnt interactions also get doubled?

#

Thats the part I am worried about really.

sage tendon
#

no

#

and i mean, just try it

shell radish
sage tendon
#

from my testing there's only ever one response even if the bot runs twice

shell radish
sage tendon
#

i do always use respond

#

let me retest

#

nope, one response in chat
cant check the other bot's console rn tho

echo wraith
#

Just a 3 server docker swarm

#

that's it

pearl carbon
#

how to create custom check for slash_command

with open('config.json', 'r') as f:
    config = json.load(f)

admin_users = config['admin_users']

def is_admin():
    async def predicate(ctx: discord.ApplicationContext):
        return str(ctx.author.id) in admin_users
    return commands.check(predicate)

@bot.slash_command(name="admin_add", description="Add a Pokémon to the database.", checks=[is_admin().predicate])
@discord.default_permissions(manage_guild=True)
async def admin_add(ctx, image_url: str, pokemon_name: str):

Is this how I supposed to do it?

fresh sierra
#
@bot.slash_command(name="admin_add", description="Add a Pokémon to the database.")
@discord.default_permissions(manage_guild=True)
@is_admin()
async def admin_add(ctx, image_url: str, pokemon_name: str):
#

this seem more logical to me

#

but depends on how u want

pearl carbon
# fresh sierra ```py @bot.slash_command(name="admin_add", description="Add a Pokémon to the dat...
Ignoring exception in on_application_command_error
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.12/site-packages/discord/client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/main.py", line 319, in on_application_command_error
    raise error
  File "/home/container/.local/lib/python3.12/site-packages/discord/bot.py", line 1137, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "/home/container/.local/lib/python3.12/site-packages/discord/commands/core.py", line 432, in invoke
    await self.prepare(ctx)
  File "/home/container/.local/lib/python3.12/site-packages/discord/commands/core.py", line 354, in prepare
    raise CheckFailure(
discord.errors.CheckFailure: The check functions for the command spawn failed
#

i am getting this

#

on both type of check styles

sage tendon
#

are you returning true or false?

pearl carbon
#

thats all i have

#
{
    "admin_users" : [330342042687504395]
}
#

config.json

pearl carbon
#

that's why it wasn't matching

modern trail
#

this is very bizarre, having two paginators active at once, trying to go to the next page of paginator A will actually affect paginator B instead. I have a thread open with my code, though idk if those get looked as actively as here. In any case, it seems the paginator class is getting confused on which buttons refer to which paginator? Has anyone else experienced something like this?

#

oh wait a second, do I need to provide a separate list of custom buttons to each paginator? all my paginators are sharing the same list of buttons

#

that's the only thing i can think of that could cause an issue. guess i'll test providing copies of the list so each is getting new button instances

#

nope, that didn't fix it. even with completely different instances of paginator buttons, the two paginators are still somehow linked

lapis dock
#

Answered fisk in the thread

vivid axle
#

Hey I had py-cord working then i cleaned my project up and repackaged it into a docker file, now its having problems with a slash commands with descriptions? did somthing change?

vivid axle
#

nothing in the console

little cobalt
#

do you use ctx.send and not respond?

vivid axle
little cobalt
#

that looks fine for me

vivid axle
#

my other comands work too, just not this one.

lofty parcel
#

Hard refresh your client.

little cobalt
#

ctrl + r

vivid axle
#

But thank you

lofty parcel
#

Yes I meant the app.

vivid axle
#

Just discord things i guess.

jaunty knot
#

How does one get the cog commands to sync/ work with the desktop client? Can get it to work on the web app

lapis dock
#

Do you mean the commands are not showing up on discord?
If so restart your discord client. Ctrl + r. It is just discord being slow to update them so you have to force it to

jaunty knot
#

Why didn't I think of that, thanks lol

lapis dock
#

np, a very common issue we have here hehehe

jaunty knot
#

It showed on the list of commands but calling it did nothing lol

nova epoch
#

Needing a hand with some discord.Option related stuff.
I have a command arg with predefined options via discord.Option with a ton of discord.OptionChoice elements in the choices arg. The choices list is 51 items long, with a max of 25 (this is the issue).

Is there any work-around for it? Thanks :D

sage tendon
#

you can only use autocomplete

#

but that doesnt enforce the options, it just suggests them, the user can still enter everything

#

(and btw you dont need optionchoices unless you want the displayed value to be different from the actual value

nova epoch
sage tendon
#

No

#

you'd have to manually check that

nova epoch
#

Ouch >.<

haughty grove
#

why does @discord.default_permissions not check permissions at all? or am i using it wrong here?

#

everyone is able to execute that command

lapis dock
#

Can you make sure that permissions in the integration menu are not overriding the default permissions?

haughty grove
#

i thought that works the same as @commands.has_permissions

lapis dock
#

So default permissions are the permissions that are required unless they are overridden by an admin in the guild.
You can go to Server Settings -> Integrations -> your bot
If these are set they will override the default permissions

lapis dock
haughty grove
#

well i never changed anything there so there shouldnt be any overrides

errant trout
haughty grove
#

just figured, thanks you two!

errant trout
#

You can only do it on the original group by passing default_member_permissions with a discord.Permissions object

haughty grove
fresh sierra
#

is that possible to setup a global check in a cog ?

cursive swallow
#

Basic Pycord Help (UPDATE TO 2.6.1!)

pearl carbon
#
quest = bot.create_group(name="quest", description="Manage you regional quests")
```How can i create quest as a solo slash_command as well use as group command?

I currently know how to create a slashgroupcommand and its subcommands and I don't know a way to use that group command as solo slash_command

for example:
`/quest add region:Alaska` : using quest with sub command
`/quest`: using quest as solo slash_command
#

I wanted to show info about quest of user using just /quest but if i can't find any help, then i'll be forced to shift to /quest info instead

sage tendon
#

not possible

pearl carbon
sage tendon
#

that makes no sense in response to that message

pearl carbon
sage tendon
#

gotta make another subcommand then

pearl carbon
#

yeah on it currently

jaunty knot
#

set the view timeout to None, but i keep getting "This interaction failed"

sage tendon
#

did you also add it to the bot?

jaunty knot
#

hmm

#

its within a cog thats loaded into the bot

pearl carbon
sage tendon
#

you need to do self.bot.add_view(View())

jaunty knot
#

could be, mostly playing around with select menus

#

ill do that

pearl carbon
sage tendon
#

in a select? yes

pearl carbon
#

no, in slash_command options

sage tendon
#

then no

pearl carbon
#

ahh guessed it :/

edgy nest
#

you can kind of simulate that with autocomplete

#

but the user can then just type whatever they damn well please

#

i'd just make multiple options

jaunty knot
#

results in "Application Command raised an exception: ValueError: View is not persistent. Items need to have a custom_id set and View must have no timeout"

sage tendon
#

why don't you make a sperate view class

#

makes it much cleaner to handle

#

and yea you didnt set no timeout

jaunty knot
#

lol

pearl carbon
jaunty knot
sage tendon
#

yea add it back

jaunty knot
#

partially worked, the add_view at the bottom is returning TypeError: object NoneType can't be used in 'await' expression

sage tendon
#

code

jaunty knot
#

here's that whole thing

sage tendon
#

and show the error too

jaunty knot
sage tendon
#

you arent awaiting that in your code tho what

#

and it shouldn't be awaited

jaunty knot
#

had an await, but, removed it after getting the error

#

while it works, the select menus don't pop up

sage tendon
#

show

jaunty knot
#

this is what happens after running the command

sage tendon
#

any error?

jaunty knot
#

nope

sage tendon
#

show where you send the message then

#

because i dont think you do

#

since you arent using ctx in that command

jaunty knot
#

i'm hitting enter after the command

sage tendon
#

you arent responding to the interaction in your code

granite pier
#

thats 1 thing

#

and show ur whole code of command

sage tendon
#

they're just missing ctx.respond, thats all

jaunty knot
#

hmm, any way to not make this persistent?

sage tendon
#

what

granite pier
sage tendon
#

they'll still need to add the view to the bot tho if they want it to be persistent
which would be much cleaner with a seperate class :>

granite pier
sage tendon
#

i know

jaunty knot
#

worked, but "this interaction failed" is back

sage tendon
#

yea because you arent adding the view to the bot

#

first of all make a seperate view class before you do anything else

#

and then add that to the bot in on_ready

jaunty knot
#

might as well, ty

red mist
#

Me who's still stuck on 2.5

#

:^]

sage tendon
#

why?

red mist
#

Didn't update

sage tendon
#

why?

red mist
#

Because I didn't wanna break my shit

#

By introducing bugs

sage tendon
#

update
test everything
done

red mist
#

update test everything some big big turns out happening

#

*bug

#

Security risk of some sort

#

and everything goes to shit

sage tendon
#

you think about it too much

red mist
#

n.n

little cobalt
#

Ab ins Bett mit euch!

edgy nest
#

voxy is right

red mist
#

Jokes on you

#

I'm already in bed

#

@little cobalt

jaunty knot
#

the only thing I'm not sure of is if I can only pass one select menu within the class

sage tendon
#

of course you can do multiple

#

idk what the max per message is tho

jaunty knot
#

From what I read (unconfirmed) it's 5, but can't seem to add another one

sage tendon
#

I think it's 3 or 4

jaunty knot
#

here's where I'm at, only the first select shows

granite pier
fresh sierra
#

For I put a check in a cog that does that for every command in the whole bot

granite pier
#

async def bot_check / async def bot_check

fresh sierra
#

Im gonna try

#

But in my memory it was not doing a global check

granite pier
#

bot_check = global

#

cog_check = cog

edgy nest
#

just a method

fresh sierra
granite pier
#

so method no decorator ^

ivory wind
#

hello, i am trying to create a delete button that deletes a message. i made the custom id channel_id-message_id. in the callback method, i tried messageObj = await commands.MessageConverter().convert(interaction.context, message_id) but it errors with
AttributeError: '_EnumValue_InteractionContextType' object has no attribute 'guild'.

can i actually do this? basically trying to delete reported messages and the view is hidden from the public

lofty parcel
ivory wind
#

another

#

trying to do this

lofty parcel
#

Just pass the message object to your view class through the init

#

Or pass your channel ID and message ID and then create a PartialMessage

lapis dock
#

you should not be using the message converter in that way. If anything you should be using my_channel.get_message() and my_channel.fetch_message(). But like dark said for deleting messages you only need a PartialMessage

ivory wind
#

thank you!

summer knot
#

How can I upload emojis to the bot?
Since even I know how to upload emojis to a discord server, but how could I do it for the same bot?

shell radish
summer knot
shell radish
#

not yet, but soon

fresh sierra
#

isnt role.position should return the role position and so not the same number for many role ? (each role in the guild has 2 as position after)

#

(this issue is not there is 2.5 so yeah seems that is a 2.6 issue)

#

after updating to 2.6.1 role.position only return 1

fast glade
#

How can I programmatically end the bot process without any traceback or extra console output?

#

(sys.exit(0) outputs traceback and bot.close() prints some extra warning messages)

pearl carbon
little cobalt
#

You might have to use bridge group for it

pearl carbon
little cobalt
#

Maybe, I never did it with bridge commands

rugged lodgeBOT
#

Here's the bridge commands example.

errant trout
#

showcased there

pearl carbon
#

and then use it like this

@quest.command(name, description)
async def add(args)```
pearl carbon
#

ohh nice thnks

pearl carbon
# errant trout showcased there

just 1 more question, i have added options in one of the slash commands, but since in prefix commands users can't see choices, so do i need to add additional custom validation decorator to check if the has entered valid choice?

#

or pycord has internal validation function to raise error for wrong choice input?

fresh sierra
#

Using autocomplete everything can be use

pearl carbon
pearl carbon
#

yes what?

fresh sierra
#

Yes it will return an error and not get i voned

#

Bad arg errro

pearl carbon
#

ohh ohk

#

thnks

pearl carbon
keen relic
#

can u give Me discord.Interaction doc link? @errant trout

lofty parcel
#

You'll be shocked when you find out there's a search bar.

sage tendon
#

and hyperlinks to look further

keen relic
keen relic
nimble matrixBOT
keen relic
sage tendon
#

is it so hard?

stray yarrow
#
    @isAdmin()
    async def view(self, ctx):
      .....
#

ctx is a required argument which is missing

#
class Config(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.functions = Functions()

    @commands.group(name="hostrole", description="View host role commands.")
    @isAdmin()
    async def hostrole(self, ctx):
      ///....
stray yarrow
sage tendon
#

thats not how you define a slash group

#

you do

x = SlashCommandGroup(...)

//later

@x.command()
async def...
#

tho if its prefix ignore what i said and idk how prefix groups work

stray yarrow
#

yes its prefixed

#

it worked earlier on till i edited isadmin

#

despite it doing the same thingwith and without it

sage tendon
#

ah

#

why dont you use commands.has_permission

stray yarrow
#
    def __init__(self, bot):
        self.bot = bot
        self.functions = Functions()

    @commands.group(name="hostrole", description="View host role commands.")
    async def hostrole(self, ctx):
        if ctx.invoked_subcommand is None:
            subcommands = [f"`{ctx.prefix}{command.qualified_name} {command.signature}`".strip() for command in self.hostrole.commands]
            subcommands_list = '\n'.join(subcommands)
            embed = discord.Embed(title=f"{ctx.command}".title() + " Commands", description=subcommands_list, colour=0xFFFFFF)
            embed.timestamp = discord.utils.utcnow()

            if any(command.signature for command in self.hostrole.commands):
                embed.add_field(name="Parameters", value="`<required>` `[optional]`", inline=False)

            await ctx.send(embed=embed)

    @hostrole.command(name="add", description="Add a role to the host roles.")
    async def add(self, ctx, *, role: commands.RoleConverter):
        fail_check = await self.functions.roleCheck(ctx, role)
        if fail_check:
            await self.functions.databaseRemove("global", "roleConfigs", "hostRole", "id", ctx.guild.id, role.id)
            return

        data = await self.functions.databaseAdd("global", "roleConfigs", "hostRole", "id", ctx.guild.id, role.id)
        if not data:
            embed = discord.Embed(description=f":whitealert: {ctx.author.mention} - {role.mention} is already a host role.", color=0xFFFFFF)
            await ctx.reply(embed=embed, mention_author=False)
            return

        embed = discord.Embed(description=f":success: {ctx.author.mention} - {role.mention} is now a host role.", color=0xFFFFFF)
        await ctx.reply(embed=embed, mention_author=False)
#

thats some other cmds

#

remove the @isAdmin() still doing it

sage tendon
stray yarrow
#

but

#

its pretty much if you have a role you want to be able to access commands but dont want to give it the actual permission, e.g, ban member

lapis dock
#

you can use

#

.rtfm has_role

sly karmaBOT
lapis dock
#

.rtfm has_any_role

sly karmaBOT
stray yarrow
#

database for multiple servers but thats not the problem

#
class Config(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.functions = Functions()

    @commands.group(name="hostrole", description="View host role commands.")
    async def hostrole(self, ctx):
        if ctx.invoked_subcommand is None:
            subcommands = [f"`{ctx.prefix}{command.qualified_name} {command.signature}`".strip() for command in self.hostrole.commands]
            subcommands_list = '\n'.join(subcommands)
            embed = discord.Embed(title=f"{ctx.command}".title() + " Commands", description=subcommands_list, colour=0xFFFFFF)
            embed.timestamp = discord.utils.utcnow()

            if any(command.signature for command in self.hostrole.commands):
                embed.add_field(name="Parameters", value="`<required>` `[optional]`", inline=False)

            await ctx.send(embed=embed)

    @hostrole.command(name="add", description="Add a role to the host roles.")
    async def add(self, ctx, *, role: commands.RoleConverter):
        fail_check = await self.functions.roleCheck(ctx, role)
        if fail_check:
            await self.functions.databaseRemove("global", "roleConfigs", "hostRole", "id", ctx.guild.id, role.id)
            return

        data = await self.functions.databaseAdd("global", "roleConfigs", "hostRole", "id", ctx.guild.id, role.id)
        if not data:
            embed = discord.Embed(description=f":whitealert: {ctx.author.mention} - {role.mention} is already a host role.", color=0xFFFFFF)
            await ctx.reply(embed=embed, mention_author=False)
            return

        embed = discord.Embed(description=f":success: {ctx.author.mention} - {role.mention} is now a host role.", color=0xFFFFFF)
        await ctx.reply(embed=embed, mention_author=False)
#

ctx is a required argument that is missing.

#

It's a prefixed group command btw

lapis dock
#

can you send the full error/traceback

stray yarrow
#

thats the error printed off

sage tendon
#

the FULL traceback

stray yarrow
#

ok 2s

#

from what i've noticed its ignoring the self argument

lapis dock
#

is it indented correctly

stray yarrow
#

yep

stray yarrow
lapis dock
#

there should be more in the terminal

#

I want to make sure it is referenceing the right thing

stray yarrow
#

yh

#
<discord.ext.commands.context.Context object at 0x000001DBECC648E0>
Ignoring exception in command hostrole view:
Traceback (most recent call last):
  File "C:\Users\ferne\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\bot.py", line 349, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\ferne\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 1550, in invoke
    await ctx.invoked_subcommand.invoke(ctx)
  File "C:\Users\ferne\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 951, in invoke
    await self.prepare(ctx)
  File "C:\Users\ferne\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 881, in prepare
    await self._parse_arguments(ctx)
  File "C:\Users\ferne\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 783, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "C:\Users\ferne\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 610, in transform
    raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.
stray yarrow
#

like in my bots error log channel it shows:

#
Command raised an exception: AttributeError: 'Context' object has no attribute 'functions'
#

which is what im guessing is referring to:

#
data = await self.functions.databaseFetchResult("global", "roleConfigs", "hostRole", "id", ctx.guild.id)
lapis dock
#

Is your code saved?

#

I would try to restart your IDE

sage tendon
#

it's passing ctx to self

lapis dock
#

Which generally implies that the fucntion is not in the class IE not indented correctly or something else above it is not indented corecctly

stray yarrow
#

everything indented correctly

sage tendon
#

can you just screenshot the code in your IDE

stray yarrow
#

just tested the other commands in the cog

#

all except the command groups worked

lapis dock
#

can you show yout pip list