#Basic Pycord Help

1 messages Β· Page 39 of 1

limber terrace
#

Na wanted to have it different, maybe plun had the solution

grizzled loom
#

hope it's random enough;

I suck at design stuff in general, but had an idea regarding embeds that turned out to appear quite nice.

I did screenshot the background color of my bots avatar (could ofc also be the background color of his banner if that's more suitable), used that to get the colors hex value and finally passed this on as the chosen color for the left stripe.

Looked really need and orderly πŸ™‚

limber terrace
#

Ah yeah, used the same technique but than background layouts became a thing

#

Now its quite.... weird

#

Damn u discord for not lettin us edit the opacity of the color.
Its all webscript anyways

#

But, the side color is fittin the embed color anyways...
Why the heck it got removed by me

grizzled loom
shadow bear
#

can someone refresh me, how do persistent views work again?

#

its been like a year since ive used them

#

I know you need a None timeout and to do something with like add_view on startup

rugged lodgeBOT
#

Here's the persistent example.

errant trout
shadow bear
#

grand, thank you :)

vital bramble
#

I have a strange problem. I don't get most of the autocomplete events from discord? I have everything set up properly in pycord and the api (guild commands) shows that autocomplete is enabled, but I don't get the auto complete interactions...
What is weird too, is that that's mainly the case for only one option, the other works most of the time.
Is this a discord bug or a pycord one? Did anybody have this issue too?

silk oriole
#

if i used autocomplete i'd try to help :(

hybrid tinsel
#

Is ot possible to have interactions like buttons and selects to keep working even after a bot restart?

echo wraith
glossy latch
#

How can i solve unknown interaction error

fresh sierra
#

but it depend what cause that

vital bramble
sage tendon
glossy latch
#

can you help me with this

#
@commands.slash_command(name="cases", description="Get Cases of verification.")
@option("cases", choices=['Member ID', 'Case', 'All'], required=True)
@option("user_id", description="The ID of the member to get cases for", required=False, default=None)
@option("case_number", description="The number of the case to get info for", required=False, default=None)
async def cases(self, ctx: discord.ApplicationContext, cases: str, user_id: int = None, case_number: int = None):
sage tendon
#

how?

#

literally just put the defer as the first line in your command

glossy latch
#

i want to add options to slash command

#

and i get this eror

sage tendon
#

ah

glossy latch
#
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 1.options.0.options.1: Required options must be placed before non-required options```
sage tendon
#

first of all, add type=int to the option decorators for the user ID and case numbers

#

not sure if it picks that up from the function header typehint

fresh sierra
glossy latch
#

like this

@commands.slash_command(name="cases", description="Get Cases of verification.")
    @option("cases", str, choices=['Member ID', 'Case', 'All'], required=True)
    @option("user_id", int, description="The ID of the member to get cases for", required=False, default=None)
    @option("case_number", int, description="The number of the case to get info for", required=False, default=None)
    async def cases(self, ctx: discord.ApplicationContext, cases: str, user_id: int, case_number: int):
#

?

fresh sierra
#

does user_id is a discord ID ?

glossy latch
#

yup

fresh sierra
#

so you should use str and not int, those id are to be as int

#

and after in the code you do user_id = int(user_id)

glossy latch
#

it can be discord.Member ?

sage tendon
#

yes

glossy latch
#

yeah it's better than str

sage tendon
#

but you shouldn't do that because you might wanna get cases for people not in your server anymore

#

i think discord.Member stops working for people not inside the server

fresh sierra
glossy latch
sage tendon
#

yea but if you do discord.Member as the option type, you physically cannot put in user IDs of people not in the server

sage tendon
#

actually i was wrong about that, i just tested it

#

it even somehow (??) works with people not sharing anything with the bot

#

so must be handled properly on discord's side already then

#

so yes, you can use discord.Member

fresh sierra
sage tendon
#

no

fresh sierra
#

yes

sage tendon
#

No.

glossy latch
#

i runned the code and it shows to me the same error

sage tendon
#

I just tested it Luma

fresh sierra
#

if the bot is not in the cache of the bot and not in the guikd

#

it will not appear

sage tendon
#

i picked you, my bot shares NOTHING with you, and i still was able to get your user object

#

try it out

fresh sierra
#

really strange

sage tendon
#

yea as i said, discord must just handle it on its end

sage tendon
sage tendon
sage tendon
#

no, use my ID

fresh sierra
#

oooooooooo

#

u made me learn something new

sage tendon
#

yea its kinda neat

#

but i guess now i need to add more safeguards to make sure that my member options actually only take members of the current server lol

glossy latch
sage tendon
glossy latch
# sage tendon the top part

@commands.slash_command(name="cases", description="Get Cases of verification.")
    @option("cases", str, choices=['Member ID', 'Case', 'All'], required=True)
    @option("user", discord.Member, description="The ID of the member to get cases for", required=False)
    @option("case_number", int, description="The number of the case to get info for", required=False)
    async def cases(self, ctx: discord.ApplicationContext, cases: str, user: discord.Member, case_number: int):

sage tendon
#

are you sure the error comes from that command tho?

#

i think it might actually be because one of your options has the same name as the command itself
can you change the name of the "cases" option

glossy latch
#
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 1.options.0.options.1: Required options must be placed before non-required options
fresh sierra
#

only in the @option

sage tendon
#

that doesnt matter, str is the default anyway

fresh sierra
#

lets try

#

i have a lot of option with the same name

#

and no issue

#

so i think there is an error that remove the @option reading and then it raise that error

#

(i got similare issue with that)

#
    @commands.slash_command(name="cases", description="Get Cases of verification.")
    @option(name="cases", type=str, choices=['Member ID', 'Case', 'All'], required=True)
    @option(name="user", type=discord.Member, description="The ID of the member to get cases for", required=False)
    @option(name="case_number", type=int, description="The number of the case to get info for", required=False)
    async def cases(self, ctx: discord.ApplicationContext, cases: str, user: discord.Member, case_number: int):
#

can you tried that ?

sage tendon
#

whats the difference

fresh sierra
#

just to be sure

#

i added the name= etc etc

sage tendon
#

that doesnt make any difference lol

fresh sierra
#

it can

sage tendon
#

no

#

Because the 2 positional arguments are name and type, in that order

#

i always do it without the kwarg

fresh sierra
#

since i never used type= for choices, that why i asked him to be sure, if its good else we know that not the issue

#

and it take 5s to test

sage tendon
#

works fine in my bot

#

str with options that are strings

glossy latch
#

the command is not visible in the list

#

of slash commands

sage tendon
#

probably because you indented it too far

glossy latch
#

it doesn't shows any eror

sage tendon
#

make sure its on the same level as the other commands, and not more to the right

fresh sierra
#

from where did u import @option ?

glossy latch
sage tendon
#

show again then

fresh sierra
#

?tag past

limber wagonBOT
#

dynoError No tag past found.

fresh sierra
#

?tag paste

limber wagonBOT
#

Please copy and paste your code here. This makes it easier for everyone helping you.

fresh sierra
#

can you put ur whole cog in it, easier

fresh sierra
wide hound
#

how do I install pycord

sage tendon
#

pip install py-cord

wide hound
#

see I thought it was ```python
pip install pycord

sage tendon
#

