#Basic Pycord Help (Quick Questions Only)

1 messages · Page 83 of 1

waxen whale
#

uh

#

well there u have it

#

thx nelo

rare ice
#

Oh

waxen whale
rare ice
#

well I do but I didn’t realize I needed to use add_item

#

I thought I tried that

proud mason
cyan quail
#

what threw me off is that the original BasicModal class you pasted here did use add_item

cinder pelican
#

Sorry, one more question (almost have Forms working now):

Is there a clean way to refresh a Page in Paginator? I have input coming from a Modal that updates the Page, but obviously those changes don't show rn without navigating away from that page

Would it just be edit_message and resend the Paginator?

If so, can I start it on a desired page?

cinder pelican
silver moat
#

yay

zealous bear
#

how do you do prefix commands on pycord?

silver moat
zealous bear
#

to be honest

#

don't know what it was before haah

young bone
#

what?

silver moat
zealous bear
#

thanks

zealous bear
#

is it something wrong with this line

#
bot = discord.Bot(command_prefix = "!", intents=discord.Intents.all())
silver moat
#

yeah it's commands.Bot

zealous bear
#

commands.Bot = "!"?

young bone
silver moat
#
- bot = discord.Bot(command_prefix = "!", intents=discord.Intents.all())
+ bot = commands.Bot(command_prefix = "!", intents=discord.Intents.all())
zealous bear
#

they said discord.Bot

#

??

silver moat
#

?tag client

obtuse juncoBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
zealous bear
#

discord.ext.commands.errors.CommandRegistrationError: The command help is already an existing command or alias.

#

:D

silver moat
young bone
#

help_command=None

#

or that

zealous bear
#

and how do you do hybrid commands? i couldn't find that in the docs

young bone
#

prefix got an inbuild help command

zealous bear
#

@bot.bridge_command()
async def ping(ctx):
await ctx.send("pong")

#

in that case the slash command works but the ! command does not

zealous bear
zealous bear
#

alright thanks

zealous bear
young bone
#

^^

zealous bear
#

or not

zealous bear
young bone
#

also at the website?

silver moat
#

that's not how pycord works

zealous bear
#

!ping still isn't working 😭

silver moat
#

do you have an on_message event?

zealous bear
#
@bot.command()
async def ping(ctx):
    await ctx.respond("pong")  
zealous bear
young bone
#

thats why

silver moat
#

change it to @bot.listen()

zealous bear
#

alr

#

alright we good now thank you much guys

zealous bear
#

i've barely touched anything and now all of my slash commands have dissapeared?!?!?

#

😭

#

does anyone know something that would cause all slash commands to stop working

#

like not even showing up in the slash menu

thorny cipher
#

quick question: can you subclass a discord.ui.View with a Modal?

full basin
silver moat
zealous bear
thorny cipher
zealous bear
#

restarted disc

#

that didn't work

#

so i guess i should just wait it out?

silver moat
#

probably comment out everything, run the bot, uncomment everything then run the bot again

#

and then restart discord

zealous bear
#

okay

#

yeah that didn't work whatever

#

ill just wait i guess

#

so damn wierd

zealous bear
#

yeah the slash commands dont show up but my prefix commands work

#

and i've waited an hour

#

and it's not just me

#

none of the server members can use it

silver moat
zealous bear
#

ok

silver moat
#

when I say run the bot, I mean wait until on_ready

zealous bear
#

but i did it and it did not work

#

is this happening to anyone else?

silver moat
#

could you print the commands out through bot.walk_application_commands?

zealous bear
#

could you link the docs or ?tag it

silver moat
#

.rtfm bot.walk_app

zealous bear
#

awesome

#

walk_application_commands is not defiened

silver moat
#

version?

zealous bear
#

newest

#

3.4

silver moat
#

uhh what

#

pip list and show output

zealous bear
#

aiohttp 3.8.4
aiosignal 1.3.1
aiosqlite 0.19.0
async-timeout 4.0.2
attrs 23.1.0
autocorrect 2.6.1
boto3 1.26.140
botocore 1.29.140
cachetools 5.3.1
certifi 2023.5.7
charset-normalizer 3.1.0
discord 2.2.3
distlib 0.3.6
ffmpeg-python 0.2.0
filelock 3.12.0
frozenlist 1.3.3
future 0.18.3
google-api-core 2.11.0
google-api-python-client 2.88.0
google-auth 2.19.0
google-auth-httplib2 0.1.0
google-cloud-language 2.9.1
googleapis-common-protos 1.59.0
grpcio 1.54.2
grpcio-status 1.54.2
httplib2 0.22.0
humanize 4.6.0
idna 3.4
imageio-ffmpeg 0.4.8
iniconfig 2.0.0
jmespath 1.0.1
multidict 6.0.4
numpy 1.24.3
packaging 23.1
pip 23.1.2
platformdirs 3.5.1
pluggy 1.0.0
proto-plus 1.22.2
protobuf 4.23.2
py-cord 2.4.1
pyasn1 0.5.0
pyasn1-modules 0.3.0
PYCORD.PY 0.1.0
pycryptodome 3.18.0
pyparsing 3.0.9
pyspellchecker 0.7.2
pytest 7.3.1
python-dateutil 2.8.2
python-twitch-client 0.7.1
requests 2.31.0
rsa 4.9
s3transfer 0.6.1
secret 0.8
setuptools 67.8.0
six 1.16.0
tabulate 0.9.0
twitchAPI 3.11.0
typing_extensions 4.5.0
uritemplate 4.1.1
urllib3 1.26.16
virtualenv 20.23.0
wheel 0.40.0
wordninja 2.0.0
yarl 1.9.2

#

i should probably be using a venv but i haven't had any issues beause i use pycord for all my apps

silver moat
#

uninstall discord, PYCORD.PY, and py-cord and reinstall py-cord

zealous bear
#

done

#

didn't fix the no slash commands issue unfortunately

#
@bot.event
async def on_ready():
    for command in bot.walk_application_commands():
        print(command)
    activity = discord.Activity(type=discord.ActivityType.watching, name="over TC")
    await bot.change_presence(status=discord.Status.online, activity=activity)
    print("Bot is fully functional and ready!")
    print("----------------------------------------")
#

is this the correct usage of the walk application commands

silver moat
#

yes

zealous bear
#

it prints nothing

#

that can't be good

silver moat
#

yeah means you have no application commands

zealous bear
#

cause even bots that are offline still show up in the slash command dashboard thing

zealous bear
#

i most definetely do

silver moat
#

.slashnoshow

winter condorBOT
#

Checklist for Application Commands Not Showing Up:
• Does your bot have the application.commands scope?
• Are you loading cogs before on_ready and on_connect?
• Is on_connect not overridden?
• Did you update to the newest version of py-cord (tag: install)?
• Is User Settings > Accessibility > Chat Input > Use legacy chat input turned off?
• Did you share your code and errors?
• Do you still have libraries that conflict with the discord namespace (e.g. discord.py)?

silver moat
#

tbh I don't think this applies to you since it was working before

zealous bear
#

right

#

plus all of those seem good

#

cause it makes no sense for a command like

#
@bot.command(server_id = server, name = "ping", description = "returns pong")
async def ping(ctx):
    await ctx.send("pong!")
#

to not work

silver moat
#

how are you defining your slash commands?

silver moat
#

and what is your bot instance, discord.Bot or commands.Bot or what

zealous bear
#

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

silver moat
zealous bear
#

well there we go

#

😭

silver moat
#

@bot.slash_command would be correct

zealous bear
#

awesome thanks

#

ahhhh

#

all for this

warm spire
#

anyone have a good way for users to input a date/time? rn im having them input a timestamp to make it easy for me. but theres gotta be a more user-friendly way.

silver moat
#

it has been there for at least 6 months tho, so I'm not sure about the feature's priority

warm spire
#

fugg it, i shall impose unix timestamps on my users

#

expand their horizons

silver moat
warm spire
#

so im just sending them to a date/time -> timestamp converter website

silver moat
meager heron
#

dateutil has some pretty good parsing