No, that's a very different package

wide hound
#

?

#

how come

sage tendon
#

the name was taken

wide hound
#

i think my pycord is done

#
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.1/1.1 MB 8.5 MB/s eta 0:00:00
Downloading aiohttp-3.9.5-cp311-cp311-win_amd64.whl (370 kB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 370.8/370.8 kB 11.3 MB/s eta 0:00:00
Downloading aiosignal-1.3.1-py3-none-any.whl (7.6 kB)
Using cached attrs-23.2.0-py3-none-any.whl (60 kB)
Downloading frozenlist-1.4.1-cp311-cp311-win_amd64.whl (50 kB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 50.5/50.5 kB 2.5 MB/s eta 0:00:00
Downloading multidict-6.0.5-cp311-cp311-win_amd64.whl (28 kB)
Downloading yarl-1.9.4-cp311-cp311-win_amd64.whl (76 kB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 76.7/76.7 kB 4.2 MB/s eta 0:00:00
Installing collected packages: multidict, frozenlist, attrs, yarl, aiosignal, aiohttp, py-cord
Successfully installed aiohttp-3.9.5 aiosignal-1.3.1 attrs-23.2.0 frozenlist-1.4.1 multidict-6.0.5 py-cord-2.5.0 yarl-1.9.4```
little cobalt
sage tendon
#

or the website

wide hound
#

which website

sage tendon
#

the pycord website

shell radish
#

any of them

wide hound
little cobalt
#

?

wide hound
#

whys it say 1992

sage tendon
#

that's an oddly specific date lol

sage tendon
wide hound
#

interesting

shell radish
sage tendon
#

i swear to god if it is what i think it is

#

i knew it

echo wraith
#

694249200

#

lol

shell radish
#

:3

#

fine I changed it

arctic oar
#

Is there a way to implement a custom converter?

#

To convert input from bridge commands

#

I have an option with a list of choices, but I'd like it to ignore uppercase

#

specifically for regular commands

sage tendon
#

wdym exactly

arctic oar
#
    @bridge.bridge_command(name="test")
    @bridge.option("category", str, required=True,
                   choices=['Collection', 'Balance', 'Inventory'])
    async def test(self, ctx, category: str):
      ...

With slash commands this works fine, but when using a non slash command you need to type it exactly like "Collection".

#

I would like ti so that a lowercase version works

#

if you input "collection" I would like it to go through

arctic oar
#

?

sage tendon
#

btw you dont need required=True

little cobalt
arctic oar
#
from discord.ext.bridge import AutoShardedBot

bot = AutoShardedBot(
    command_prefix=get_prefix,
    case_insensitive=True,
    intents=intents
)

When I run that command and try lowercase I get
discord.ext.commands.errors.BadArgument

sage tendon
#

how many guilds does your bot have?

slim scroll
#

evening, how is it possible to make slash command groups which are like /group subgroup command?

little cobalt
#

;3

slim scroll
little cobalt
#

what?

slim scroll
#

I mean this mb

little cobalt
#

you already got anything for it at that one screenshot

frail basin
#

Any way to limit discord.ui.user_select to certain members?

little cobalt
#

no

frail basin
#

I guess I'll iter through the guild members then and filter it

little cobalt
#

you could use a normal select menu but it got a limit of 25 and only strings

frail basin
#

Well there goes my plan then

sage tendon
#

UI components are neglected af by discord

glossy latch
harsh bloom
#
import discord

import os

bot = discord.Bot()
token = os.environ.get('TOKEN_DISCORD')

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

@bot.slash_command(name="hello", description="say hello to the bot")
async def hello(ctx: discord.ApplicationContext):
    await ctx.respond("Hey!")

bot.run(token)

Basic code from the docs, but the slash commands are not showing up. What could be the reason?

FIXED
just re-invite the bot

#

but why did this happen?

shell radish
sly karmaBOT
#

Tag not found.

fresh sierra
#

.tag slashnotshowing

sly karmaBOT
#

Tag not found.

Did you mean...
slashnoshow
slashcmdnoshow
slash no show

fresh sierra
#

.tag shashnoshow

sly karmaBOT
#

Tag not found.

Did you mean...
slashnoshow
slashcmdnoshow
slash no show

fresh sierra
#

.tag slashnoshow

sly karmaBOT
#

Application Commands Not Showing Up?

  • Refresh Discord by restarting or pressing ctrl+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.
harsh bloom
#

very common issue

sage tendon
#

No

#

It really isnt

#

I've been here for long enough and seen enough people to judge that as one of the issues that happens rather rarely

#

you're just biased because it's the issue you had and were probably annoyed with / spent a lot of time trying to fix

atomic fern
#

how to add icon to an embed's field? like this, add_field doesn't have emoji parameters

little cobalt
lofty parcel
fresh sierra
little cobalt
fresh sierra
#

And kbm small

#
  • autocorrect
#
  • im finding excuse
little cobalt
#

lul

vital bramble
#

When I send an ephemeral response, I get a discord.WebhookMessage object back, right? I can use this object to update the ephemeral message. Does this webhook have a 15 min timeout like interactions have? Also, how would I save this in e.g. a database and reconstruct it again? What data would I need to save for that?

cobalt comet
#

in ui components, how to add new buttons/select menu in specific row when editing the message from another button?

shell radish
#

you can specify the row with row = number in the component decorator

cobalt comet
shell radish
#

It depends on how you are adding the button to the message

cobalt comet
#

ok i got an idea, i have to create another ui.View and edit the message to that ui.View right? lol

rugged lodgeBOT
shell radish
#

is this what you were looking for?

cobalt comet
#

so remove_item exists aswell?

rugged lodgeBOT
cobalt comet
#

perfect, tysm

outer trout
#

Is it possible to finish a method after await interaction.response.defer() without sending a followup message?

I have the problem that await interaction.response.defer() forces me to send a followup message and not defering leads to discord showing an error message since I dont want to send a response at all

sage tendon
#

why do you defer at all then?

#

you also need to send a response without deferring tho so what

fresh sierra
#

And in my memory it was working

sage tendon
#

why lol

fresh sierra
#

To answer a response without sending message

sage tendon
#

but why the try

outer trout
fresh sierra
#

Without try except it will raise an error can’t say empty message

fresh sierra
sage tendon
#

cant you also just edit the interaction message but change nothing?

#

But wouldn't a clear indication that whatever the bot is doing is done be better?

fresh sierra
sage tendon
#

but its a valid response to the interaction

#

so it wouldnt show an error

fresh sierra
#

Yes but their will not have the thinking thing that he needs

sage tendon
#

defer, then edit lol

fresh sierra
#

How ?

sage tendon
#

cant you just do that lol

#

i hate interactions ngl

fresh sierra
#

Nope after defer you can’t use interaction.response

sage tendon
#

yea, i really hate interactions

shell radish
#

why not just send an ephemeral message saying "Success" or something?

fresh sierra
#

Idk for his thing

#

But for example in my experience it was for the Tetris game

sage tendon
#

if the loading circle just disappeared i'd think "ok did it work now or what"

shell radish
fresh sierra
#

And for Tetris I wasn’t wanting each time a message or that will be unplayable

outer trout
fresh sierra
#

Because there was already a loop

#

To edit the message for the piece moving down

fresh sierra
wary silo
#

did bot send pics using url with file changed? i always post like this recently
here's the way i used for few years, but not work recently

    @commands.command()
    async def test(self, ctx: commands.Context):
        file = discord.File(io.BytesIO(requests.get('https://imgur.com/...').content), 'test.png')
        await ctx.send(file=file)
sage tendon
#

if you download the pic, does it work properly?

wary silo
#

now not lol, i remember it was ok. it says {"data":{"error":"Imgur is temporarily over capacity. Please try again later."},"success":false,"status":403}
so it's not changed, got it, thanks!

errant trout
#

imgur api has been pretty unreliable

sage tendon
#

love how its a 403 lol

#

makes no sense

#

should be a 503 if anything

wary silo
sage tendon
#

Why don't you just send the imgur link directly

wary silo
#

i feel ugly to show the url in the msg lol, it shows url if sends url with other text

sage tendon
#

doesn't it hide it for actual direct image urls that end in a file ending?

#

test

#

yea it does

wary silo
#

yes if only send the url

#

but don't with other text

#

i want it togetherπŸ₯Ή

sage tendon
#

damn
well, you can only listen for 403s on imgurs side then and retry or abort then i guess

sage tendon
sage tendon
#

lol

wary lava
#

how to change the bot avatar for a perticular server?

sage tendon
#

not possible

wary lava
red mist
#

Use webhooks

low trench
#

when using the tasks loop decorator, how is the interval time calculated from the entered seconds minutes & hours. Are they all just summed together into a timedelta object?

#

What happens if seconds > 60 and minutes is also entered?

#

would be nice if devs could enter a timedelta object themselves

sage tendon
#

I mean, typically you don't change it often or have crazy intervals
Usually it's every X seconds or minutes or hours
And you typically only set it once

low trench
manic glen
#

One quick question if someone uses a command X which has a cooldown enabled, can using different commands let's say Y can resets the cooldown for command X ?

sage tendon
#

Not that i know of, no

manic glen
#

Ok, so we have to reset the cooldown in the same command?

sage tendon
#

think so yes

manic glen
#

Ok thanks πŸ‘πŸΌ

stable yarrow
wary silo
#

i don't think so

modern trail
#

little confused, if i want to get the author of a message that someone replied to, do I have to do this?

class Foo(Cog):
    ...

    @Cog.listener()
    async def on_message(self, message: Message) -> None:
        original_message_ref = message.reference
        original_message_id = original_message_ref.message_id
        original_message = self.bot.get_message(original_message_id)
        original_author = original_message.author

because this seems really convoluted

sage tendon
#
if message.reference
    author = self.bot.get_message(message.reference.message_id).author
modern trail
#

that's cleaner certainly. I guess the answer is yes then

dreamy prawn
#

Hey guys, new to discord bot making as a whole but not new to python. For some reason I cant get Discord to display my new slash commands I added, or edited since the first run of hte bot on the server.

Basically, What i see for slash options are the ones that were present in the code when I first added the bot to the server.

sage tendon
#

restart discord

modern trail
#

self.bot.get_message is returning None for the referenced message id. Is that because it isn't cached or something? Do i need to get the message object another way?

shell radish
#

you can fetch it from the channel object (await channel.fetch_message(message_id))

modern trail
#

i see, i'll try that, thanks

sage tendon
#

you should always try to get first though, fetching should be done as little as possible

modern trail
#

is there any situation in which the get_message would succeed?

wide hound
#

how do I add app commands

sage tendon
wide hound
sage tendon
wide hound
#

like the little menu you get to do a command

sage tendon
wide hound
shell radish
sage tendon
#

Yes, but what would you say is an application command?

A slash command? A user command? A message command?

#

could be any of those

shell radish
shell radish
sage tendon
#

Yea, but i still needed the exact command they want :)
And application commands might be the grouped name, but they're not a thing by themselves

#

if you get me

modern trail
#

well i guess i'll keep the get_message and fall back on fetch_message if/when it fails

shell radish
sage tendon
fleet cedar
#

Isn’t there a get_or_fetch thing too?

shell radish
#

client.get and messageable.fetch

fleet cedar
#

Ah makes sense

dreamy prawn
wide hound
#

i keep on getting the "unknown integration" error when trying to run my bot

sage tendon
#

can you show the full error

wide hound
#

ive got another issue

#

ive pasted my code and the @bot.commands() thing isnt showing up in the dropdown menu

sage tendon
#

one after the other

wide hound
#
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True  # Enable the members intent

bot = commands.Bot(command_prefix='/', intents=intents)

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')
    print(f'Bot ID: {bot.user.id}')

@bot.command(name='ban_nuke', help='Ban all members who join in rapid succession.')
async def ban_nuke(ctx):
    # Check if the author of the command has the necessary permissions
    if not ctx.author.guild_permissions.ban_members:
        await ctx.send("You don't have permission to use this command.")
        return

    # Get all members who have joined the server recently
    recent_members = ctx.guild.members

    # Define the threshold for rapid succession
    threshold = 5  # Change this value according to your server's needs

    # Check for rapid succession of member joins
    if len(recent_members) > threshold:
        for member in recent_members:
            try:
                await member.ban(reason="Rapid succession of member joins detected (anti-nuke).")
            except discord.Forbidden:
                print(f"Failed to ban member {member.name}#{member.discriminator} (ID: {member.id})")
        await ctx.send(f"Banned {len(recent_members)} members for rapid succession of joins.")
    else:
        await ctx.send("No rapid succession of member joins detected.")

bot.run('NUHUH')
sage tendon
#

I need to see the error lol

#

also wow that code is old, still using discrims

wide hound
edgy nest
#

try reloading your client

#

ctrl+r

#

otherwide re-add the bot

wide hound
#

ok

sage tendon
#

also i just skimmed over the code but.. this would just literally count everyone in the server as "recent member"?

sage tendon
#

So, unless I'm missing something, do not run that code lol

wide hound
sage tendon
#

yea but if it was to work it would ban everyone in the server

wide hound
#

no commands are even popping up

sage tendon
sage tendon
#

read your code

little cobalt
wide hound
little cobalt
#

what?

wide hound
sage tendon
#

If you want actual / commands, you should use discord.Bot, and need to use @bot.slash_command

#

dude for real why

little cobalt
wide hound
sage tendon
sage tendon
#

Also...
is that code from ChatGPT

#

its setting off my ai bells lol

wide hound
sage tendon
#

because it very much feels like it is

little cobalt
wide hound
#

my brother gave the code to me

#

said its for my anti nuke bot

sage tendon
#

genuine advice, dont take more code from your brother

#

he's either incapable of programming or wants to troll you

wide hound
#

i didnt even read the code i will now

sage tendon
#

running code blindly is a mistake you make as often as it goes well, and only that often

wide hound
#

wel

#

i see where i went wrong

wide hound
sage tendon
#

yes

#

a function like that one requires a lot more code to actually handle the recently-joined-members tracking

#

i still think its chatgpt tho
all the comments (especially those), the use of old principles (discrims), the clearly completely wrong logic inside the code

wide hound
#

i made a simple latency ping

import discord
from discord.ext import commands

bot = commands.Bot() 

@bot.command(description="Sends the bot's latency.")
async def ping(ctx):
    await ctx.respond(f"Pong! Latency is {bot.latency}")

@bot.event
async def on_ready():  
    print(f"Logged in as {bot.user}, Application ID: {bot.user.id}")
sage tendon
#

that's still a prefix command

wide hound
#

how

sage tendon
#

because it is lol

wide hound
#

???

#

wait

sage tendon
#

a slash command is bot.slash_command when you use commands.Bot

#

again, if you only want slash commands, use discord.Bot

wide hound
#
import discord
from discord.ext import commands

bot = discord.Bot() 

@bot.slash_command(description="Sends the bot's latency.")
async def ping(ctx):
    await ctx.respond(f"Pong! Latency is {bot.latency}")

@bot.event
async def on_ready():  
    print(f"Logged in as {bot.user}, Application ID: {bot.user.id}")
sage tendon
#

yea

little cobalt
#

.tias

sly karmaBOT
wide hound
#

tias

sage tendon
#

lol

wide hound
#

it did not work

sage tendon
#

show errors, etc

#

and restart discord after running your bot with that code

wide hound
#

ty it works

#

now I have to learn how to use embed

sage tendon
#

use the docs, always

wide hound
#
embed=discord.Embed(*insert
embed
stuff
here)
little cobalt
#

did discord changed something at the slash commands?

sage tendon
#

like what

little cobalt
#

I cannot get my command builder to add descriptions to it

wide hound
#
import discord
from discord.colour import Colour
from discord.ext import commands

bot = discord.Bot() 

@bot.slash_command(description="Sends the bot's latency.")
async def ping(ctx):
    embed = discord.Embed(
    title="Pong!",
        description="NukeGuard's latency is {bot.latency}ms.",
        colour=discord.Colour.blurple(),
    )
    embed.set_author(name="NukeGuard Team", icon_url="https://i.imgur.com/OVBw9iz.png")
    embed.set_thumbnail(url="https://i.imgur.com/OVBw9iz.png")
@bot.event
async def on_ready():
    print(f"Logged in as {bot.user}, Application ID: {bot.user.id}.")
edgy nest
#

you need to respond

wide hound
edgy nest
#

same as you did earlier, but with the embed kwarg

wide hound
edgy nest
#

await ctx.respond(embed=embed)

wide hound
#

oh

#

right

edgy nest
#

embed is a kwarg (keyword argument) because you're referring to it with a keyword

wide hound
#

where do i put it tho

#

inside the discord.Embed(?

edgy nest
#

right at the end, after your embed is constructed

#

so it can refer to the embed

little cobalt
#

@wide hound that is not at beeing rude or anything but do you know basic Python?

edgy nest
#

we have an idea of the answer already but sure

wide hound
#

not really no

sage tendon
#

your name already gives it away tbh

wide hound
#

i saw alot of discord bots and I was like "cool" so i kinda just

#

got into coding

edgy nest
#

i was the same way

#

i just used google a lot

sage tendon
#

sort of same

wide hound
little cobalt
#

I did some simple projects before

wide hound
#

"why do i have traceback most recent call last error?!?!?!?!?!?!?!?!?"

little cobalt
#

like a yt to mp3 converter

wide hound
#

in python?

little cobalt
sage tendon
#

show the full traceback

wide hound
#

the best ive done so far in python is a calculator but 1 divided by 0 crashes the program

edgy nest
wide hound
#

my discord bot is quite meh

edgy nest
#

someone should make a graphing calculator on a discord bot

little cobalt
edgy nest
#

no like

#

literally just a ti84 recreation

#

with all the stock functions

little cobalt
#

uh

wide hound
#

is this normal

edgy nest
#

you forgot to make it an f-string

#

you just put f before the string

#

so it will run the code in the curly brackets

wide hound
#

description=f"NukeGuard's latency is {bot.latency}ms.",

#

or before that

edgy nest
#

yup

#

thats good

wide hound
#

ok

#

it works ty

edgy nest
#

np

#

if you need any more help, just ask

wide hound
#

ok i will

dreamy prawn
#

Ive got the bot to send the response to the slash command, Is there an easy way (didnt see it in documentation) to replace that message with the response instead of a separate message?

little cobalt
#

.edit_message(content="")

sage tendon
edgy nest
dreamy prawn
# sage tendon just out of curiosity, what is your bot for?

Im part of a group that archive and preserve old UK school software from a specific company (sounds dull, but they had full custom networks and everything, were very big back in the day) and this is a proof of concept for something we are working on to let others experience some of the software a little easier than before. A lot of the software is not really out there anywhere else.

austere plank
#

Anyone know why my Bot cant post in Threads? I have a command with -(text)channel and -text as args. But if the channel is a thread it keeps saying "{channelname} not found"

#

Even if i mention the bot in there (the thread) and it's added it doesn't work to find it

sage tendon
#

show your code

austere plank
lofty parcel
#

You're already typehinting discord.TextChannel, the library is already converting the argument to a TextChannel object

tidal estuary
#

Does await bot.sync_commands(force=True) have an issue with 25 or more commands? Not sure why I'm getting discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form BodyIn 1.options: Must be 25 or fewer in length. on command registration

#

Aha, for future ctrl + f-ers, if you copy-paste the code to register a slashcommandgroup and you leave the name the same as another slashcommandgroup, it will throw the above error

sage tendon
wide hound
#

does anyone know what is wrong with my code

@bot.slash_command(description="A secret vault for keeping items. Do not enter your discord password.")
async def secret_vault_password(ctx: discord.ApplicationContext):
    """Shows an example of a modal dialog being invoked from a slash command."""
    modal = Password(title="Enter your **VAULT** password/passkey")
    await ctx.send_modal(modal)
#

wait

#

istg if its what i think it is

#

bruh

sage tendon
#

well?

wide hound
#

nevermind

#

python

bot.slash_command(description="A secret vault for keeping items. Do not enter your discord password.")
async def password(ctx: discord.ApplicationContext):
        """Shows an example of a modal dialog being invoked from a slash command."""
async def ctx(ctx):
        await ctx.respond("Hello!")
modal = password(ctx, title="Enter your **VAULT** password/passkey")await ctx.send_modal(modal)
wide hound
sage tendon
errant trout
errant trout
#

Consider using autocomplete instead

open hearth
#

hi, can someone tell me what im doing wrong?

    @other.command(name="test1", description="big black balls.", options=[discord.Option(name="image", input_type=discord.Attachment, description="A file to attach to the message", required=True)])
    async def test1(self, ctx: discord.ApplicationContext, image: discord.Attachment):
        await ctx.respond("test")
quartz umbra
#

Hi, simple question here- Is there a way I can store roles for future use? i.e., The owner configures the bot to give a certain role when achieving x level. I know this is possible, i've done it before, I just forget how

open hearth
#

without options it works idk whats goin on

sage tendon
#
@other.command(name="test1", description="big black balls.")
@discord.option("image", discord.Attachment, description="A file to attach to the message")
    async def test1(self, ctx: discord.ApplicationContext, image: discord.Attachment):
        await ctx.respond("test")

This is how its usually done

#

that, or with a discord.Option typehint at the parameter itself but i hate that

quartz umbra
sage tendon
#

yes

quartz umbra
#

ok

sage tendon
#

sounds like the job for a database

quartz umbra
#

and how to retrieve the roles again?

sage tendon
#

using a db library like mysql

sage tendon
quartz umbra
sage tendon
#

and ideally you use an async db library

#

I know

quartz umbra
#

how can I reconstruct a role from a role ID?

#

can you link docs? I couldn't find them

sage tendon
quartz umbra
#

thanks a lot, any recommendations for an async db library? Does sqlite3 work?

sage tendon
#

mysql's library has an async part in it

#

but if you wanna use sqlite there's 100% an async version for that too

quartz umbra
#

alright, I'll go look for that then

#

just 1 quick one aswell, how to add a role to a user?

#

nvm

sage tendon
#

docs are your friend

quartz umbra
#

thanks a lot

sage tendon
#

np
but a role add would most likely be either in the guild, the role, or the member
so only 3 major places you need to check ;3

quartz umbra
#

alright

wide hound
#

ill try that

quartz umbra
#

Hi, can someone see what the sql error is? python await db.execute( f""" INSERT INTO roles_list( Guild_ID, Admin_ID, Tester_ID, LT5_ID, HT5_ID, LT4_ID, HT4_ID, LT3_ID, HT3_ID, LT2_ID, HT2_ID, LT1_ID, HT1_ID) VALUES ({ctx.guild_id},{ids[0]}, {ids[1]}, {ids[2]}, {ids[3]}, {ids[4]}, {ids[5]}, {ids[6]}, {ids[7]}, {ids[8]}, {ids[9]}, {ids[10]}, {ids[11]},) """ )

sage tendon
#

well, what does it tell you

open hearth
#

how do i fix random unknown interaction errors?

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
#

when using await ctx.respond

fresh sierra
#

it can be because it takes more than 3s so use defer will be efficient

austere plank
fresh sierra
# quartz umbra Hi, can someone see what the sql error is? ```python await db.execute( f...

idk but im doing something like that, if that can help you

await db.execute(
    """
    INSERT INTO roles_list(Guild_ID, Admin_ID, Tester_ID, LT5_ID, HT5_ID, LT4_ID, HT4_ID, LT3_ID, HT3_ID, LT2_ID, HT2_ID, LT1_ID, HT1_ID)
    VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
    """,
    (ctx.guild_id, ids[0], ids[1], ids[2], ids[3], ids[4], ids[5], ids[6], ids[7], ids[8], ids[9], ids[10], ids[11])
)

#

it can be easier to see which one is which one

fresh sierra
#
  async def say(self,ctx, out : discord.TextChannel, *, msg):
      await out.send(msg)
#

will be more logical since the out is already a discord channel object

quartz umbra
wide hound
#
@bot.slash_command()
async def secret_vault(ctx):
    """A secret vault for storing information."""
    view = discord.ui.View()  
    view.add_item(discord.ui.Button(label="Enter your secret vault password"))

    message_content = "This modal is for entering your secret vault password."
    message = await ctx.send(message_content, view=view)
    await view.wait()
sage tendon
#

don't do it like that

#

make a proper view subclass

wide hound
#

how

sage tendon
#

check the guide

wide hound
#

it doesn't specify in the docs when I last read it

sage tendon
#

it's all in the guide

wide hound
#

can you send the link

sage tendon
#

pycord website > guide

wide hound
#

oh

#

ok

sage tendon
#

and then UI components

wide hound
#

ive read the docs and I still get the same erroras before

sage tendon
#

did you make a proper view subclass?

#

and use that in your command?

wide hound
#

it doesnt specify that in the guide

sage tendon
#

Oh yes it does

wide hound
#

so no

wide hound
sage tendon
#

in the UI components part lol

wide hound
#

oh

#

i was looking at the sending modals through application thing

#
class MyView(discord.ui.View):
        @discord.ui.button(label="Send Modal")
        async def button_callback(self, button, interaction):
            await interaction.response.send_modal(MyModal(title="Modal via Button"))

    @bot.slash_command()
    async def send_modal(ctx):
        await ctx.respond(view=MyView())
#

now the slash command isnt showing up at all

glossy tide
#

how have 2 embeds in one message?

sage tendon
#

the view class is entirely separate from your command

#

please check the guide

sage tendon
austere plank
#

Is it just not possible like that to send to a thread because of the out : discord.TextChannel ?

quartz umbra
#

hi, say I have an argument for a command which is text, how can I make it so that the argument MUST be one of a given fixed set? eg, it has to be a fruit out of the list [apple, banana, orange] ?

sage tendon
#

use the choices= kwarg

quartz umbra
#

is that even possible?

quartz umbra
sage tendon
#

show the code of your command / the options

quartz umbra
#

something like this i want, if you understand:py @bot.slash_command( guild_ids=guild_ids, description="[Tier Tester Only command] - Award a tier to a player" ) async def giverank(ctx, args=[apple, banana, oranage]): pass

sage tendon
#

well I always recommend using the decorator
so
discord.option("optionname", str, choices=["choice1", "choice2"])

sage tendon
#

well yes but that's not how it works

quartz umbra
sage tendon
#

yea

quartz umbra
#

in that decorator, what does "str" mean?

sage tendon
#

the type of the option

#

you can only have choices for str and int and float options I think
or even just string

quartz umbra
sage tendon
#

no

#

it's still a string option lol

quartz umbra
#

OHhhhhh like the type

#

mb

sage tendon
#

"optionname" is the option name, and also the parameter it binds to

quartz umbra
#

the dtype

#

mb

sage tendon
#

you can override it but there's really no need

quartz umbra
#

thanks for the help

sage tendon
#

np

glossy tide
sage tendon
#

embeds

glossy tide
#

oh thanks, it works xD

quartz umbra
#

What is an embed field?

#

what do they look like?

sage tendon
#

make one and see how it looks

quartz umbra
#

alr

austere plank
#
async def say(self,ctx, out: discord.abc.GuildChannel, *, msg):
      channels_id = out.id
      channel_or_thread = ctx.guild.get_channel_or_thread(channels_id)
      print(type(channel_or_thread))

      if channel_or_thread is None:
        print("Channel oder Thread wurde nicht gefunden!")
        return

      print(channel_or_thread)
      print(channels_id)

      if isinstance(channel_or_thread, discord.Thread):
          await channel_or_thread.send(msg)
          print("Ist Thread!")
      elif isinstance(channel_or_thread, discord.TextChannel):
          await channel_or_thread.send(msg)
          print("Ist Textkanal!")
      else:
          print("Kein gΓΌltiger Textkanal oder Thread!")

Still not able to post in text channels and threads. Even with all the prints if it comes to a actual thread it doesnt print anything lol.
Has anyone a function like that for their bot and could help me out?

quartz umbra
#

how can I get the user who sent a command?

sage tendon
#

ctx.author

#

the docs are your friend, for this too :)

quartz umbra
#

i thought it would be sender

#

so i didn't find nothing lol

sage tendon
#

well, check the ApplicationContext class

#

that's what ctx is in slash commands

quartz umbra
#

now how do I get the bot's icon because the docs says that bot.user is the bot's client when logging in and Client also has a .user with the same message?

#

what dtype is bot.user?

sage tendon
#

discord.User lol

quartz umbra
#

damn it why does that have to say Client then? when they're 2 seperate thing

sage tendon
#

show?

quartz umbra
#

property user
Represents the connected client. None if not logged in.

#

its confusing

sage tendon
#

meh, I mean it makes sense

quartz umbra
#

ig

main hearth
#

Hi guys. How send modal after ctx.respond?

sage tendon
#

not sure if that's possible
what's your plan with that command

little cobalt
main hearth
main hearth
sage tendon
#

make a button that then triggers the modal

#

that's how I'd do it

main hearth
#

That is, interaction with UI components generates a new interaction?

sage tendon
#

yes

#

it's in part to e.g prevent modal spam
so you can't spam the user with inescapable modals etc

lean garnet
#

Hi, how to remove a timeout using pycord ?

fresh sierra
sage tendon
#

i think its just member.edit(communication_disabled_until=None)

fresh sierra
#

And then answer the interaction

sage tendon
#

communication_disabled_until=None*

lean garnet
#

sorry i forgot to check the documentation after checkung the guide

#

it's remove_timeout

sage tendon
#

ah, or that

sage tendon
fresh sierra
sage tendon
austere plank
#

how do you pass a message id for an arg in a slash command? I try to convert all my prefix commands to slash but now i know why i skipped it the last time lol. It wont take message_id : int as arg. Well it takes it but i cant pass it

sage tendon
#

you need to use str as the type

#

IDs are too long for the length of integer discord allows

austere plank
shell radish
#

you might want to consider message_commands

quartz umbra
#

I think I'm doing something stupid here: role = await ctx.guild.get_role(rank_id)
Why do I get TypeError: object Role can't be used in 'await' expression

little cobalt
quartz umbra
#

how might I approach resolving this?

shell radish
little cobalt
quartz umbra
#

so i have another silly error: channel = await bot.get_channel(announcement_channel_id)

sage tendon
#

that aint an error

quartz umbra
#

TypeError: object TextChannel can't be used in 'await' expression

sage tendon
#

well, exact same thing there

lean garnet
#

Hello again, is it possible to make an image option for slash commands ?

quartz umbra
#

remove it?

sage tendon
#

you are awaiting a non-async function

quartz umbra
#

alright

shell radish
#

You can add an internal check to validate the file information and inform the user that the information they uploaded was invalid

lean garnet
#

thanks, i put this in the option type ?

shell radish
lean garnet
#

i just dit it, that was a question to be sure i was right

#

thanks !

sage tendon
#

discord.Attachment is shorter btw

#

and achieves the same result

shell radish
#

it’s a matter of preference

sage tendon
#

sure, just wanted to show them another possibility

#

also, required is true by default, you dont have to explicitly pass it

glossy tide
#

how i have two "view" in one message? Example:

views=[Buttons(), Dropdown()]

or

view=[Buttons(), Dropdown()]

doesn't work

edgy nest
#

you can only have one view

shell radish
glossy tide
shell radish
glossy tide
shell radish
#

yes

glossy tide
#

Okay πŸ‘

shell radish
glossy tide
#

oh I think I know why when I tried that it didn't work, I forgot to put row πŸ˜…
(I already tried to put everything in a view)

glossy tide
deft kestrel
#

there's any limitation of this options? like max 100 options

deft kestrel
errant trout
#

Multiple selects

#

Or paginate them I guess

deft kestrel
errant trout
#

(Not an official feature, just using buttons to make up pages; see ext.pages)

wary saffron
#

Hello all, how can I add slash commands to a slash command group?

rugged lodgeBOT
#

Here's the slash cog groups example.

errant trout
#

(basically @group.command, where group is the group's variable)

wary saffron
#

Ok thx, I'll run it and see if it works

wary saffron
wide hound
errant trout
wary saffron
wide hound
wary saffron
wide hound
wary saffron
#

pkg install py-cord ?

wide hound
#

shell
pip uninstall discord.py

then:
shell
pip install py-cord

#

wait

#

nvm

#

what device are you coding from

wary saffron
#

an android phone

errant trout
#

just the pip commands are enough

wide hound
#

does pip work on android

wary saffron
#

I think so

wide hound
#

do that

errant trout
#

they're using python so it's probably fine Β―_(ツ)_/Β―

wary saffron
#

on termux I think I used pkg or pip, not sure which

errant trout
#

just try pip then

wary saffron
#

It gave me this error now

#

Oh wait

#

Forgot to do shell

#

No wait

wide hound
#

uh oh

wary saffron
wide hound
#

same error I encountered when trying to install arcade

wary saffron
#

Odd

errant trout
#

what does pip list show

wary saffron
errant trout
#

what about python -m pip list

wary saffron
#

Same thing

errant trout
#

can you exit the shell mode so it shows the green file path again instead

wary saffron
#

like in cd storage?

errant trout
#

cd to your bot's main path

wary saffron
#

oo ok

errant trout
#

then after you're in the path run you pip stuff

wary saffron
errant trout
#

hm

#

can you show the folders? ls

wary saffron
errant trout
#

hmmm

#

what shows when you type python

wary saffron
errant trout
#

it's odd that your main.py file makes it past the first line...

wary saffron
#

yeah idk how lol

#

it even ran before

errant trout
#

did you change something to make it stop running?

wary saffron
#

yeah I added a lot of code

errant trout
#

oh wait that's the issue lol

#

in the very first screenshot, it uses python 3.8

wary saffron
#

oh

errant trout
#

but just now you're on python 3.11

wary saffron
#

oh how do I fix thay

errant trout
#

well... the odd thing is that you used the same command

#

and it ended up with two different versions

#

what if you do python bot.py now

wary saffron
errant trout
#

i mean after exiting python

wary saffron
#

Oh woops

#

how do i exit python lol

errant trout
#

ctrl+z or probably exit

#

ah, on linux it's ctrl+D or exit()

wary saffron
errant trout
#

ok we're getting somewhere

wary saffron
#

Yay :3

errant trout
#

can you try typing python3.8

wary saffron
errant trout
#

no space

wary saffron
errant trout
#

ok good

#

now instead of pip, we use python3.8 -m pip

#

so try python3.8 -m pip install py-cord

wary saffron
#

oo ok

errant trout
#

and if that works, python3.8 bot.py

wary saffron
errant trout
#

exit() first

wary saffron
#

Right

#

Oo it worked

errant trout
#

eyyyy

wary saffron
#

It ran all the way til line 104

errant trout
#

i think ideally you uninstall 3.11 so 3.8 can be the default, but this should be fine for now

wary saffron
#

ok

#

sorry i guess my friend was helping me with the discord.py code idk how to change this

errant trout
#

setchannel should be a command

wary saffron
#

ohhh

#

It is here

errant trout
#

it should be @misc.command()

wary saffron
#

Oo

errant trout
#

that's from dpy, unneeded

wary saffron
#

Ooh ok

#

Ok it's online :3

errant trout
#

nice

wary saffron
#

None of the commands show up

errant trout
#

do you perhaps have an on_connect?

wary saffron
#

Don't think so

#

Nope

errant trout
#

then,

  1. at what point are you running bot.run
  2. what's in your on_ready
wary saffron
shell radish
errant trout
#

probably

wary saffron
#

Sure hold on

rugged lodgeBOT
errant trout
#

oh wait i see

wary saffron
#

oo

errant trout
#

oops, discord.SlashCommandGroup is when you're using cogs

wary saffron
#

cogs?

errant trout
#

for regular bots, it should be client.create_group

wary saffron
#

Yeah it works now

#

Btw do you have a guide on how to restrict a bot only to talk in certain channels?

errant trout
#

do you mean restrict commands?

wary saffron
#

Yep

errant trout
#

there's two main ways

  • channel permission Use Application Commands
  • guild settings > integrations > you can set channels and roles here for the entire bot, or specific commands
#

that assumes you can edit permissions and such; if you mean on the bot's side, you can write a custom check

wary saffron
#

ooh which one would you recommend? I'm looking for something like
User: /restrict_to (channel1, channel2)

errant trout
#

hm, what's your end goal? you want specific users to be restricted to specific channels?

wary saffron
#

Hmm, I want an option for anyone with the manage bots permission role in a server to be able to restrict the bot to their own #botspam for example

errant trout
#

i guess there's two sides to this; the matter of hiding commands is completely on discord's end, you can't toggle it from the bot, so it comes down to an internal check

#

so i'd recommend using a db or whatever to save a config that checks if the bot is locked to a channel

#

then write a check as i linked above

#

you can either apply that check to individual commands, or enable a global bot_check

wary saffron
#

Yes I want a global bot check

wary saffron
#

Thanks :D

#

Okay I tried messing around with it and I don't know how to implement it

errant trout
#

what's the issue

wary saffron
#

I don't understand it at all

errant trout
#

so here's the example py @bot.check def check_commands(ctx): return ctx.command.qualified_name in allowed_commandsit uses bot, but in your instance it'd be client
this code will run on every command; if it returns True, then it's allowed to run

#

so in your example, let's say you have some sort of config file that contains a json of userid: channelid json { "242367619431268353": 1132206148309749830, }from what you described, you want something like

  • if the user ID is not in this file, they can use the command
  • if the user ID is in this file, if the channel id matches they can use the command
  • if neither of the above are true, they can't use the command
#

(i'm just guessing, perhaps you want to test it works at all with a more basic condition)

wary saffron
#

Yeah πŸ˜“

#

I need help with setting up the actual /restrict_to command

errant trout
#

well that's a matter of deciding how you want to save your data

#

ideally using some database library

wary saffron
#

okay

errant trout
#

when it comes to the actual slash command, just make the option types discord.Member and discord.TextChannel

wary saffron
#

Ooo

#

and ctx?

errant trout
#

ctx is just ctx

#

you don't need to typehint it

#

(but if you want to, it's discord.ApplicationContext)

wary saffron
#

oh how do I check if the user has the manage bots permission? πŸ˜“

errant trout
#

i assume you mean manage_server? or perhaps manage_webhooks

wary saffron
#

ok I'll try with manage_server

errant trout
#

oh forgot it was renamed

wary saffron
#

Ooo

errant trout
#

all the guild-wide perms are on ctx.author.guild_permissions

wary saffron
#

Like this or?

shell radish
#

and if for some reason author doesn't exist, ctx.interaction.permissions as well

lofty parcel
# wary saffron Like this or?

If this is supposed to be the check function for Bot.check, no, not really

wary saffron
#

It's not, it's supposed to be the command that uses Bot.check

lofty parcel
#

You create a bot check. It just gets applied to all commands.

#

You don't apply it to a command / the command callback doesn't call it.

#

Either way, it's wrong.

wary saffron
#

It's not the bot check to see if the bot is restricted, it's the command to restrict the bot. Hope that makes sense πŸ˜“

lofty parcel
#

Yes, I know what you mean.

#

Let's. Let's go step by step.

#
  1. You have the restrict_to command. Which only users with the manage server permissions should be able to use.
wary saffron
#

Yep

lofty parcel
#
  1. You have the other X commands which should be restricted in usage by the channels set in the mentioned command.
wary saffron
#

All of them except for a dif command called /unrestrict

lofty parcel
#

So restrict_to and unrestrict shouldn't be affected by that setting.

wary saffron
#

Yep

lofty parcel
#

OK, where are you storing such setting?

#

The channels the user sets.

wary saffron
#

Haven't stored it yet but maybe a list called restricted_channels

lofty parcel
#

That will reset on every bot restart.

wary saffron
#

ohhh

#

makes sense

lofty parcel
#

Simplest way is a json file.

#

Do you know how to store and fetch stuff from a json file?

wary saffron
#

Not at all

lofty parcel
#

Great, you will google how to do that.

wary saffron
#

Okay

#

Okay it's telling me to use JSON.parse but I don't know how to specify where to parse it

lofty parcel
#

Is the bot going to be global?

wary saffron
#

wdym

lofty parcel
#

Like anyone can add your bot and specify their own channels

wary saffron
#

Yes

lofty parcel
#

So you need to store config on a guild basis.

wary saffron
#

Yep

lofty parcel
#

Well, I'd tell you to learn actual real databases cause json files aren't meant for bots, so...

#

.nojson

sly karmaBOT
#

JSON is a convenient and easy-to-read data storage protocol that's widely accepted by most programming languages. However, we caution against its use for storing and retrieving data in an asynchronous environment like a Discord bot. Don’t use json!

  • It's a file-based data storage, which makes it vulnerable to race conditions
  • You'll need to implement your own synchronization primitives to avoid corrupting data
  • If you're not careful, you could accidentally wipe your entire JSON file.

Solution? Use a database. Recommended schema are SQLite, PostgreSQL, and MongoDB.

  • Async libraries exist on pypi for each of these
    sqlite -- aiosqlite (or Danny's wrapper: asqlite)
    postgresql -- asyncpg
    mongodb -- motor
  • Databases organize your data into tables, and are fast at inserting, retrieving, and removing records
  • You can impose uniqueness constraints to ensure against duplication
  • The Python libraries enforce synchronization for you
  • The query language is intuitive, you can get running with simple queries in just a few hours!
wary saffron
#

Ohhhh

#

Got any tutorials you recommend? I won't have pc access for awhile btw

lofty parcel
#

Plus, you need to learn OOP.

#

How much of the python basics you know?

wary saffron
#

Most of the basics but barely OOP

lofty parcel
lofty parcel
wary saffron
#

Oo ty :3

lofty parcel
#

@errant trout What do you recommend as DB for them

errant trout
#

json rodab

#

If you want a "serious" suggestion uhhh aiosqlite is pretty good at this scale

tidal vessel
#

guys, a question, if I add a new Slash Command and reload the extension is it automatically added in discord?

errant trout
#

Not now no

#

I'm aiming to improve slash command syncing for 2.7

tidal vessel
errant trout
#

Just restart the bot

#

Only have to do that for adding/removing commands or updating their metadata (name, options etc), if you're just changing code then reload is fine

tidal vessel
#

Ok, ty!

signal trench
#

how to create threads ?

karmic river
#

I made a bot in pycord which was working perfect but now it have stopped responding to my commands

#

how can I fix it up???

#

@errant trout

little cobalt
karmic river
forest rain
#

Is it possible to make review buttons and modal windows that have them active for 48 hours?

class ReviewButtons(discord.ui.View):
@discord.ui.button(label="Review", style=discord.ButtonStyle.green, custom_id="review_button")
async def review(self, button: discord.ui.Button, interaction: discord.Interaction):
modal = ReviewModal()
await interaction.response.send_modal(modal)

sage tendon
#

it just needs to be a persistent view

fresh sierra
#

.rtfm persistent

forest rain
shadow bear
#
Ignoring exception in on_connect
Traceback (most recent call last):
  File "/app/venv/lib/python3.11/site-packages/discord/client.py", line 400, in _run_event
    await coro(*args, **kwargs)
  File "/app/venv/lib/python3.11/site-packages/discord/bot.py", line 1178, in on_connect
    await self.sync_commands()
  File "/app/venv/lib/python3.11/site-packages/discord/bot.py", line 754, in sync_commands
    app_cmds = await self.register_commands(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/app/venv/lib/python3.11/site-packages/discord/bot.py", line 588, in register_commands
    data = [cmd["command"].to_dict() for cmd in filtered_deleted]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/app/venv/lib/python3.11/site-packages/discord/bot.py", line 588, in <listcomp>
    data = [cmd["command"].to_dict() for cmd in filtered_deleted]
            ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/app/venv/lib/python3.11/site-packages/discord/commands/core.py", line 875, in to_dict
    "options": [o.to_dict() for o in self.options],
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/app/venv/lib/python3.11/site-packages/discord/commands/core.py", line 875, in <listcomp>
    "options": [o.to_dict() for o in self.options],
                ^^^^^^^^^^^
  File "/app/venv/lib/python3.11/site-packages/discord/commands/options.py", line 337, in to_dict
    "type": self.input_type.value,
            ^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'value'

How can I debug this? the error gives me no information and I have over 100 commands to check through if I need to go through it manually

sage tendon
#

whatever you changed last is the issue

shadow bear
#

so funny story

#

I have had this error in my logs for like

#

a month

#

and just

#

haven't noticed

#

lmfao

#

I can't figure out how input_type would be None, doesn't Option() force it to be string if its not an InputType?

sage tendon
#

maybe you put bogus there

shadow bear
#

I've got an amazing idea

#

I'll just try parsing them all manually before registering

#

to_dict() is raising the error

#

so if I just iterate through all commands after loading them and calling it manually, I'll find out which command is whack

shadow bear
#

I don't appear to be able to do this

#
log.debug("Walking the following application commands: %r", list(bot.walk_application_commands()))
for command in bot.walk_application_commands():
    log.debug("Checking %r", command)
    try:
        assert command.input_type is not None, "Input type was None!"
        d = command.to_dict()
    except Exception as e:
        log.error("Failed to convert %r to dict", command, exc_info=e)
        bot.remove_application_command(command)
    else:
        log.debug("Loaded command %r.", command)
bot.run(...)
#

Walking the following application commands: []

little cobalt
#

do you use cogs?

shadow bear
#

yes, they're loaded before this

shadow bear
#

the cogs are loaded just after the bot's instance definition just after line 130

#

I could try overriding on_connect's event and doing the validation in that function I guess

little cobalt
shadow bear
#

I just called super()

#

which, still isn't working

class Client(commands.Bot):
    def __init_(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.web: typing.Optional[asyncio.Task] = None
        self.uptime_thread = None
    
    async def on_connect(self):
        log.debug("Walking the following application commands: %r", list(self.walk_application_commands()))
        for command in self.walk_application_commands():
            log.debug("Checking %r", command)
            try:
                assert command.input_type is not None, "Input type was None!"
                _ = command.to_dict()
            except Exception as e:
                log.error("Failed to convert %r to dict", command, exc_info=e)
                self.remove_application_command(command)
            else:
                log.debug("Loaded command %r.", command)
        log.info("Connected to Discord.")
        await super().on_connect()
#

am I missing something?

sage tendon
#

pass self to it (?)

#

or im dumb idk

shadow bear
#
def walk_application_commands(self) -> Generator[ApplicationCommand, None, None]:
    """An iterator that recursively walks through all application commands and subcommands.

    Yields
    ------
    :class:`.ApplicationCommand`
        An application command from the internal list of application commands.
    """
    for command in self.application_commands:
        if isinstance(command, SlashCommandGroup):
            yield from command.walk_commands()
        yield command

This is the source for walk_application_commands

#

so I cna only assume self.application_commands is empty for... some reason

#

which it really shouldn't be given I define one or two application commands in the runtime file, just after loading cogs

#

I am so confused right now

sage tendon
#

then id suggest showing your cogs and those 2 commands too

shadow bear
#

Hang on, I might try checking pending_application_commands

#

maybe application_commands only gets populated post-sync

#

that was it

#
jimmy-public   | WARNING  2024-05-27 16:40:10 WARNING jimmy: No application commands. using pending.
jimmy-public   | ERROR    2024-05-27 16:40:10 ERROR jimmy: Failed to convert <discord.commands.SlashCommand name=election> to dict
jimmy-public   |          Traceback (most recent call last):
jimmy-public   |            File "/app/main.py", line 125, in on_connect
jimmy-public   |              assert command.input_type is not None, "Input type was None!"
jimmy-public   |                     ^^^^^^^^^^^^^^^^^^
jimmy-public   |          AttributeError: 'SlashCommand' object has no attribute 'input_type'
#

bingo

#

nevermind

#

idk why i tried to get the input type of the entire command lmao

fresh sierra
#

sorry im a bit late but what is ur issue ?

#

and what are you trying to achieve ?

shadow bear
#

issue I just fixed was I couldn't walk the application commands to figure out which command it was

fresh sierra
shadow bear
#

Yeah, that's what i've just figured out

#

didn't realise pending was separate

fresh sierra
#

so basically you have a command that cant be sync

#

are you are trying to know which one it is ?

shadow bear
#

Yep

#

I've got 10 cogs, and thousands of lines to comb through

#

so I wanted to just figure it out from the error

#

rather than going through manually

fresh sierra
#

when you simply run without overwritting the on_connect

#

what does it give you ?

shadow bear
#
jimmy-private  | ERROR    2024-05-27 16:45:25 ERROR jimmy: Failed to validate <discord.commands.SlashCommand name=about>
jimmy-private  |          Traceback (most recent call last):
jimmy-private  |            File "/app/main.py", line 128, in on_connect
jimmy-private  |              raise TypeError("Input type is None")
jimmy-private  |          TypeError: Input type is None

There we go, found the violating command

shadow bear
#

Except my changes to commands weren't being updated, since it couldn't sync

#

hence why I just didn't notice for so long lol

#
@bot.slash_command(name="about")
async def about_me(self, ctx: discord.ApplicationContext):
    ...
    return await ctx.respond(embed=embed)

Hold on, what option?

#

OH WAIT

fresh sierra
#

i have a basic thing to help you, normally it just remove the command that is laggy so you can just check you help if you have one to see what command is missing

shadow bear
#

I ADDED SELF TO THAT

#

its not in a cog

fresh sierra
#

here you go ;)

#

how many hour have you spent on that ?

shadow bear
#

uh if we're counting since the first error, like a month

#

if we're counting time spent actively debugging, about an hour? half an hour?

fresh sierra
#

only an hour is fine, hopefully it will not take longer next time

shadow bear
#

its fine, it was only 10 commits, which is less than usual mmlol

sage tendon
#

why did you commit any of that