inland viper
#

trying to reload bridge command defined in cogs with bot.reload_extension() but raised error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'BridgeCommand' object has no attribute 'name'
I found in recent question history its a known issue?

fervent cradle
proud mason
fervent cradle
proud mason
#

Hmm dk

earnest widget
#

is there any way to edit an embed without touching the image inside it?

#

the images inside my embeds are uploaded, dont have a static url

#

so if i edit it and use message.embeds[0].url theyll eventually expire

#

i wanna edit the embed and keep the image in it as is

cyan quail
#

when you use attachment:// it's uploaded to the current channel

#

unless it's an ephemeral message, which is designed to expire anyway

earnest widget
#

uploaded image in embed

(Action 2 happens)
Image URL taken from embeds[0].image.url

Set new emb

Edited old embed with emb

removed old file with files = [] otherwise the image doubles one inside embed one outside

#

I have a workaround where I'll upload all images to a common channel and then use their url instead of directly uploading them to a main channel but I'd rather not to the extra work of migrating if there's a built in way to go around it

#

ping when reply ty

cyan quail
pseudo surge
#

Hey all, I have a persistent view with multiple select menus where MyView.is_persistent(MyView()) returns True, but when I restart the bot and try to reuse it, I'm getting "this interaction failed"

I'm using

async def select_callback1(self, select, interaction):
        [...]
        await interaction.response.defer() ```

between select menus. Is that the right approach?

Everything appears to work as intended until bot restarts. Any ideas?
cyan quail
pseudo surge
#

Yep, hence the MyView.is_persistent(MyView()) returns True

cyan quail
#

well is_persistent only returns whether the custom_id was set by the user

pseudo surge
#

Oh ok

cyan quail
#

but hm

proud mason
#

||there is a better way to use OOP||

#

MyView().is_persistent()

cyan quail
pseudo surge
#

Yes but there's four select menus and a button so apologies in advance:

 class MyView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)  # timeout of the view must be set to None


    @discord.ui.select(custom_id="select-1",
                       placeholder="What kind of character is this?",
                       min_values=1,
                       options=[
                           discord.SelectOption(
                               label="Monastic",
                               description="Pick this if you plan to live in the founding monastery"
                           ),
                           discord.SelectOption(
                               label="Representative",
                               description="Pick this if you plan to live in another clan"
                           )
                       ]
                       ) 
    async def select_callback1(self, select, interaction):
        characterType = select.values[0]
        self.s1check = True
        await interaction.response.defer()
#

Then three more and a button:

  @discord.ui.button(label="Submit", custom_id="button1", row=4, style=discord.ButtonStyle.primary)
    async def first_button_callback(self, button, interaction):
        if self.s1check and self.s2check:
            await interaction.response.send_modal(bioModal(title="Modal via Button"))
        else:
            await interaction.response.send_message("Questions 1 and 2 are required to submit", ephemeral=True)```

Then:

```py
@bot.command()
async def select(ctx):
    await ctx.send(
        f"Make a Character Book! \n \n First, what kind of character is this? {MyView.is_persistent(MyView())}",
        view=MyView())```
#

At the top of the file:

@bot.event
async def on_ready():
    bot.add_view(MyView())
#

Does it matter that I'm using bot = commands.bot instead of discord.bot?

#

Edited to include the button if that's helpful

young bone
#

But for commands yes

#

?tag client

obtuse juncoBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
pseudo surge
pseudo surge
earnest widget
#

for the embed

#

will that maintain the same imageurl after its uploaded as the previous one orwill that change

cyan quail
#

the way attachment:// works is that if any files in the message have a matching filename, the file will hide itself and show in the embed instead

#

but when you edit the embed using that url, attachment:// no longer exists so it shows both

#

so the solution is to set it as attachment:// again

earnest widget
#

o so its gonna maintain the same file inside the embed

cyan quail
#

mhm

earnest widget
#

tyty

cyan quail
pseudo surge
eternal wing
#

The docs say there is such a property? "If applicable" of course, but shouldn't it return None or False if it's not applicable?

tired crag
#

how do I send a message to a channel without ctx (during on_ready())

pseudo surge
full basin
#

.rtfm get_channel

tired crag
#
Traceback (most recent call last):
  File "C:\Users\possi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 378, in _run_event
    await coro(*args, **kwargs)
TypeError: on_ready() missing 1 required positional argument: 'ctx'```
#

bruh

#

I have ctx everywhere

young bone
tired crag
#
@bot.event
async def on_ready(ctx):
    # Embed Creation

    mainchannel = bot.get_channel(main_channel)
    await mainchannel.send(file=screenshot(ctx)) # Send the info message
young bone
#

why ctx

tired crag
#

it doesn't like it for some reason

tired crag
young bone
#

() has to be empty

tired crag
#

gives me the same thing now

#

but look

#

it wants ctx in screenshot()

#

but idk why

young bone
#

?

tired crag
#

line 48 is screnshot()

#

and screenshot returns a discord.File

full basin
#

On ready doesnt take any parameters

tulip ledge
#

How to make a simple slash command to show info about user?

full basin
#

Read the docs and try

#

You won't get code

tulip ledge
#

Ok, I will try

young bone
tired crag
#

it was a strange fix but I fixed it

full basin
#

"Strange fix" had to remove the argument

tired crag
#

not at all

#

I had to move my functions inside on_ready and then change some other things around

#

ok wtf is this
File "c:\Users\possi\Documents\Dev\discordlogger\mainrw.pyw", line 17, in <module>
bot = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'

#

I did pip update discord and now it gives me this??

full basin
#

Because the library on pip is py-cord

#

Not discord

tired crag
#

oh right

#

ok its still not working

#

wait hold up

full basin
#

You must uninstall all discord related libraries and only install pycord

tired crag
#

okay..

full basin
#

It is imported as discord

still helm
#

i have a problem sending a file to a user. Thats my code

                                if fileSize < 50000000:
                                    file = discord.File(filename)
                                    await channel.send(embed=embed)
                                    await channel.send(file=file)
                                    user = self.bot.get_user(322812067994140672)
                                    await user.send(embed=embed)
                                    if fileSize < 8000000:
                                        await user.send(file=file)

The file was sended to the channel but not to the user, the embed is send to both, the file is not deleted. Is there anything i did wrong there?

full basin
#

You import discord

#

But install py-cord

tired crag
#

yeah I did

#

i un-imported discord

full basin
#

No

#

You import discord

#

But install py-cord not discordn

#

The folder name is discord. The library on pip is py-cord

tribal girder
#

how to do interaction.response.send_message twice? looks like it can only be responded once

tired crag
#

so I pip uninstall discord?

tired crag
#

AttributeError: module 'discord' has no attribute 'Bot'

#

I just did pip uninstall discord

#

and made it called discord, same error

young bone
#

Show the pip list

#

@tired crag

tired crag
#

yeah there's a lot lol

young bone
untold spoke
#

so it will be self.bot

young bone
#

@tired crag uninstall discord.py and py-cord and reinstall only py-cord

tired crag
#

ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)

untold spoke
young bone
#

Also discord-webhook

tired crag
#

still same thing

young bone
#

Py-cord already have webhook

tired crag
#

'commands' from 'discord.ext' (unknown location)

full basin
#

Isn't nextcord a Discord library too

young bone
#

Yes

#

Nextcord is also one

full basin
#

It is

tired crag
#

still the same errors

#

ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)

full basin
#

My man installed every possible discord api wrapper

tired crag
tired crag
full basin
#

You have like 3 discord libraries installed

tired crag
#

I just uninstalled

full basin
#

Uninstall py-cord again

#

And install it back

untold spoke
#

use an venv

full basin
#

You have files replacing each other

untold spoke
#

delete everything

#

and reinstall cleany

tired crag
#

AttributeError: module 'pycord' has no attribute 'Bot

untold spoke
tired crag
#

which parts?

full basin
#

Why are you importing pycord

proud mason
#

why are you doing import pycord 😭

tired crag
#

because I just uninstalled discord??

proud mason
#

?guide

#

?tag guide

obtuse juncoBOT
proud mason
#

please have a read

tired crag
#

nvm shut up

untold spoke
tired crag
#

same error

untold spoke
#

like when you install pycord, you will have to use discord

untold spoke
tired crag
full basin
proud mason
#

pip install py-cord
import discord

thats what you do

untold spoke
tired crag
#

I have a bunch of sensitive stuff on there

young bone
#

Not everyone at the same time pls guys ;3

tired crag
proud mason
untold spoke
#

bot = commands.Bot(command_prefix="+",intents=intents, owner_id = owner_bot)

proud mason
#

dark you'll handle this?

untold spoke
#

like this

tired crag
#

but I don't use commands? I use slash commands

proud mason
#

mhm

young bone
#

Only slash_command use discord.Bot

tired crag
untold spoke
#

show your import

tired crag
#

import discord

#

that's all

proud mason
#

yk what do this

pip uninstall discord discord.py nextcord dissnake py-cord pycord
followed by
pip install py-cord

and keep the code unchanged

untold spoke
#

if you use slash command

#

i thing you can define bot = commands.Bot( intents=intents) like this

#

because i have some slash command and it work like this so

obtuse juncoBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
untold spoke
#

yes but if it works

tired crag
#

uh

#

it workedty @proud mason

proud mason
#

nice 👍

young bone
#

@untold spoke you dont need commands.Bot for only slash commands ;3

untold spoke
#

so you doesnt have installe a venv

untold spoke
#

i know its strange but sometime i have to import discord as disc for it work and then reuse discord

inland viper
#

using bridge command with typing var: Option(int) = 0
works for slash command
but error for prefix command discord.ext.commands.errors.BadArgument: Converting to "Option" failed for parameter "var".
is this because using wrapper on command?

inland viper
# young bone just do var: int=0

okay thanks, also is there a option for command that ignore parameter such as **kwargs ?
when using **kwargs it gives discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body

silver moat
#

Slash Command options have to be explicit.

strong bobcat
#
      try: 
            exec(code) 
      except Exception as e: 
             await ctx.respond(f'Error: {e}') 
@bot.slash_command(name="execute", description="Code execute.") 
async def execute(ctx: discord.ApplicationContext, *, code): 
    loop = asyncio.get_event_loop() 
    loop.run_until_complete(compile(ctx, code)) 
    loop.close()```
Please help, await outside function error.
#

And i use nest_asyncio

finite flame
#

is it possible to generate an invite link for your bot that's already directed at a specific guild and if so how?

lunar fossil
#

I am trying to add the server Icon as a image to an embed, but I can't find how to do it, maybe that somebody wants to help

silver moat
lunar fossil
#

booth

silver moat
#

guild.icon.url

#

would be the image

untold spoke
silver moat
untold spoke
#

i dont pass it into a string

#

but it still work so i dont understand what you mean

silver moat
#

Guild.icon returns an Asset object.

#

the Asset object has a method that allows it to be converted to a string, but the same result can be converted to with Asset.url

untold spoke
#

so we dont need to pass ourself this to a string

#

its automatic

#

if i understand or im totally wrong

silver moat
#

sometimes it is, sometimes it isn't

lunar fossil
#

I got it working, Thanks!

untold spoke
#

for thumbnail and image it always works

#

have you an example of when this doesnt work ?

silver moat
cyan quail
thorny stag
#

how do i get the emojis in a guild

cyan quail
#

... guild.emojis

untold spoke
#

ctx.guild.emojis

young bone
thorny stag
#

it just worked

#

it wasnt working before

untold spoke
#

@strong bobcat if you ask help then stop respond...

strong bobcat
untold spoke
#

and you can just eval i guess

strong bobcat
untold spoke
untold spoke
young bone
strong bobcat
strong bobcat
strong bobcat
strong bobcat
untold spoke
strong bobcat
untold spoke
#

so you will need to eval the texte

#

so you will have
@commands.command()
asyc def eval(self,ctx,*,text)
+eval(text)

#

for exemple

strong bobcat
untold spoke
#

it try with await

#

send without

somber pelican
strong bobcat
#

Await error

somber pelican
#

🤔

#

Await outside async function? That shouldn't be happening, because your function is async, can you send your full code? (Not just the function, but also the cog, etc)

strong bobcat
somber pelican
#

I did see your code, is the await outside async function error happening at the ctx.respond line?

patent knoll
#

I know the file= part is wrong, but how do i make it right :D

somber pelican
#

.rtfm discord.file

patent knoll
#

that doesnt help me

somber pelican
strong bobcat
proud mason
somber pelican
#

Pip list output

#

In the console

patent knoll
strong bobcat
young bone
#

pip list > pip.txt <-- at the terminal

strong bobcat
#

Hosting

proud mason
somber pelican
#

Yeah sorry it might mean you don't have pycord installed, but rather a different package under the same discord namespace because there's no way it would throw that error

proud mason
somber pelican
#

No idea here sorry, :/

patent knoll
#

so
discord.File(io.BytesIO(zipped_F.read()))?

proud mason
#

Btw Nullptr, how about you share the full error?

proud mason
#

Isn't that for Jupyter Notebooks?

strong bobcat
#

Also

patent knoll
proud mason
#

Could you show the updated code

patent knoll
#

i made it work

#

easier than you think lol

proud mason
#

Lmao

patent knoll
#

Is there any way to scrape stickers with pycord
There is neither a URL nor a read() to do that

patent knoll
#

idk if i'm in the wrong place but it seems right

young bone
patent knoll
#

yea i just saw

#

i'd need to use fetch_stickers

#

kind of odd

round rivet
#

feel free to pr a read method

patent knoll
#

would be great
I just now wrote an emoji downloader which simply does emoji.read() and writes to a zip
Now i gotta figure out how to properly handle it only being a URL for stickers

round rivet
#

make an http request to the url

#

read data

patent knoll
#

yes, dw, i'm on it
just a bit inconvenient

cyan quail
copper pine
#

How can I make the bot go into "thinking mode" after executing a command and then respond?

silver moat
#

?tag defer

obtuse juncoBOT
#

dynoError No tag defer found.

silver moat
#

.rtfm context.defer

wet coral
#

In the Discord Server settings you can enable or disable certain slash command for certain users or roles. Is it possible to set a default for that in pycord?
Default member permissions? Checks? Or is it simply not possible?

silver moat
#

.rtfm discord.default_

wet coral
#

thx, I'll have a look at it

wet coral
silver moat
#

yeah those aren't possible under the current system

wet coral
#

does the api not allow it or is it just not yet implemented?

silver moat
#

for which one?

#

actually both questions have the same answer

wet coral
#

roles and users

#

second one doesn't have anything to do with the discord api...

silver moat
#

they aren't possible under current api

wet coral
#

And the default_member_permissions actually don't translate to the command usage you can set in the server settings do they?

silver moat
#

yup

wet coral
#

Ok, well discord gotta change that xD

waxen whale
#

they won't

waxen whale
#

yes, and what a convinient coincidence: we have guides, docs and even examples!

#

literally look on github and the website lmfao

young bone
#

And also pls dont crosspost

waxen whale
#

don't minimod when i'm here zerv

young bone
#

Oh doch xd

silver moat
#

And also, please don't crosspost

waxen whale
#

-to @young bone 1m no

wanton pondBOT
#

⏱ Timed out zervyrel#0 for 1 minute

waxen whale
#

well breaking rules clearly does catch my attention, but i dont think people like the results

young bone
young bone
#

Why did they not just removed it....

waxen whale
silver moat
#

and also, it's not adding a button to an embed. It's adding components to a message

#

the message just so happens to have embeds on it

waxen whale
#

well yeah #rules is "dont be a knob"
but #how-to-get-help with #help-rules is specific to avoid that we as helpers/devs get a headache from users

waxen whale
young bone
#

Only py-cord

silver moat
waxen whale
#

they just slow

#

its not an hard implementation lol

solemn gale
#

i have error with prefix commands using prefix

discord.ext.commands.errors.BadArgument: Converting to "Option" failed for parameter "miembro".

i get that error using Option() and the command, recomendations?

silver moat
solemn gale
#

ohhh

silver moat
solemn gale
#

¿What do you recommend, continue using the prefix commands or use the slash/application commands?

silver moat
#

application commands because it's the standard

solemn gale
#

¿Do you recommend me still using bridge commands?

brittle fable
#

Hey y'all, been working on my first bot :) Was wondering if there was a way to render a button that is only visible to the author of a command?

silver moat
#

?tag ephemeral

obtuse juncoBOT
#

An 'ephemeral' message is one that's only visible to the person who invoked a command. If you ever got a command error with a blue background, this is an example of one.

To do this, set ephemeral=True when you first use an ApplicationContext. (This includes .defer()ing it; the choice of whether a message is ephemeral or not must be made up front. If you .respond() to a deferred message, setting the ephemeral flag at that time will have no effect.)

This is the equivalent of hidden=True if you're coming from interactions.py

e.g.

await ctx.respond("Imagine a message!", ephemeral = True)

await interaction.response.send_message("Imagine a message!", ephemeral = True)
brittle fable
#

Ah, I meant like the button ui element itself, not a message 😅

brittle fable
#

Unfortunate - thanks for the help!

fervent cradle
spring hare
#

Is there a way to find users with their pomelo nickname?

versed fern
#

How much RAM does an average sized bot need?

spring hare
tribal girder
#

how to do interaction.response.send_message twice or more for one interaction? for multiple condition

proud mason
proud mason
proud mason
spring hare
tribal girder
proud mason
spring hare
#

sry

proud mason
#

Lmao fr. 1gb is extremely large

spring hare
#

yup

#

I host my bot on my old android phone with 2gb of ram

proud mason
#

Oh damn

#

Cool

spring hare
#

free hosting

proud mason
#

Fr kek

spring hare
#

termux

young bone
#

With root?

spring hare
#

no?

young bone
#

oof

spring hare
#

Termux doesn't need root lmao

spring hare
tribal girder
# proud mason Hmm can you show what you are doing?
    async def callback(self, select, interaction: Interaction):
        remove_role = [x for x in select.values if x in interaction.user.roles]
        add_role = [x for x in select.values if x not in interaction.user.roles]
        for i in select.values:
            inter = interaction.user.roles
            if i in inter:
                for x in remove_role:
                    r = discord.utils.get(interaction.guild.roles, name=x)
                    await interaction.user.remove_roles(r)
                    await interaction.response.send_message(f"added {r} role")
                    
            if i not in inter:
                for x in add_role:
                    r = discord.utils.get(interaction.guild.roles, name=x)
                    await interaction.user.add_roles(r)
                    await interaction.followup.send(f"removed {r} role")
versed fern
proud mason
finite flame
#

hey, I have a python backend sending discord IDs to my frontend like below

@router.get('/bot_guilds')
async def get_bot_guilds():
    return [
        {
            'id': guild.id,
            'name': guild.name
        } for guild in Guild.get_all()
    ]```

and receiving it in my frondend (ts) I push it into this structure
```ts
export type PGuild = {
  id: bigint;
  name: string;
  icon: string;
  owner: boolean;
  permissions: bigint;
}

export class PartialGuild {
  id: bigint;
  name: string;
  icon: string;
  iconAssigned: boolean;
  isOwner: boolean;
  private readonly _permissions: bigint;

  constructor(data: PGuild) {
    this.id = BigInt(data.id);
    this.name = data.name;
    [this.icon, this.iconAssigned] = PartialGuild.getIcon(data.id, data.icon, data.name);
    this.isOwner = data.owner;
    this._permissions = BigInt(data.permissions);
  }```

could it be that the json in between can't handle the bigints? because sending this: `287585628852584460` in my backend ends up as `287585628852584448n` in my frontend
spring hare
#

try to pass id as str

inland viper
#

for slash command autocomplete, is it possible to have different display value and actual parameter?
did not see any on the example

tribal girder
#

what type of view is this? i need to know the name

cyan quail
#

the recieved variable will be the value as a string; note that as always, you need to still validate that value since autocomplete isn't enforced.

untold spoke
#

Does someone know how to unlock a database ?

#

i always get this kind of error and the only way i found is reload the bot
self.cursor.execute("INSERT INTO embeds (guild_id, embed, title) VALUES (?, ?, ?)", (interaction.guild.id, str(embed_dict), str(original_embed.title)))
sqlite3.OperationalError: database is locked

#

but is it possible to just reload all database without reload the bot ?

versed fern
#

How do y'all feel about hosting a bot on a raspberry pi?

young bone
versed fern
#

Anything I should be aware of? Any issues?

young bone
#

Do you have a good Internet connection?

loud sail
young bone
#

discord.utils.format_dt()

#

do you mean this?

loud sail
#

nvm, I have it

earnest widget
versed fern
#

Where do you keep your pi? Did you print some kinda case?

versed fern
#

And did you install a fan or anything for cooling?

mossy holly
# versed fern I'm currently getting a new router, should be better afterwards

If you don’t have a good connexion like me, I host my bot on oracle cloud free tier.
You need to use a credit card to confirm your account (they take some money but give it back to check so no fake cards) and afterwards you have up to the equivalent of 24Go of RAM and 4 cores (and 200 or 250 Gb of storage i think)

pseudo glen
#
import discord
from discord.ext import commands

from base.cog import BaseCog
from utils.emojis import Emojis
from views.selects import DropdownView


class VoiceSetup(BaseCog):
    def __init__(self, bot: discord.AutoShardedBot) -> None:
        self.bot: discord.AutoShardedBot = bot

    @commands.slash_command(guld_only=True)
    async def setup(self, ctx: discord.ApplicationContext) -> None:
        embed = discord.Embed(
            ...
            color=self.bot.user.color
        )
        embed.set_author(name=self.bot.user.name, icon_url=self.bot.user.avatar.url)
        embed.set_footer(icon_url=ctx.author.avatar.url, text=f"{ctx.author} 測試")
        view = DropdownView(self.bot)
        await ctx.respond(embed=embed, view=view)


def setup(bot: discord.AutoShardedBot) -> None:
    bot.add_cog(VoiceSetup(bot))

for some reason, the user.color always returns the color black.

#

sorry, I was trying to get the banner color

still helm
#

i have a problem sending a file to a user. Thats my code

                                if fileSize < 50000000:
                                    file = discord.File(filename)
                                    await channel.send(embed=embed)
                                    await channel.send(file=file)
                                    user = self.bot.get_user(322812067994140672)
                                    await user.send(embed=embed)
                                    if fileSize < 8000000:
                                        await user.send(file=file)

The file was sended to the channel but not to the user, the embed is send to both, the file is not deleted. Is there anything i did wrong there?

cyan quail
cyan quail
#

(also fwiw, it's possible to send that uploaded file inside the embed rather than as a separate message)

still helm
cyan quail
#

ahh fair enough

still helm
#

What´s the way to send it multiple times?

cyan quail
#

just create another discord.File

still helm
#

ok thanks

soft girder
#

How to do button counter

patent knoll
#

Idk if im stupid but why does

message = await ctx.respond(...)
await message.edit(...)

not work?

#

"interaction attribute has no interaction edit"

silver moat
#

yeah because respond returns an interaction object

#

.rtfm applicationcontext.edit

patent knoll
#

Ah yea thx, forgot about edit_original_response

young bone
naive steppe
#

hey, so im wondering if its possible to do multipstep autocomplete?

so i have the first command that uses autocomplete to select a variable in the config file for a server. would it be possible for the 2nd options input / autocomplete to change depending on the 1st selected?

such that if option 1 was "autoban" it would be true/false
but if it was "accountageflag" it would give you the ability to input day/month/year and then the amount?

naive steppe
#

ty 😄

patent knoll
young bone
topaz ruin
#

i've got a cog for a bot like this

from discord.ext import commands
import discord
from cogs_list import cogs_list

class Utils(commands.Cog):
    def __init__(self, bot: discord.Bot):
        self.bot = bot

    async def testcommand(ctx: discord.ApplicationContext):
        await ctx.respond(cogs_list)

def setup(bot):
    bot.add_cog(Utils(bot))

on line 3, "from cogs_list import cogs_list" when running the bot from the main file using

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

i get the error:
discord.errors.ExtensionFailed: Extension 'cogs.botutils' raised an error: ModuleNotFoundError: No module named 'cogs_list'

but when adding

...
from cogs_list import cogs_list

print(cogs_list)

class Utils(commands.Cog):
...

it prints the cogs just fine, why does it do this? it works when printing the variable normally by running the cog on it's own, but when calling it from the main code, it doesnt work

topaz ruin
#

inside the cogs_list is

cogs_list = [
    "cogname"
]

it's so the main file can load the cogs and so the "testcommand" can list them for future use
(testcommand will be renamed and should have @discord.slash_command too)

#

hold on, i got it to work using

from . import cogs_list
...
await ctx.respond(cogs_list.cogs_list)
young bone
topaz ruin
#

oh yeah, duh

proud mason
#

That would load all cogs from within that folder (and any subfolders)

#

👀

topaz ruin
#

alright, thank you 👍

ruby oriole
#

hey i got problem about installing pycord

young bone
ruby oriole
#

py-cord

young bone
#

And what is the problem?

ruby oriole
#

i'm already installing py-cord but when i run code containing slash_command it doesn't work

silver moat
#

?tag idw

patent knoll
#

do you actually import that?

obtuse juncoBOT
#

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

ruby oriole
patent knoll
#

from discord import slash_command

ruby oriole
#

i tried to install it

#

and same probleme

patent knoll
young bone
#

Show the pip list pls

silver moat
#

@patent knoll @young bone we don't need 3 people.

patent knoll
#

Yea i mean, i was already there

young bone
#

Same ;3

young bone
patent knoll
#

ah yes
my discord bugged again and stopped showing messages above that, the last message above the one i responded to is hours old
bye

ruby oriole
#

should i uninstall discord py when i'm using py-cord?

young bone
#

eh yes

#

?tag install

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

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

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

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

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

ruby oriole
wary rover
#

rHello,
Help, my two buttons don't line up. Do you have a solution? The spaces no longer work.
My perfectionist side is going to kill me

novel jay
#

Is there a event i can use to know when the bot goes offline (ex, shutting it down from docker)?

#

i tried using on_disconnect but it doesn't appear to fire

cyan quail
cyan quail
novel jay
#

fair ig

tidal narwhal
#

does anyone know what the boxes are and how i can add them in

zinc cloak
silver moat
zinc cloak
#

Would it be good if I added that to the docs

warped jungle
#

how do I get an user's avatar?

cyan quail
scenic raven
# novel jay Is there a event i can use to know when the bot goes offline (ex, shutting it do...

For docker Linux containers (idk how this works w/ Windows containers), SIGTERM is sent to each process to shut everything down. By default, this simply stops execution of your program, but if you want your program to something else when it's told to shut down, you can catch SIGTERM by attaching a handler to the event loop your bot runs in https://docs.python.org/3/library/asyncio-eventloop.html#unix-signals m

#

Also see the signals stdlib (you can have bad results if you try use only this with an async program tho)

fringe socket
#

Hey, I don't want any code, but can someone give me a basic outline for the logic behind a slash-based custom help command?

proud mason
#

Look into that

#

.rtfm slashcommand.mention

winter condorBOT
proud mason
#

.rtfm slashcommand.description

winter condorBOT
#

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

proud mason
#

.rtfm applicationcommand.description

winter condorBOT
#

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

proud mason
#

Uh huh

fringe socket
proud mason
#

Lol that's for prefix cmds

fringe socket
#

I'm using bridge anyways so it doesn't matter anyways lmao

#

Also, how can I get a set of all the commands on my bot in the guild of ctx?

#

My syntax highlighting is broken lol

#

and my intellisense

#

YES I FINALLY GOT THE THING!

silver moat
#

bruh files are terrible for mobile users

fringe socket
#

It gets around the message limit (to a point) ¯_(ツ)_/¯

silver moat
#

paginators

fringe socket
#

Can't be bothered

#

It's a lot harder

silver moat
#

how so?

fringe socket
#

It's just a pain to set up

silver moat
#

ig trading your ux for that is too much

fringe socket
#

💀 I just realized how large my bot is

#

It looks so small when split across cogs but...

#

Dang

silver moat
#

average projects

fringe socket
#

I have 24 lines of imports 💀

#

In one file

fringe socket
wind plinth
#

hi, my code was working before, however I factory reset my PC and reinstalled python and packages. I receive this error on my code: Module 'discord' has no attribute called 'Bot'. How can I remedy this?

coarse spire
wind plinth
#

...let me go do this

#

welp no change this time

#

my terminal does not recognize discord.py at all now though

coarse spire
#

can you show your pip list?

silver moat
#

what are the exact errors?

wind plinth
#

where can i find it?

coarse spire
wind plinth
#

module 'discord' has no attribute called 'Bot

silver moat
#

If you're using mac, it would be pip3

wind plinth
wind plinth
silver moat
#

uninstall discord, py-cord and reinstall py-cord

wind plinth
#

okaaa

#

same error persists

silver moat
#

restart IDE/terminal/whatever you use to run your bot

wind plinth
#

yeah nothing

silver moat
#

or more correctly, kill it and do it again

silver moat
wind plinth
#

yes

silver moat
#

how are you running your bot?

wind plinth
#

through vsc

silver moat
#

specifically how? Using a run button?

wind plinth
#

yes

silver moat
#

the version of the python you have selected, could you check it's pip list

wind plinth
silver moat
#

well, I don't enough information

wind plinth
#

oh okay, how can i find the more specific list?

silver moat
#

the standard pip could be different than the python you're running it from

#

and this seems to be an installation fault

wind plinth
#

makes sense

silver moat
#

It should be on the bottom right corner

wind plinth
#

hmmm no

#

i tried to find it thru select interpreter and its like that

silver moat
#

try using the global one

wind plinth
#

ohhhhhh

#

it worked! thank you lots

silver moat
#

If python -m pip list returns a proper list, then that should work

#

yay

round rivet
#

fuck ms store python

wind plinth
#

i wonder why the microsoft store vs is different?

fringe socket
round rivet
wind plinth
#

that makes a lot of sense. thanks

wheat stirrup
#

hey guys, I currently have this paginator that refuses to send. I switched to paginator.send() over paginator.respond() because the embeds were taking too long to build, and now it is giving me this error that I do not understand. Any help would be appreciated!

fringe socket
#

.codeblock

winter condorBOT
#

Please put your code in a code block:
```py
Here is your Code
```

That makes reading code in Discord a lot easier:

print("This is an example.")
somber pelican
#

also like the error says you have to pass ctx

wheat stirrup
#
@slash_command(name = "rankings", description = "view the server points rankings", guild_ids=guildIDs)
    async def rankings(self, ctx: ApplicationContext):
        db = await asyncpg.connect(user = 'postgres', password = 'gaming123', database = 'postgres', host = 'localhost')
        result = await db.fetch(f"SELECT * FROM goosmus WHERE guild_id = '{ctx.guild.id}' ORDER BY  gspts DESC, palpts DESC")
        embed = discord.Embed(title=f"Goosmus Points Rankings", description=f" in {ctx.guild}", color = 0x5198e4)
        leader = await db.fetch(f"SELECT * FROM goosmus WHERE guild_id = '{ctx.guild.id}' ORDER BY gspts DESC, palpts DESC LIMIT 1")
        leadermem = await ctx.guild.fetch_member(leader[0]['user_id'])
        embed.set_thumbnail(url = leadermem.avatar.url)
        embed.set_footer(text="Use the arrows below to navigate the ladder")
        embed2 = embed.copy()
        embed3 = embed.copy()
        embed4 = embed.copy()
        embed5 = embed.copy()
        embed6 = embed.copy()
        embed7 = embed.copy()
        embed8 = embed.copy()
        embed9 = embed.copy()
        discord_pages = [
            embed,
            embed2,
            embed3,
            embed4,
            embed5,
            embed6,
            embed7,
            embed8,
            embed9
        ]
        emojilist = {1: ':first_place:', 2: ':second_place:', 3: ':third_place:', 4: 
#
':four:', 5: ':five:', 6: ':six:', 7: ':seven:', 8: ':eight:', 9: ':nine:', 10: ':keycap_ten:'}
        paginator = pages.Paginator(pages=discord_pages, show_disabled=False, show_indicator=True)
        paginator.add_button(pages.PaginatorButton("next", label=">", style=discord.ButtonStyle.blurple))
        paginator.add_button(pages.PaginatorButton("prev", label="<", style=discord.ButtonStyle.blurple))
      
        
        page_idx = 0
        for i, v in enumerate(result):
            i += 1
            num = emojilist[i] if i in emojilist else f'{i}'
            usid = str(v['user_id'])
            goospts = str(v['gspts'])
            palpts = str(v['palpts'])
            member = await ctx.guild.fetch_member(usid)
            print(f"adding member {i}")
            discord_pages[page_idx].add_field(name=f'{num}: {member.name}', value=f'Goosmus Points: `{goospts}`    Pal Points: `{palpts}`', inline=False)
            if i % 10 == 0 and i != 0:
                page_idx += 1
        # await paginator.respond(ctx.interaction, ephemeral=False)
        await paginator.send(ctx)
#

for the error

#
Ignoring exception in command rankings:
Traceback (most recent call last):
  File "/usr/local/lib/python3.9/dist-packages/discord/commands/core.py", line 124, in wrapped
    ret = await coro(arg)
  File "/usr/local/lib/python3.9/dist-packages/discord/commands/core.py", line 976, in _invoke
    await self.callback(self.cog, ctx, **kwargs)
  File "/root/goosmus/serverxp.py", line 192, in rankings
    await paginator.send(ctx)
  File "/usr/local/lib/python3.9/dist-packages/discord/ext/pages/pagination.py", line 973, in send
    raise TypeError(f"expected Context not {ctx.__class__!r}")
TypeError: expected Context not <class 'discord.commands.context.ApplicationContext'>

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

Traceback (most recent call last):
  File "/usr/local/lib/python3.9/dist-packages/discord/bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "/usr/local/lib/python3.9/dist-packages/discord/commands/core.py", line 375, in invoke
    await injected(ctx)
  File "/usr/local/lib/python3.9/dist-packages/discord/commands/core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: expected Context not <class 'discord.commands.context.ApplicationContext'>
wheat stirrup
fringe socket
#

Try removing the type hint here:

ctx: ApplicationContext
soft girder
#

How to make it so that one person can press the button once. But the button must remain in working condition.

#

Is it possible to track the clicks of participants without issuing a role.

wheat stirrup
fringe socket
#

Why did you post this in #general too lol

spring hare
ebon dove
#

In a discord.Option, how can I accept more than one input type?

full basin
#

You can't

proud mason
#

Accept as string, and convert to whatever you want. That's your only choice

vague steeple
#

Does anyone know how I can add slash commands when the bot is as a class, so that it has a description and leads to a function?

example code:
class some_bot_name(discord.Bot):
def init(self):
<add slash command with description "abc" that leads to self.example>
def example(self, ctx):
await ctx.send("succesful")

waxen whale
#

Your request is sketchy af. If you don't need lib help, leave the server.

low dune
#

im sorry but how tat sketchy, i legit needed help testsing my join/leave thiiiiiiiiiiiingies but it ok

waxen whale
#

this server is not to get testers

full basin
#

Create an alt account?

pseudo surge
#

If anyone is available to chat about ext.pages and persistence, it would be much appreciated! I'm beginning to believe persistent paginators are a thing of myth and legend 😅

pseudo surge
# cerulean stump wdym

Paginators are a subclass of views. So in theory, adding them with bot.add_view on_ready and giving each component a custom_id without a timeout would render the paginator persistent (i.e., able to be interacted with after a bot restart). But this doesn't seem to work

full basin
#

Paginators and persistent views are complex thing lol.

#

I'm not sure if someone succeeded trying to make them persistent. You should try searching older posts

pseudo surge
gleaming falcon
#

Yikes, anyone ever see the error

WARNING:discord.gateway:Shard ID None heartbeat blocked for more than 60 seconds.
And then the process being outright killed? (oom)

proud mason
spring hare
#

Is there regex aliases for prefixed commands?

proud mason
#

If yk

#

Are your pages constant? Or are they dynamic (based on any inputs)

pseudo surge
#

At this point I'd be happy with figuring out how to do it with just generic example text on the pages.

full basin
#

You could create a basic paginator

pseudo surge
#

I'd like to see it being possible with something really simple before trying to make it work with my usecase

full basin
#

I meant, a basic paginator using normal views, doing it yourself instead of using ext.pages

pseudo surge
#

Oh I see what you're saying, yeah maybe. Would like to try everything here first though

warped jungle
#

When creating a slashcommand group, it returns that the command group has no attribute "name"

proud mason
#

What i will do is, make a function, that returns buttons with custom ids set

#

.rtfm paginatorbutton

proud mason
#

Create a list of 5 buttons in that, and return it

#

Pass that to use_custom_buttons in paginator

#

That kwarg might be named slightly different, not sure

#

Then make a paginator on ready, and pass it to bot.add_view

#

So smth like paginator = Paginator(..., use_custom_buttons=my_function())

pseudo surge
#

If so, then how will I call it in a command since it will be out of scope? I still want users to be able to post the paginator even if its contents are static

proud mason
#

the whole game is of custom ids

pseudo surge
#

Ok I'm trying it, will report back!

pseudo surge
# proud mason the whole game is of custom ids

Would it also work to use:

@bot.event
async def on_ready():
    print(f"We have logged in as {bot.user}")
    paginator = Paginator(pages=my_pages, use_default_buttons = False)
    paginator.add_button(
        PaginatorButton("prev", label="<", custom_id="paginator1", style=discord.ButtonStyle.green))
    paginator.add_button(
        PaginatorButton("page_indicator", custom_id="paginator2", style=discord.ButtonStyle.gray, disabled=True))
    paginator.add_button(
        PaginatorButton("next", label=">", custom_id="paginator3", style=discord.ButtonStyle.green))
    paginator.timeout = None
    bot.add_view(paginator)

#

When I use Paginator = Paginator(..., custom_buttons=my_function() I get Object is not Iterable error

cerulean stump
#

you have to pass custom_id

#

keep in mind that self.current_page will not be ok prob

cerulean stump
#
custom_buttons: Optional[List[:class:`PaginatorButton`]]
pseudo surge
# cerulean stump ``` custom_buttons: Optional[List[:class:`PaginatorButton`]] ```

Sorry not sure I completely understand. I was hoping the paginator.add_button solution would get around making a custom button function.

def customButtons():
    buttons = [PaginatorButton("prev", label="<", custom_id="paginator1", style=discord.ButtonStyle.green),
    PaginatorButton("page_indicator", custom_id="paginator2", style=discord.ButtonStyle.gray, disabled=True),
    PaginatorButton("next", label=">", custom_id="paginator3", style=discord.ButtonStyle.green)]
    for x in buttons:
        return x
paginator = Paginator(pages=my_pages, use_default_buttons = False, custom_buttons=customButtons()

TypeError: 'PaginatorButton' object is not iterable

#

Should customBottons() also be in its own class?

cerulean stump
#

not button (x)

pseudo surge
# cerulean stump not button (x)

Ah duh. Ok that solved the first error. The paginator now posts but it's not persistent. "This interaction failed" on bot restart.

proud mason
#

Hmm

proud mason
pseudo surge
#

Here's everything:

def customButtons():

    buttons = [PaginatorButton("prev", label="<", custom_id="paginator1", style=discord.ButtonStyle.green),
    PaginatorButton("page_indicator", custom_id="paginator2", style=discord.ButtonStyle.gray, disabled=True),
    PaginatorButton("next", label=">", custom_id="paginator3", style=discord.ButtonStyle.green)]
    for x in buttons:
        return buttons
@bot.event
async def on_ready():
    print(f"We have logged in as {bot.user}")
    paginator = Paginator(pages=my_pages, use_default_buttons = False, custom_buttons=customButtons())
    paginator.timeout = None
    bot.add_view(paginator)
@bot.command()
async def paginatortest2(ctx):
    paginator = Paginator(pages=my_pages, use_default_buttons=False, custom_buttons=customButtons())
    await paginator.send(ctx)
proud mason
#

Hmm paginator.send might be doing some stuff

#

Ah turn off author check

#

Also pass timeout to the init ?

pseudo surge
pseudo surge
# proud mason Also pass timeout to the init ?

And do you mean in the command like here?

@bot.command()
async def paginatortest2(ctx):
    paginator = Paginator(pages=my_pages, use_default_buttons=False, custom_buttons=customButtons())
    paginator.timeout = None
    await paginator.send(ctx)

Cause I tried that already 😦

proud mason
#

There are too many, i can't remember 😭

pseudo surge
# proud mason Hmm should be one of the parameters in the init

I was hoping this would work but no dice 😦

@bot.command()
async def paginatortest2(ctx):
    paginator = Paginator(pages=my_pages, use_default_buttons=False, custom_buttons=customButtons(), author_check=False)
    paginator.timeout = None
    await paginator.send(ctx)
#

I tried author_check=False there and in the on_ready

proud mason
pseudo surge
#

To be clear, the pages do change before restarting the bot

proud mason
#

You could do some "smart" workarounds

pseudo surge
pseudo surge
proud mason
# pseudo surge Such as? Not even sure what that means.

Ok this might be a bit weird, but it should be possible.

Make a subclass of PaginatorButton, and override the callback

In the callback, get the 3rd button in interaction.message.components (3rd button is index 2. This is the page indicator)

You will need to split the button label at / and get the first part. Convert it to an int. This is the current page number.

Set self.paginator.current_page to this

Then call super().callback with the interaction parameter

#

And use this subclass in your custom buttons function

pseudo surge
#

Ok I'm trying

tulip ledge
#

How to add a second button in a message?

pseudo surge
#

Must not be because now all interactions fail 😅

tulip ledge
silver moat
#

each view can have up to 25 buttons

tulip ledge
#

And, how to make multiple buttons? Multiple classes?

young bone
pseudo surge
proud mason
tulip ledge
pseudo surge
pseudo surge
# proud mason You can just do `components[2]` install of class getitem Also you forgot to cal...

interaction.message.components[0] prints as:

<ActionRow children=[<Button style=<ButtonStyle.success: 3> custom_id='paginator1' url=None disabled=True label='<' emoji=None>, <Button style=<ButtonStyle.secondary: 2> custom_id='paginator2' url=None disabled=True label='1/3' emoji=None>, <Button style=<ButtonStyle.success: 3> custom_id='paginator3' url=None disabled=False label='>' emoji=None>]>

There's nothing in [1] or [2]

full basin
#

Which can contain up to 25 components

proud mason
#

Pass interaction to it
(It is an async function)

pseudo surge
# proud mason Oh right. Should be `[0][2]`

Still no good, unfortunately

class ButtonClass(PaginatorButton):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

    async def callback(self, interaction: discord.Interaction):

        test = interaction.message.components[0][2]
        print(test)
        testsplit = test.split("/")
        index = int(testsplit[0])
        self.paginator.current_page = index
        await super().callback(interaction)```

Getting: 
```py
    test = interaction.message.components[0][2]
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^
TypeError: 'ActionRow' object is not subscriptable
proud mason
#

Btw that super callback looks perfect

pseudo surge
#

Ok, progress:

interaction.message.components[0].children[2] prints as:

<Button style=<ButtonStyle.success: 3> custom_id='paginator3' url=None disabled=False label='>' emoji=None>```

so the split doesn't work: `AttributeError: 'Button' object has no attribute 'split'`
pseudo surge
pseudo surge
# proud mason Hmm try `[0].children[2]`

Oh actually I think we wanted <Button style=<ButtonStyle.secondary: 2> custom_id='paginator2' url=None disabled=True label='1/3' emoji=None>

The 1 from the 1/3.

So I got this now by partitioning the string, selecting the [label number], converting to int, and setting to self.paginator.current_page = index

But this doesn't play nice with the page numbers. When you hit the button to go to the next page it jumps two pages instead of one and is locked there.

cerulean stump
#

so [0:N-1] for N pages

halcyon gorge
#

my pycord says that embeds cannot exceed 10 elements

silver moat
#

what are elements

pseudo surge
# proud mason Hmm try `[0].children[2]`

Ok so it all works now until the bot restarts. There is no 'interaction failed' but it doesn't advance pages and throws this error:

Ignoring exception in view <Paginator timeout=None children=3> for item <Button style=<ButtonStyle.success: 3> url=None disabled=True label='>' emoji=None row=0>:
Traceback (most recent call last):
  File "python3.11/site-packages/discord/ui/view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "[myfile]", line 67, in callback
    await super().callback(interaction)
  File "/pythonProject/venv/lib/python3.11/site-packages/discord/ext/pages/pagination.py", line 120, in callback
    await self.paginator.goto_page(
  File "/pythonProject/venv/lib/python3.11/site-packages/discord/ext/pages/pagination.py", line 694, in goto_page
    message_id=self.message.id,
               ^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'id'```
halcyon gorge
pseudo surge
silver moat
halcyon gorge
#
        embed=discord.Embed(title="Earnest Ice Cream", description="Fraser Street Location", color=0xFF5733)
        embed.add_field(name="Flavour", value="3", inline=True)
        await ctx.respond(embeds=embed)
proud mason
halcyon gorge
#

oh

#

ok that might be why

silver moat
#

yeah

halcyon gorge
#

this is what I get for having github copilot write it for me

soft girder
#

How to make it so that one person can press the button once. But the button must remain in working condition.
Is it possible to track the clicks of participants without issuing a role.

pseudo surge
proud mason
#

Could you share the final stuff?
This would be helpful to future travellers on this path

pseudo surge
proud mason
#

👍

brittle fable
#

Might be overlooking something very basic but.. I'm trying to send a message with my bot that pings a specific role. I'm using the syntax <@&[role id]> which gives me the correct role + color, but doesn't actually actually ping anyone with the role. The bot should have the correct permissions in the server it's in. Is there something I'm missing?

#

Oh I think I figured it out, seems like I can't ping in a ctx.respond ... is there any way to cleanly ping a role in response to a slash command?

grizzled sentinel
#

@chrome ore are you using pycord?

chrome ore
#

yes

grizzled sentinel
#

can you show the full error please

chrome ore
#

this is all what I am getting

eternal wing
#

I am trying my best to find a solution but i can't so i am coming here: I want the bot to play in a voice channel, i connect it and when it tries ```py
source = await discord.FFmpegPCMAudio("https://streams.ilovemusic.de/iloveradio1.mp3")

await channel.play(source)

i get an error

ffmpeg was not found

I can't find anything about that
young bone
#

Did you add it to the path?

#

also installed it with pip?

eternal wing
#

What path? I only installed ffmpeg with pip

young bone
grizzled sentinel
eternal wing
chrome ore
grizzled sentinel
# chrome ore I ll send you PM

please send it here unless it contains private information that you cant remove. This will help others be able to see how it was solved

chrome ore
#

cant can you please respond to my pm thanks a lot

eternal wing
lethal nexus
#

How can I check if a server is a community server or not?

silver moat
lethal nexus
silver moat
#

or something like that

eternal wing
lethal nexus
silver moat
lethal nexus
topaz ruin
#

is it possible to print the commands in all loaded cogs when the bot starts up?
something like

Logged in as [bot user]

Load cog: cog_name1
├─ command1
├─ command2

Load cog: cog_name2
├─ command1
├─ command2
eternal wing
silver moat
frail matrix
#

I'm trying to get my bot to send a message whenever someone says something in chat, but it doesn't seem to be doing anything, can anyone help me?

import discord
from core import Cog

class Responder(Cog):
    def __init__(self, bot):
        self.bot = bot

    @Cog.listener()
    async def on_message(self, message: discord.Message):
        if message.author.bot:
            return
        await message.channel.send('test message')

def setup(bot):
    bot.add_cog(Responder(bot))```
silver moat
#

Did you enable intents? (If you don't know what I'm talking about you probably don't)

#

@frail matrix

frail matrix
#

I think so, I have this in my bot.py file

class Milkbot(commands.Bot):
    def __init__(self) -> None:
        super().__init__(intents=discord.Intents.all())```
silver moat
#

how are you loading your cogs?

#

And what is core?

frail matrix
#

oh god thats embarrassing i just forgot to add it to the cogs in bot.py LMAO

#

thanks haha

silver moat
#

that happens

frail matrix
#

i always forget 😐

tulip ledge
#

What is the variable for server name and member count?

static juniper
#

how can i add a upload attachment option to slash command

full basin
full basin
tulip ledge
#

I type guild.members and guild.name, and it did not work

full basin
#

.idw

winter condorBOT
#

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

soft girder
#

Is it possible to see a WORKING example tasks loop

#

I'm studying now, and they write to me that the code given in the guide does not work

winter condorBOT
soft girder
#

I have a code that sends a list. But I need the list to update itself every time after a reload. And I need the update to happen every 5 seconds

#

Simply put, I need to remove the blue button, and make the bot update this message itself, even after a reboot.

#
class TlB(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button( label="Confirm participation",custom_id="button-1",emoji="✅",style=discord.ButtonStyle.success,row=1)
    async def button_callback(self, button: discord.ui.Button, interaction):
        

        guild = interaction.guild_id
        msg = interaction.message
        user = interaction.user

     
        cursor.execute(f"")
        db.commit()

        cursor.execute(f"")
        item2 = cursor.fetchmany(4)
        db.commit()
        b = "" .... 

class NS(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    game = SlashCommandGroup("newstate", "Various greeting from cogs!")


    out_game = game.create_subgroup("teamlist", "Teamlist commands")

 @commands.has_permissions(administrator =True)
    @commands.guild_only()
    @out_game.command(name='send', description='Displays TeamList.',guild_ids=[944934277777326090,769823680695107594])
    async def teamlist(self , ctx: discord.ApplicationContext,*,time: Option(str,max_length=17, description='Start time')):
        cursor.execute(f"")
        item2 = cursor.fetchmany(4)
        db.commit()

        await ctx.respond("Done.",ephemeral=True)
        b = ""
        i = 0
        for el in item2:
            i+=1
            b += f"**{i}**.{el[5]}__{el[1]}__ | {el[2]} | <@{el[3]}>\n"

        cursor.execute(f"")
        item = cursor.fetchmany(26)
        db.commit()

        a = ""
        f=4
        for el in item:
            f+=1
            if 4<f<17:
                a += f"**{f}**.{el[5]}__{el[1]}__ | {el[2]} | <@{el[3]}>\n"    
            if f>16:
                a += f"Res.🔴**{f}**.{el[5]}__{el[1]}__  | {el[2]}  | <@{el[3]}>\n"

        await ctx.send(f":scroll: __**TEAM LIST**__ :scroll:\n**🕐Time: `19:00` Moscow **\n \n{b}{a}\n \n
`•To confirm participation, click on :white_check_mark:\n•1-4 vip slots.`",view=TlB())
#

Regarding this code, where you need and how to insert it correctly tasks.loop

static juniper
#

how can i make multiple thread to a slash command so every can run command at a time

#

i just put a while loop in 1 command and it's never end

#

and then run it 2 time

#

and got this error

cyan quail
#

the docs example demonstrates it best

soft girder
full basin
#

While loop in a slash command Skull

cyan quail
#

you should really avoid while in commands unless you have a guarantee that it will end quickly, otherwise your entire bot stalls

static juniper
#

and when i put while 1: pass to it

#

and its stuck at the first command

cyan quail
#

that will loop infinitely yes...

#

while 1 is always true

static juniper
#

so how can i

#

multi thread it

cyan quail
#

you can't even attempt to do that with slash commands because of restrictions with interactions

full basin
#

Why you want a while loop in a command

#

I think that's the question

static juniper
full basin
#

for WHAT

cyan quail
#

you're probably looking for asyncio.run, but either way while is always blocking; it's only worth using if you actually have something awaitable

static juniper
cyan quail
#

just don't do while 1 then???

#

you literally can't get around it

full basin
#

Lmfao

static juniper
#

i already sent the respond

#

and then edit it later

cyan quail
#

having an eval or debug command is very normal, but while will always block your bot and you will have to restart

static juniper
#

💀

full basin
#

You're expecting to be able to handle an infinite loop? It's codings basics you never do that

cyan quail
#

it's as simple as not using while in the first place

static juniper
#

but others would

#

💀

cyan quail
#

why???????

static juniper
#

idk

cyan quail
#

maybe i can understand while k < 100 and increment k or something but that's just a for loop

#

if there's no condition to end the while loop then you're literally killing your bot

static juniper
#

💀 :(

full basin
#

While loops must have a condition that breaks them.

#

There's no usage.for infinite loops other than wasting time and resources

static juniper
#

can i use threading with my slash command?

full basin
#

Yes

static juniper
#

o

#

k

fervent cradle
#
    @tasks.loop(minutes=1.0)
    async def update_gaw_embed(self):
        print('loop running')
        await self.bot.execute("DELETE FROM giveaways WHERE startTime + duration < (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') - INTERVAL '2 days';")
        giveaways = await self.bot.fetch("SELECT * FROM giveaways;")
                
        for row in giveaways:
            channel_id = row['channelid']
            custom_id = row['customid']
            start_time = row['starttime']
            duration = row['duration']

            print(row)

            print(channel_id)
            print(custom_id)
            print(start_time)
            print(duration)

            channel = self.bot.get_channel(channel_id)
            message = channel.get_partial_message(custom_id)

            duration_seconds = duration.total_seconds()
            end_time = start_time + timedelta(seconds=int(duration_seconds))

            print(end_time)

            current_time = datetime.utcnow()
            if current_time > end_time:
                print('checked time')
                await message.edit(content="The giveaway has ended!")``` how can i check the time so that it edits the message? currently the start time, duration, and end time are in order: 2023-06-16 11:05:50.951275
19524 days, 11:06:11
2076-11-28 22:12:01.951275 seems like my calculation of end time is incorrect how can i fix this what am i doing wrong
static juniper
#

this code does not work

full basin
#

Not familiar with threading at all. Can't give you a good answer.

worldly schooner
#

when reloading an extension after adding a slash command it does not appear to me, do I will need to restart the bot if I add a new slash command instead of just reloading an extension?

cyan quail
#

(this may change in the future)

fervent cradle
proud mason
#

you need to use asyncio.run_coroutine_threadsafe

proud mason
static juniper
#

um how

proud mason
static juniper
#

ok

proud mason
#

can you show what dep is

static juniper
# proud mason well, you would need to show me more than this to understand the structure

@bot.slash_command(description="Debug a python file.")
@option("attachment", discord.Attachment, description="Add a python or text file here.", required=True)
async def debugfile(ctx: discord.ApplicationContext, att: discord.Attachment):
await ctx.defer()
embed = discord.Embed(title="Debug", description="Running...")
code = await att.read()
msg = await ctx.respond(embed=embed)
o = StringIO()
try:
with redirect_stdout(o):
exec(code.decode("utf-8"), globals())
embed.description = "\n" + o.getvalue() + "\n"
except Exception as e:
embed.description = "\n" + str(e) + "\n"
await msg.edit(embed=embed)

proud mason
#

?tag paste

obtuse juncoBOT
proud mason
#

would be easier

static juniper
#

oh ty

static juniper
proud mason
#

Where’s threading in that tho? 👀

static juniper
#

wait a sec