#Basic Pycord Help (Quick Questions Only)

1 messages · Page 69 of 1

silver moat
#

What do you want to happen? Could you provide an example?

errant vale
#

I have a function that returns a bunch of strings and integers that change every hour so it has to be called alongside the slash command. The slash command has an embed in it that then displays all that data

#

Could i put it below the decorator so that its called when the command is recieved but before the slash command?

silver moat
#

?tag botvar

obtuse juncoBOT
#

Need to keep track of a variable between functions? No problem!

⚠️ Careful what you name it though, else you might overwrite something ⚠️

Just add it to your commands.Bot or discord.Client instance like so:

bot = commands.Bot(...)
bot.my_variable = 0

async def foo():
    bot.my_variable += 1

# In a cog
@commands.command()
async def counter(self,ctx):
    await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))

This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance

errant vale
#

Ah so id just run the function beforehand and change the variables to ones under the bot object

errant vale
#

Ok cool

night pollen
#

Im using bot.reload_extension(f"cogs.{cog_name}") to reload a cog but its saying its not loaded while i can still use the commands in the cog. why is that? and how would i fix it?

solemn idol
night pollen
#

ah alr

errant vale
# silver moat yeah

are there certain disallowed variable names? this one doesnt seem to be assigning when i put it under the bot object bot.api_key = os.getenv("HYPIXEL_API_KEY")

#

oh nvm i read the error wrong sorry for ping

errant vale
#

for this command option here how would i make the list of members options? offline_ping_discord_tag:discord.Option(str, description="The Discord tag to be pinged when you go offline",choices=[]),

errant vale
#

members = [member.display_name for member in ctx.guild.members] offline_ping_discord_tag.choices = members doesnt seem to work

desert path
#

i think my issue got lost in chat 👀

silver moat
silver moat
#

If you are looking for dynamic choices, you can check out

errant craneBOT
#

Here's the slash autocomplete example.

errant vale
#

im thinking of doing something like that also using minecraft name api that autocompletes as you tpye your name in

desert path
proud mason
errant vale
#

so i can put that in choices?

silver moat
proud mason
#

Ah ok

errant vale
#

imma just ignore it fn until i reach the public stage

#

is there a way to make an interaction that is kinda like a form or ballot

#

i have a set of data that i need from the user and it would just be clunky to chuck it all in the /setup command as different fields with different choices

errant vale
#

im basically asking the user a bunch of attributes of a single item

#

they can click them

#

what data type does it return, and is there an example somewhere i can see of a working select menu?

silver moat
#

nothing better than trying it yourself.

errant vale
#

a list of strings is preferable, id asssume thats when you have more than one choice selected when the user confirms?

silver moat
#

yeah

errant vale
#

i can just force it to be in a list no biggie

errant vale
#

how do i do math with variables that are under bot object

#

bot.actiontime = bot.base_action_time/15(1+(.18*bot.rising_celsius_scalar)+(.2*bot.flycatcher)+(.05*bot.minionexpanders)+bot.infusion_scalar+bot.beacon_scalar) makes the error j:\infernal addons\hypixelapi.py:205: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma? bot.actiontime = bot.base_action_time/15(1+(.18*bot.rising_celsius_scalar)+(.2*bot.flycatcher)+(.05*bot.minionexpanders)+bot.infusion_scalar+bot.beacon_scalar)

#

oh turns out i just needed to add an asterisk to explicitly multiply the 15

covert kayak
#
intents=discord.Intents(65277)

Why does this return an error TypeError: Intents.__init__() takes 1 positional argument but 2 were given? Without the number the bot won't be able to read messages in my server.

covert kayak
#

Without the number the bot won't be able to read messages in my server.

#

The number is the number of intents

young bone
#

?tag intents

obtuse juncoBOT
#

https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents

import discord
from discord.ext import commands

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

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

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

# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

covert kayak
#

Just yesterday this code worked fine

#

Now it keeps returning errors

#

😭

solemn idol
#

Traceback?

covert kayak
#

Usually when it runs there is going to be colored line like this

#

But now there is no more

young bone
#

?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)
covert kayak
#

commands.Bot

errant vale
#

how come i cant use functions in slash commands

errant vale
#
async def embedsetup(ctx: discord.ApplicationContext):
    await test()
    if hypergolic_sell_price != 0:
        await ctx.respond('embed variables set!')```  ```File "j:\infernal addons\main.py", line 393, in embedsetup
    await test()
TypeError: object NoneType can't be used in 'await' expression

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

Traceback (most recent call last):
  File "C:\Python310\lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Python310\lib\site-packages\discord\commands\core.py", line 375, in invoke
    await injected(ctx)
  File "C:\Python310\lib\site-packages\discord\commands\core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: object NoneType can't be used in 'await' expression```
#

def test(): print("test")

young bone
#

lol

#

its really easy to see why its not working

errant vale
#

whats happening

errant vale
young bone
#

Im not sure if you know basic python

errant vale
#

im learning ive only had the course for 2 months

young bone
#

#help-rules

errant vale
#

ive made it really far

proud mason
proud mason
errant vale
#

i just cant seem to figure out why i speciffically cant run a function within a function if i put it in await

#

cuz its asynchronous

proud mason
young bone
#

^

proud mason
#

you defined it with def, not async def pogbruh

errant vale
#

oh that seems very obvious

young bone
errant vale
#

im almost done my bot

#

ive made a whole bunch of games

covert kayak
#

Why does from discord.ext import commands return an error

covert kayak
young bone
#

did you also uninstall and reinstall py-cord?

covert kayak
#

done

young bone
#

and close the terminal after it

green hinge
#

Can I customize the profile description of a user on my server via bot?

green hinge
# young bone no?

Okay too bad, thought that might work for the server because you can also change the nickname

young bone
#

the the user name

green hinge
covert kayak
#

ok I fixed it 🥳

#

Which one of these data structure should I use to have the best speed? I want to be able to retrieve both single data within a specified type and also all data regardless of type.

{
  "type 1": {
    "data 1": {...},
    "data 2": {...}
  },
  "type 2: {
    "data 3": {...},
    "data 4": {...}
  }
}

or

{
  "data 1": {"type": 1, ...},
  "data 2": {"type": 1, ...},
  "data 3": {"type": 2, ...},
  "data 4": {"type": 2, ...},
}
hybrid flower
#

subcommand of SlashCommandGroup, guild_ids parameter does not work?

proud mason
#

Discord limitation

#

Cuz subcommands are just a different type slash cmd option for the parent cmd

hybrid flower
#

OK, I SEE

fallen cove
#

Any recommendations for getting a channel or category with a specific name so it would get the target even if it’s not in the cache

proud mason
#

i dont recommended it tho, as fetch guild is slow and has high ratelimits

hybrid flower
#

if the guild_ids parameter contains a guild id that guild does not add the bot, the re-register act will all failed.

fallen cove
hybrid flower
#

first time bot started with guild_ids=[1,2], its worked, second time with guild_ids=[1,3], but the guild with guild id 3 was not add the bot, so the command re-register to guild_ids 1,3 was failed with DISCORD Forbidden, but bot was running, and command still in guild 1,2

proud mason
proud mason
hybrid flower
hybrid flower
jovial vapor
#

How do I add commands in other files (or cogs) using slash commands ?

import discord
from TOKEN import TOKEN

bot = discord.Bot()

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

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

bot.run(TOKEN) # run the bot with the token

With the commands extensions, I can add cogs without any problem, but how am I supposed to do using the slash commands ?

young bone
jovial vapor
#

Where should I load it then ? And how to add slash commands to the other file ? Sorry if this is a question that has been posted a hundred times, I've been coding bots when slash commands were not a thing yet and now I feel completely lost

young bone
proud mason
# hybrid flower

you are missing app cmds scope. invite the bot again with it (no need to kick the bot)

glad remnant
#

Is there a way how to read uploaded csv file? pepehmm

attachment: discord.Attachment

proud mason
glad remnant
#

Yessir

proud mason
# glad remnant Yessir

i would read it and save it into a bytesio
smth like f = io.BytesIO(await attachment.read()) and then use the csv library to read the bytesio

glad remnant
#

Yeah reading that bytesIO is where I struggle

#

nvm got it

night pollen
#

How can i autocomplete with a list of members in a slash command? Tried alot and since i cant use ctx since its not defined outside the command function im kinda stuck.

full basin
#

Typehint discord.Member

night pollen
#

Yea i toguht of that but couldnt get it to work

#

ill try again tho

#

gimme a few

tropic cradle
#

Is it possible for a but to include a local video file in a message?

#

I my bot setup to have yt-dlp download a linked video and then respond with it but it posts as a file and isn't watchable. I'm thinking the answer is no, but it would be pretty cool to be wrong

full basin
#

?tag localfile

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

so i got to discord.Guild.members and a few other things that seemed like it would be helpfull to me but i got nothing to work, mind giving me another nudge in the right direction?

proud mason
#

Also, is the downloaded file playable directly on your pc?

full basin
night pollen
# full basin Provide the code you're using

    @commands.slash_command(name="ban", description="Ban a user")
    async def ban(self, ctx, member: discord.Option(str, autocomplete=discord.utils.basic_autocomplete(discord.Guild.members)),  reason):
        for member in ctx.guild.members:
            print(member)

dont mind what the command is doing, was just testing a bit

tropic cradle
#

Playable on pc, but the message is a link to the file

full basin
proud mason
full basin
#

The library does all the job

errant craneBOT
#

Here's the slash options example.

proud mason
night pollen
full basin
#

Code again?

#

And show what you see

tropic cradle
#
file = discord.File("tiktok.mp4")
####


@bot.command(description="test")
@option("test", description="test")
async def test(ctx):

    await ctx.respond(file = file, ephemeral=True)
night pollen
#

    @commands.slash_command(name="ban", description="Ban a user")
    async def ban(self, ctx, member: discord.Member,  reason):
        for member in ctx.guild.members:
            print(member)

Sorry if i made a dumb mistake or something, havent wroked with python in a while.

#

2 sec ill get the ss

#

ok

#

wtf, i swear it didnt load

#

well it works now, thanks

proud mason
tropic cradle
#

It appears to be a codec issue, but I was about to give up thinking it wasn't possible so thank you for putting me on the right track!

plush moat
#

I'm struggling a bit with decorators

Say I have

@bot.slash_command(name="setbalance", guild_ids=[GUILD], description="tempDescription")
async def setbalance(ctx,
                  user: Option(discord.Member, required=False, description="tempDescription")):
```, and I'd want to run a functon before and after this using decorators

```py
def transactional(func):
    async def wrapper(*args, **kwargs):
        print("before func")
        result = func(*args, **kwargs)
        print("after func")
        return result
    return wrapper

however, if I put it like

@transactional
@bot.slash_command(name="stats", guild_ids=[GUILD], description="Give stats across all orders")

the "before func" and "after func" doesn't get printed, and if I put it like

@bot.slash_command(name="stats", guild_ids=[GUILD], description="Give stats across all orders")
@transactional

it includes "**kwargs" as an argument I can pass to my bot's command

How would I best go about doing this?

silver moat
plush moat
proud mason
#

even better, use @before_invoke and @after_invoke

plush moat
#

what's the differnece between @before_invoke @after_invoke vs @on_application_command @on_application_command_finish?

proud mason
#

before invoke actually halts the command from running until the function has executed

#

and before/after can be set different per command

plush moat
#

I see, so I'd do something like

@bot.slash_command(name="stats", guild_ids=[GUILD], description="Give stats across all orders")
@bot.before_invoke(setup)
@bot.after_invoke(cleanup)

for all the functions where that's relevant?

proud mason
#

you can even set those either for all cmds in the bot, for all cmds in the cog, all in the group or for a single cmd

proud mason
#

smth like

@bot.slash_command(...)
async def my_command(...):
    ...

@bot.slash_command(...)
async def your_command(...):
    ...

@my_command.before_invoke
@your_command.before_invoke
async def before(ctx)
    ...
#

.rtfm before_invoke

proud mason
#

before/after invoke is there on many classes depending on where you want to do it

plush moat
#

That's great!

#

Tysm, I'm gonna look into it more. This sounds like exactly what I need

plush moat
plush moat
#

Sick! tysm, that has been stumping me for a few days now ^^

viscid sluice
#

Is it possible to change async def dice(self, ctx, bet_on: int = 6, amount: int): to async def dice(self, ctx, amount: int, bet_on: int = 6):? Because when I do that I get the error SyntaxError: non-default argument follows default argument

limber urchin
#

No, just like the error says you can't have a non-default argument after a default one

#

And this isn't even correct Python syntax

viscid sluice
limber urchin
viscid sluice
#

I dont know thats why Im asking

limber urchin
#

To set a value on the amount parameter means you have to set a value on your bet_on parameter as well. Which means having a default value on bet_on is absolutely useless because you're always explicitly setting a value to it anyways.

#

It's an error for a reason

viscid sluice
viscid sluice
#

So flip bet_on and amount?

limber urchin
#

Yes?

viscid sluice
#

How?

limber urchin
#

By flipping them??

viscid sluice
#

But thats not possible

#

Then comes the error

limber urchin
#

._.

viscid sluice
#

So?

limber urchin
#

Then the error is from something else

viscid sluice
limber urchin
#

What?

#

I'm saying what you have right now doesn't work

viscid sluice
limber urchin
#

?????

viscid sluice
#

🥲

#

I want to flip bet_on and amount

#

async def dice(self, ctx, amount: int, bet_on: int = 6):

#

But then comes the error

proud mason
proud mason
#

its not possible

viscid sluice
viscid sluice
proud mason
proud mason
viscid sluice
#

The other works

viscid sluice
viscid sluice
proud mason
# viscid sluice

the error shows you are using async def dice(self, ctx, bet_on: int = 6, amount: int):

#

||also thats dpy||

viscid sluice
#

Im stupid

viscid sluice
#

Alright now

viscid sluice
#

And that was my question

silver moat
viscid sluice
#

And how do I do that?

limber urchin
viscid sluice
#

A normal question

limber urchin
#

Read rule 1 in #help-rules

maiden nexus
#

is it possible to add buttons to images?

proud mason
maiden nexus
#

and adding a button to this

#

or yea that would work as well sending a message with it

proud mason
maiden nexus
#

right

#

what I did instead earlier was use reactions instead

proud mason
#

you can have one below it

maiden nexus
#

oh yea that's what I meant

#

like for embeds

proud mason
#

yea you can do that

maiden nexus
#

o ok ty

maiden nexus
# proud mason yea you can do that

also like I'm using a lot image manipulation and making profiles for many commands, is there anything I should be aware of? Like I usually don't see a lot of bots using images to show info and more of embeds.

proud mason
#

but should be fine otherwise

maiden nexus
#

alright got it ty

silk spindle
#

.rtfm thread

silk spindle
#

how do I detect if a message is from a thread?

silver moat
#

message.channel would be a thread object iirc

silk spindle
#

Found it ! Need guilds=True as Intents

finite flame
#

how can ApplicationContext.message be None?
below is the code and exception I've got (working with a custom context)

class ApplicationContext(discord.ApplicationContext):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.bot: ServiceDroid
        self.lfg = LFGData(self)

    @property
    def guild(self) -> Guild:
        return Guild.get(self.interaction.guild_id)

    @property
    def own_perms(self) -> discord.Permissions:
        return self.channel.permissions_for(self.message.guild.me)
Traceback (most recent call last):
  File "C:\projects\python\discord_bots\service_droid\.venv\Lib\site-packages\discord\commands\core.py", line 124, in wrapped
    ret = await coro(arg)
          ^^^^^^^^^^^^^^^
  File "C:\projects\python\discord_bots\service_droid\.venv\Lib\site-packages\discord\commands\core.py", line 978, in _invoke
    await self.callback(self.cog, ctx, **kwargs)
  File "C:\projects\python\discord_bots\service_droid\cogs\custom.py", line 73, in lfg_slash
    if ctx.own_perms.manage_messages:
       ^^^^^^^^^^^^^
  File "C:\projects\python\discord_bots\service_droid\classes\context.py", line 39, in own_perms
    return self.channel.permissions_for(self.message.guild.me)
                                        ^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'guild'```
finite flame
#

just asked myself the same thing and it doesn't look like it, no idea why my linter was suggesting it
wouldn't make any sense anyways since slash commands aren't casted with a normal message

proven mantle
#

How can i run a async function with pycord in a synchronus function?
I tried asyncio.run which throws asyncio.run() cannot be called from a running event loop

limber urchin
proven mantle
#

Oh yeah. I meant Pycord

limber urchin
#

.rtfm Bot.loop

winter condorBOT
#

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

limber urchin
#

.rtfm loop

limber urchin
#

k nvm then

proven mantle
#

So ```py
member = asyncio.run_coroutine_threadsafe(guild.fetch_member(int(msg["data"]["userID"])), self.client.loop).result()

young bone
proven mantle
#

I used get_member before but that uses cached data which is not always up to date

young bone
#

ye

worldly schooner
#

recently ive been getting this error:
discord.errors.Forbidden: 403 Forbidden (error code: 90001): Reaction blocked

#

It was working all fine since I noticed my bot wasnt reacting anymore

full basin
worldly schooner
cyan quail
#

if your cached members don't have the correct info then you're somehow doing something wrong elsewhere, or perhaps you're working at far too large a scale

shut jasper
#

what is wrong with this code?

#

returns admin not found

#

1089419657749987418 my id

#

if i make it an int it says

frail matrix
#

I have a ui view for a select menu that accepts arguments from the user when they run a slash command. So I put the view into on_ready to make it persistent, and then I need to pass data into that view to initalize it and the select menu. But what happens if I have multiple select menus? What do I put into on_ready?

proud mason
# shut jasper

can you show how you define the var, and how you call bot.get_user

proud mason
#

i assume you store the data which you pass in a db

frail matrix
#

yeah its in a db

proud mason
#

so just iterate over than and create a new view for every different select menu

frail matrix
#

so i have to add the view for each active select menu?

proud mason
#

yes

frail matrix
#

ok cool thanks

proven mantle
finite flame
#

why does time_amount: discord.Option(name="amount", description="The amount of time", input_type=int) give me a string even tho I'm specifying I want an int?

cerulean yacht
#

is there anyway to unregister guild command registered using this^?

finite flame
finite flame
#

dunno, never did this so far

winter condorBOT
# finite flame why does `time_amount: discord.Option(name="amount", description="The amount of ...

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)?

proud mason
#

even tho tag is for smth else, the checklist still applies

errant craneBOT
#

discord/bot.py line 419

raise NotImplementedError```
finite flame
proud mason
#

can you try using @option

tough lion
#

how to run my bot on pythonAnywhere?

fervent cradle
#

how can I edit a buttons lable after I pressed it?

this is the code

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

    @discord.ui.button(label="Ja", style=discord.ButtonStyle.green, custom_id="yes_button")
    async def yes(self, button, interaction):
        await interaction.response.edit_message(components=[Button(label='Hello', custom_id='yes_button')])```
limber urchin
#

You need to edit the button and then edit the message with your view

silver moat
#

Pycord also doesn't have a components kwarg.

fervent cradle
limber urchin
#

You already have the button as a parameter in your callback

#

You don't need to create a new

fervent cradle
#

do you mean like this:

limber urchin
#

Change the label of the button and then edit the message with your view again

fervent cradle
#

        button.lable = "hello"

        await interaction.response.edit_message(view=self)```
limber urchin
#

yes?

#

but you don't need interaction.response

#

just do self.message

fervent cradle
limber urchin
#

you don't need interaction.response
just do self.message

fervent cradle
full basin
fervent cradle
#

when I do it with this: py await interaction.response.edit_message(view=PollView()) I get no error, but the button lable doesn't change

limber urchin
fervent cradle
#

and when I do it with py await self.message.edit_message(view=self) I get this error: AttributeError: 'NoneType' object has no attribute 'edit_message'

limber urchin
#

That's just going to reset everything about it

fervent cradle
#

oh

#

but how should I do it then?

limber urchin
#

Just use self?

full basin
#

try py await interaction.response.edit_message(view=self)

fervent cradle
#

without any error

full basin
#

Code

fervent cradle
#
 async def yes(self, button, interaction):

        button.lable = "Hello"

        await interaction.response.edit_message(view=self)```
full basin
#

lable

fervent cradle
#
@discord.ui.button(label="Ja", style=discord.ButtonStyle.green, custom_id="yes_button")```
full basin
#

button.lable

#

lable

#

It's label

fervent cradle
#

oh

proud mason
full basin
limber urchin
#

You prbably can, but it looks like a pretty bad way to host a bot

#

You only get a set amount of CPU-seconds per day and only 1GB disk space for the $5/mo plan

#

You can get way better on pretty much any VPS provider

silver moat
#

even Replit's better

young bone
limber urchin
#

I'm guessing it's another one of those "Hey I found a free hosting service, I bet I can host my bot on this"

#

As if there's ever going to be a good and free way to do that

silver moat
#

I also found a free hosting service, ||localhost||

limber urchin
#

What do you guys think of my website?
http://localhost:8000/index.html

young bone
young bone
silver moat
young bone
#

found it

silver moat
#

file not found

young bone
#

Im not sure if they fixed it

silver moat
#

maybe because I'm on mac

young bone
#

...

fervent cradle
#

why is my bot returning None for the channel if it has access

async def send_to_discord(fields, channelid):
    channel = bot.get_channel(channelid)
    if channel is None:
        print(f"Could not find channel with ID {channelid}")
        return
    embed = discord.Embed(title=f"ok")
    for field in fields:
        embed.add_field(name=field["name"], value=field["value"], inline=field["inline"])
    await channel.send(embed=embed)```
fervent cradle
#

hello, i want to ask if the pycord docs are outdated

#

i replicated everything on the docs, even tried to copypaste (ew) after 7 mins of nothing but i still get errors, i have fixed that tho, just here to ask

silver moat
fervent cradle
#

this one

silver moat
#

the second question?

fervent cradle
#

what part of the docs shows how to make a handler

silver moat
#

what handler

fervent cradle
#

command handler

#

like cleaner index and each command in a file

#

like discord.js

silver moat
#

Well, that's not Pythonic, but you would be looking at cogs.

fervent cradle
#

okay thanks

fervent cradle
silver moat
fervent cradle
silver moat
#

umm what

fervent cradle
#

except if you're working with discord.ext commands

#
intents= discord.Intents.default()
client = discord.Client(intents=intents)
silver moat
#

discord.Bot should work just fine.

fervent cradle
silver moat
#

what IDE are you using

fervent cradle
silver moat
#

ah yup that makes sense.

#

?tag replit

obtuse juncoBOT
silver moat
#

tl;dr replit doesn't work with pycord very well.

fervent cradle
#

oh so i have to start from pylex vps then

silver moat
#

or just like use an actual IDE like visual studio code or pycharm

#

?tag ide

obtuse juncoBOT
fervent cradle
#

is this enough for a vps

silver moat
fervent cradle
silver moat
#

Visual Studio Code is pretty lightweight across all OS.

fervent cradle
silver moat
#

but again, my bot has like a huge message cache

fervent cradle
silver moat
#

my bot is in around 150 ish servers and has a peak ram usage of 500 ish mb

fervent cradle
#

mb 💀

silver moat
#

really depends on your bot.

fervent cradle
#

my current bot is made with discord.js (moving to py thats why im here) and currently eating 6 gb ram

#

only 55 servers

limber urchin
#

What on earth are you storing in memory to reach that

fervent cradle
limber urchin
#

45 database tables?

fervent cradle
#

yes

limber urchin
#

Why

fervent cradle
#

leveling, counting, guess the number, cookie clicker game on discord, tictactoe, most of them are leaderboards and full of people as over 3000 people use the bot

#

which is such a omg for a non verified bot

limber urchin
#

It sounds like you could definitely rethink your database structure, and look at why you're using 6gb of ram

silver moat
#

yeah pretty sure this isn't a language issue.

fervent cradle
#

i wont, i am moving to discord.py so i don't have to

limber urchin
silver moat
limber urchin
#

Changing languages won't magically make things use less ram, you need to look at the actual problem

fervent cradle
fervent cradle
silver moat
#

what

limber urchin
#

Either way, this is pycord. Which means we won't help you with discord.py or any other lib for that matter.

fervent cradle
#

i don't feel like developing in it anymore

fervent cradle
silver moat
#

well, what was the topic on hand again?

fervent cradle
#

just i am going to use a vps for it, thanks for the info

silver moat
#

ok

fervent cradle
#

hope i did not disturb anyone, peace sus_tb_fade

silver moat
#

cya

fervent thunder
silver moat
#

?tag idw

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.

fervent thunder
#

Traceback (most recent call last):
File "C:\Users\miche\Downloads\bot\bot.py", line 40, in <module>
@bot.slash_command(name="modaltest")
^^^^^^^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'slash_command'. Did you mean: 'add_command'?

#

Here's the error I'm having

fervent thunder
#

aiohttp 3.8.4
aiosignal 1.3.1
async-timeout 4.0.2
attrs 22.2.0
certifi 2022.12.7
chardet 4.0.0
charset-normalizer 3.1.0
click 8.1.3
colorama 0.4.6
configparser 5.3.0
discord 1.7.3
discord.py 2.2.2
discord-py-slash-command 4.2.1
discord-webhook 1.1.0
Flask 2.2.3
frozenlist 1.3.3
idna 3.4
itsdangerous 2.1.2
Jinja2 3.1.2
markdown-it-py 2.2.0
MarkupSafe 2.1.2
mdurl 0.1.2
multidict 6.0.4
numerize 0.12
pip 23.0.1
psutil 5.9.0
py-cord 2.4.1
Pygments 2.14.0
pypresence 4.2.1
requests 2.28.2
rich 13.3.3
setuptools 65.5.0
typing_extensions 4.5.0
urllib3 1.26.15
Werkzeug 2.2.3
yarl 1.8.2

silver moat
#

go ahead and uninstall discord, discord.py, and discord-py-slash-command. py-cord as well so you can reinstall it with

pip unisntall discord discord.py discord-py-slash-command py-cord -y
pip install py-cord
fervent thunder
#

pip uninstall discord discord.py discord-py-slash-command py-cord -y

#

done

silver moat
#

this isn't your terminal..

fervent thunder
#

huh

lean creek
#

sum(i for i in range(1, 101) if i%2 == 1) why does my code not work?

silver moat
#

close/restart your terminal/IDE

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.

lean creek
#

oops

silver moat
#

for all I know you could want to add 1 and 3

lean creek
#

im trying to get the sum of all odd numbers from 1-100 but it says int object is not callable

lean creek
#

sorry im new to coding 💀

silver moat
#

the error has a traceback

fervent thunder
#

Ignoring exception in on_connect
Traceback (most recent call last):
File "C:\Users\miche\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "C:\Users\miche\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 1164, in on_connect
await self.sync_commands()
File "C:\Users\miche\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 738, in sync_commands
app_cmds = await self.register_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\miche\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 531, in register_commands
prefetched_commands = await self._bot.http.get_guild_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\miche\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 371, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In guild_id: Value "Ellipsis" is not snowflake.

lean creek
silver moat
lean creek
silver moat
fervent thunder
#

yes

silver moat
lean creek
#

uh okay

fervent thunder
#

command_prefix=commands.when_mentioned_or("!"), debug_guilds=[myguildid?], intents=intents

silver moat
#

so by showing that, I can help you better

lean creek
#

how do i show that 😭

silver moat
fervent thunder
#

ok

#

thanks got it

silver moat
fervent thunder
#

if i wanted to, how would i get it to be a button, then the menu pops up

lean creek
fervent thunder
#

is that possible?

errant craneBOT
#

examples/modal_dialogs.py lines 69 to 102

@bot.command()
async def modaltest(ctx: commands.Context):
    """Shows an example of modals being invoked from an interaction component (e.g. a button or select menu)"""

    class MyView(discord.ui.View):
        @discord.ui.button(label="Modal Test", style=discord.ButtonStyle.primary)
        async def button_callback(
            self, button: discord.ui.Button, interaction: discord.Interaction
        ):
            modal = MyModal(title="Modal Triggered from Button")
            await interaction.response.send_modal(modal)

        @discord.ui.select(
            placeholder="Pick Your Modal",
            min_values=1,
            max_values=1,
            options=[
                discord.SelectOption(
                    label="First Modal", description="Shows the first modal"
                ),
                discord.SelectOption(
                    label="Second Modal", description="Shows the second modal"
                ),
            ],
        )
        async def select_callback(
            self, select: discord.ui.Select, interaction: discord.Interaction
        ):
            modal = MyModal(title="Temporary Title")
            modal.title = select.values[0]
            await interaction.response.send_modal(modal)

    view = MyView()
    await ctx.send("Click Button, Receive Modal", view=view)```
silver moat
lean creek
silver moat
lean creek
#

wait here they didn't turn it into a list tho

silver moat
fervent thunder
#

yes

silver moat
#

You send a view with a button on it

fervent thunder
#

with what command

silver moat
silver moat
fervent thunder
#

something like this

silver moat
#

What about that

fervent thunder
#

but when u click it pops up a menu

silver moat
#

yes you can do that

lean creek
fervent thunder
#

is their a guide on it?

#

I don't know where I would start

silver moat
silver moat
lean creek
#

oh

#

ok thx

silver moat
#

Not sure why you are going for one-liners but whatever

fervent thunder
#

Traceback (most recent call last):
File "C:\Users\miche\Downloads\phisher\bot.py", line 69, in <module>
@bot.slash_command()
^^^^^^^^^^^^^^^^^^^
File "C:\Users\miche\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 930, in decorator
result = command(**kwargs)(func)
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\miche\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 1788, in decorator
return cls(func, **attrs)
^^^^^^^^^^^^^^^^^^
File "C:\Users\miche\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 686, in init
_validate_descriptions(self)
File "C:\Users\miche\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 164, in _validate_descriptions
validate_chat_input_description(obj.description)
File "C:\Users\miche\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 1899, in validate_chat_input_description
raise error
discord.errors.ValidationError: Command and option description must be 1-100 characters long. Received "Shows an example of modals being invoked from an interaction component (e.g. a button or select menu)"

#

i tried making it a slash command

#

this is the error

fervent thunder
#

im stupid

silver moat
fervent thunder
#

please help me

silver moat
#

how

fervent thunder
#

I'm trying to code, but I can't, I'm trying to code a bot that can do /embed and create a embed, with a working one button, that opens up the menu, then can send to a channel or webhook

#

what's happening here

silver moat
#

Because i have a feeling this will clump this chat, please create a new post and ping me once your done.

fervent thunder
#

ok

fervent cradle
#

Why am I getting this error:

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

this is my code:

class PollViewNew(discord.ui.View):
    def __init(self):
        super().__init__(timeout=None)

    options = [
        discord.SelectOption(label="Yes", description="Vote for yes", emoji="👍"),
        discord.SelectOption(label="No", description="Vote for no", emoji="👎")
    ]
    @discord.ui.select(
        min_values=1,
        max_values=1,
        placeholder="Select an option",
        options=options,
        custom_id="poll_select"
    )

    async def select_callback(self, select, interaction):
          pass
young bone
fervent cradle
ornate current
#

How can i make persistent giveaways?

young bone
ornate current
#

Like multiple giveaways and they wont stop even if the bot restarts

young bone
#

?

ornate current
#

Buttons

#

multiple persistent views??

young bone
#

give them a custome id and set the timeout to None

ornate current
#

all of the custom ids need to be different?

young bone
#

You mean for the same button? no

#

if you have more than one than every button need his own custome id

spring hare
#

What possible problems may appear with scaling discord bots? (If do not take into account the specifics of the code) Is sharding hard and what other code changes do I need if I decide to shard my bot (Or I just need to change Bot to AutoShardedBot, and start new bot instances?)

ornate current
#

Best way to make asyncio.sleep? so it works even after bot restarts?

#

Should i use asyncio.sleep and store the time a giveaway finishes and in the on_ready i should use multithreading to restart their asyncio.sleep where it left off earlier?

undone falcon
#

How do you check the help for hosting?

#

Like ?host

#

In bot commands

full basin
#

What

undone falcon
#

With the bot for this server

#

Like ?nojson

finite flame
novel yacht
#
    @discord.slash_command(name='give_funds', description='Give funds to a user', guild_ids=[796804050305417276],)
    async def give_funds(self, ctx, member: discord.Member, count: int):
        staff_roles_ids = [913710830602829854, 928969191795609670, 995817536010600498]
        if ctx.author.id not in staff_roles_ids:
            await ctx.respond('You do not have permission to use this command.', ephemeral=True)
            return
```but i have role this
drifting birch
#

When doing await ctx.respond("test") in my slash command, I'm getting a 404 Unknown interaction. It doesn't happen on my other commands. What could be the cause of this?

solemn idol
drifting birch
#
@discord.slash_command(name="searchh")
  async def search(self, ctx, search: discord.commands.Option(
    str,
    description="Thing you want to search for in the Wiki",
    required=True,
  )):
    page_id = fandom.search(search, results=1)[0][1]
    page = fandom.page(pageid=page_id)
    print(page.title)
    print(page.summary)
    #print(page.sections)
    #for section in page.sections:
    #    print(page.section(section))
    await ctx.send("test")
    await ctx.respond("test")

The printing and ctx.send work, but ctx.respond gives the 404

solemn idol
#

hmm I dont really see anything wrong with the command, maybe it needs to be defered I am not sure...

#

.rtfm defer

drifting birch
solemn idol
proud mason
errant craneBOT
#

Here's the slash options example.

#

Here's the modal dialogs example.

fervent thunder
#

#1094093451294937088

#

can someone help me here?

limber urchin
fervent thunder
#

what

limber urchin
#

Everyone has to follow them, including you

fervent thunder
#

im asking a question

#

im asking how i would do it, please

limber urchin
#

Read rule 6

fervent thunder
#

i understand that, i'm waiting

#

no one has responded for at least 10 hours

limber urchin
#

And that makes you exempt from the rules?

fervent thunder
#

what

#

Bruh, you make no sense, I've waited, I'm asking,

#

For someone to look.

#

Please

limber urchin
#

How am I making "no sense"? I'm telling you to follow the rules, which you are not doing.

#

I don't care how long you've waited for, you still need to follow all rules in #help-rules

fervent cradle
#

can someone help my channel id isnt working even tho it should

async def send_to_discord(fields, channelid):
    channel = bot.get_channel(channelid)
    if channel is None:
        print(f"Could not find channel with ID {channelid}")
        return
    embed = discord.Embed(title=f"ok")
    for field in fields:
        embed.add_field(name=field["name"], value=field["value"], inline=field["inline"])
    await channel.send(embed=embed)```
#

its a func

#

but await send_to_discord(fields, 1092588870337573018) dosent work

#

its a valid channel

#

im using bot = discord.Bot(intents=discord.Intents.all()) and it has all intents in the portal

winter condorBOT
fervent cradle
#

theres nothing else about it dude

#

Could not find channel with ID 1092693725139968060

#

thats a different output

#

but u get it

#

the error is just "cant send to type none"

silver moat
#

If the channel is None, you can try fetching the channel

#

.rtfm bot.fetch_channel

silver moat
#

You cannot fetch a channel before on_ready

fervent cradle
#

oh

silver moat
#

.rtfm wait_until_ready

fervent cradle
#

ok thx

silver moat
#

which would also explain why your channel cache is empty.

fervent cradle
#

no its still giving errors

#

it said it was ready and on ready was moved up to before the func and stuff

silver moat
#

send code?

#

and error

fervent cradle
#
@bot.event
async def on_ready():
    print('Logged in as {0.user}'.format(bot))

async def send_to_discord(fields, channelid):
    channel = await bot.fetch_channel(channelid)
    if channel is None:
        print(f"Could not find channel with ID {channelid}")
        return
    embed = discord.Embed(title=f"ok")
    for field in fields:
        embed.add_field(name=field["name"], value=field["value"], inline=field["inline"])
    await channel.send(embed=embed)```
silver moat
#

You still aren’t waiting for pn_ready to fire.

fervent cradle
#

is there a difference?

#

cuz i wait till it says its ready then i do what im doing'

silver moat
#

Where are you doing that

fervent cradle
#

no like

#

when it prints its ready in the console

silver moat
#

The order of the functions doesn’t mean anything.

fervent cradle
#

heres what the output looks like


error goes here```
#

its ready

#

then i do it

#

so i would be waiting for nothing right?

silver moat
fervent cradle
#
import multiprocessing as mp

def start_bot():
    bot.run("not for you mr hakr man!11")

def start_webapp():
    web.run_app(app)

if __name__ == '__main__':
    bot_process = mp.Process(target=start_bot)
    bot_process.start()

    webapp_process = mp.Process(target=start_webapp)
    webapp_process.start()

    bot_process.join()
    webapp_process.join()```
#

this wouldnt change anything right?

#

im using aiohttp and it works when i run the bot without the webserver

limber urchin
#

Why are you using multiprocessing if you're on aiohttp? The whole point of aiohttp is to run it asynchronously

fervent cradle
#

yeah but when i do it for some reason dosent run properly and only runs the web app

#

or if i put the bot above it it only runs the bot

#

so i tried mp

limber urchin
#

Probably because you're starting your web server incorrectly, and bot.run is blocking so yeah, that's of course going to only run the bot

fervent cradle
#

how am i starting it incorectly

limber urchin
#

I don't know, how are you starting it?

fervent cradle
#

web.run_app(app)????

#

do i do async run

limber urchin
#

You need to start it on your bots event loop

fervent cradle
#

huh

limber urchin
fervent cradle
#

sigh opens chatgpt

#

its fine guys i have gpt 4 😎

silver moat
#

If you can’t read documentation or know fundamentals, that’s not something AI can solve for you.

fervent cradle
limber urchin
#

At least people go to chatgpt to get spoonfed now instead of crying here doggokek

limber urchin
#

Eh, less people asking basic questions here means the helpers have more time to answer people who actually have real issues NPCMechanicShrug

fervent cradle
#

¯_(ツ)_/¯

silver moat
#

I mean, maybe AI conjuring methods out of thin air is normal.

#

I remember it was like button.view.delete()

fervent cradle
#

😭

#

wait

#

maybe i got it

#

no i dont got it

    loop = asyncio.new_event_loop()
    loop.call_soon(start_bot())```

```def start_bot():
    bot.run("e")
    web.run_app(app)```
#

is this not correct

#

am i dumb

#

its only running discord bot

#

wat da fak

#

OH I AM DUMB

#

no nvm its still not working

silver moat
#

go sleep

fervent cradle
#
def start_bot():
    bot.run("MTA5MjY5MzA4NDY1Mjk2NTg4OA.Gvvd8b.dfgdfgd
F-VHKNcs7h63nA-Wlo")


def start_webapp():
    web.run_app(app)

if __name__ == '__main__':
    loop = asyncio.new_event_loop()
    loop2 = asyncio.new_event_loop()
    loop.call_soon(start_bot())
    loop2.call_soon(web.run_app())```
#

shity

fervent cradle
#

no im to [wfbgrwi

silver moat
#

MTA5MjY5MzA4NDY1Mjk2NTg4OA.Gvvd8b.OTk51x_pREeHjmoOncnKi-VHKNcs7h63nA-Wlo

fervent cradle
#

😭

#

wait fuck

young bone
fervent cradle
#

its k

#

i reset

#

yknow i just now realize i started working on this yesterday at 7am

#

its 431 rn

#

wtf

fervent thunder
#

damnt

#

i was about to send a meme

fervent cradle
silver moat
#

go sleep and use environment variables

#

In that order

young bone
#

for me its 1:32 am sooooooo

fervent cradle
#

its 4:37 pm u ghave bad tim zone

silver moat
fervent cradle
#

433*

#

im bad at typeing

silver moat
#

just go to bed…

#

sleep and talk less

fervent cradle
#

buttttt discrd botttttt

#

😔

silver moat
#

Without you there is no Discord bot.

young bone
fervent cradle
#

this ^^^

errant craneBOT
#

Use the buttons below to search for sleep on the internet.

fervent cradle
#

that is the most usless commend

#

@silver moat you were so close

#

ok fine ill sleep

#

gn

young bone
#

@silver moat where are you from?

silver moat
young bone
#

aww

#

its fine ^^

coarse cargo
#

Im trying to get the emoji that should be in the button from a .yml file but it throws Invalid emoji.

This is my button >

@discord.ui.button(
            label=f"{ticketpanelconf['button_text']}",
            style=discord.ButtonStyle.green,
            emoji=f"{ticketpanelconf['button_emoji']}",
            custom_id="openticket-button"
        )

And this is the Key and Value >

button_emoji: ":incoming_envelope:"
fervent cradle
#

a moderator asking a question!?

#

what is this bafoonary

#

(joke)

limber urchin
#

If it's a nitro emoji, you need to use the <:emoji_name:emoji_id> format.

fervent cradle
#

i am literally unable to fall asleep because of this shitty bot

#

also

#

im using a Bot not a Client

#

so that wouldnt work anywayy

limber urchin
#

Bot inherits Client...

silver moat
fervent cradle
#

i tried anyway and it still didnt work

limber urchin
#

"didnt work" gives us nothing

fervent cradle
#

it runs the bot and never the app

#

no errors

#

it just dosent run

limber urchin
#

And what does your code look like now?

fervent cradle
#
async def run_webapp():
    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, 'localhost', 8080)
    await site.start()
    
app = web.Application()
app.router.add_get('/e', get_info)
app.router.add_get('/', index)
app.router.add_get('/{path}', redirect)


bot = discord.Bot(intents=discord.Intents.all(), loop=run_webapp())```
limber urchin
#

Why are you passing loop as a parameter?

fervent cradle
#

is it not a parameter

#

im so confused dawg

limber urchin
#

Exactly, so why are you using it as one?

desert path
#

hey i need some help w modals

#

is there such thing in pycord as there is in discord.py?

    name = discord.ui.TextInput(
        label='Name',
        placeholder='Your move here',
    )
#

the .textinput part

fervent cradle
#

im too tired for this

desert path
#

oh

#

ic lol

#

thank

limber urchin
fervent cradle
#

spoonfeed me the code and i will pay you

#

im genuinly on the verge of banging my head on the wall until life feels good again

#

😭

silver moat
#

I think your mentality is a bigger issue than your code rn.

limber urchin
fervent cradle
#

ok i give up on this project

#

back into the trash like the other 200 failed discord bots

#

😭

desert path
#

For this line of code :class Moving(discord.ui.Modal,title="Hi"):
I got this error: TypeError: Moving.__init_subclass__() takes no keyword arguments

but when i removed the title part is says it needs a title 😦

#

how do i add a title in pycord :C

silver moat
desert path
#

whats OOP?

silver moat
#

object-oriented programming

desert path
#

oh well not rlly

silver moat
#

concepts like polymorphism, inheritance, and abstractions

desert path
#

nah i dont lol

silver moat
desert path
#

yea ;/

silver moat
#

You are trying to inherit from Modal.

#

Do you know what a constructor is?

desert path
#

yeah

silver moat
#

do you know what super() does?

desert path
#

i've heard of it but no

silver moat
#

super() returns the parent class or super class.

desert path
#

ic

silver moat
#

of your child class.

#

so to access the parent class’s constructor, you would use super().__init__(). This would usually be the first line of your child class’s constructor.

desert path
#

oh i think i get it

#

super().__init__(title="Hi")?

silver moat
desert path
#

lol thx

desert path
#

looks like this chat died

#

i needed some help with this error:

In data.components: Must be between 1 and 5 in length.
#

what does that mean?

jaunty jewel
#

dynamic command choices in pycord 🤨

full basin
jaunty jewel
#

something like that but change by the user input

linked with database to fatch and get the data from it and not limited with 25 choice max

full basin
#

That's literally what autocomplete is

errant craneBOT
#

Here's the slash autocomplete example.

jaunty jewel
jaunty jewel
limber urchin
#

Autocomplete and choices are different things

#

Autocomplete can be fully dynamic and doesn't force the user to pick one of the choices. And does not have the same limits as choices do.

jaunty jewel
stark walrus
#

In your online leaderboard for levels
How do you display the usernames of your leaderboard people?
Do you store usernames separately in the database as well?

#

Because I don't think it is efficient to fetch_user all the time

full basin
#

You just need the username and pfp

stark walrus
#

Yup

#

But from where should I get that?

full basin
#

Storing it makes more sense

stark walrus
#

Oh

#

alright then!

full basin
#

But you work with the risk of the user changing their username or pfp

stark walrus
#

No

#

There is a on user update event right

#

I could have it update just their username in my database

full basin
#

Sure

stark walrus
#

ty for your input too

desert path
full basin
desert path
#

nvm i figured it out

silver moat
#

These are just some edge cases, there may be more.

limber urchin
#

You can always just build your own cache to store the usernames and re-fetch the names less frequently.

#

And if you want it to be persistent between bot restarts, use something like Redis for your cache

proud mason
limber urchin
#

unless you specify a time to live on the cache

proud mason
#

True

fervent cradle
#

can i pay you

proud mason
#

I do this shit for free kek

fervent cradle
#

you deserve better ong

#

ill finish tomorrow i need sleep

meager mica
#

so im confused how im supposed to pass arguments into my modal with title i tried ReplyModal(user_id, suggestion, title="Respond to user")
but i still get missing 1 required keyword-only argument: 'title' here is my class ```py

class ReplyModal(discord.ui.Modal):
def init(self, user_id: int, suggestion: str, *args, **kwargs) -> None:```

stark walrus
#

Why does on_interaction make your commands fail

proud mason
meager mica
#

oh

#

lol

proud mason
meager mica
#

thanks

proud mason
#

haha np

stark walrus
#

Oh thanks

proud mason
# stark walrus Oh thanks

oh and why do you need that event? dont use that event for buttons. buttons have callbacks which you can set

stark walrus
#

I want to update my user cache

#

I store userid, username, pfp url in cache

#

Want it to update every time a command is used

proud mason
#

ah

#

dont use this event then

stark walrus
#

it's a valid application for on_interaction?

#

Oh

proud mason
#

cuz it is fired for buttons too

stark walrus
#

Then what do you recommend

proud mason
#

use on_application_command

stark walrus
#

Oh that existed-

#

Thanks

fervent thunder
#

File "C:\Users\miche\OneDrive\Desktop\test\bot.py", line 9, in <module>
class MyModal(ui.Modal, title=test"):
File "C:\Users\miche\OneDrive\Desktop\phisher\bot.py", line 10, in MyModal
name = ui.TextInput(label="Test", placeholder="", style=discord.TextStyle.short)
^^^^^^^^^^^^
AttributeError: module 'discord.ui' has no attribute 'TextInput'
PS C:\Users\miche\OneDrive\Desktop\tes>

stark walrus
#

That's @bot.listen() or @bot.event?

fervent thunder
#

?

proud mason
stark walrus
#

Alright

#

Thank you!

proud mason
#

np

stark walrus
#

What argument does on_application_command have?

proud mason
#

.rtfm on_application_command

proud mason
#

1st one

stark walrus
#

Thankss

proud mason
#

btw there is on_application_command_completion too
that one is only fired if the slash command runs successfully

proud mason
stark walrus
fervent thunder
# proud mason `ui.InputText`

File "C:\Users\miche\OneDrive\Desktop\phisher\bot.py", line 9, in <module>
class MyModal(ui.Modal, title="Test"):
File "C:\Users\miche\OneDrive\Desktop\phisher\bot.py", line 10, in MyModal
name = ui.InputText(label="Test", placeholder="", style=discord.TextStyle.short)
^^^^^^^^^^^^^^^^^
AttributeError: module 'discord' has no attribute 'TextStyle'

#

it should be discord.InputTextStyle

fervent thunder
proud mason
frail matrix
#

how do i convert role data thats stored in a database into role objects?

fervent thunder
#

How would I add a button to this code to make it pop up a menu, where I can put info where it sends to a discord webhook?

import discord
from discord.ext import commands

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

@bot.slash_command()
async def create_embed(ctx):
    embed = discord.Embed(
        title="Test",
        description="Test",
        color=discord.Color.og_blurple()
    )
    embed.set_author(name="")
    embed.set_image(url="")

    embed.add_field(name="test", inline=False)
    embed.add_field(name="test", inline=False)
    embed.set_footer(text="")
    await ctx.send(embed=embed)

bot.run("My Bot Token!")
fervent thunder
#

why not?

#

ok i'll change it

young bone
fervent thunder
#

ye, i don't understand it

young bone
#

Do you know basic python?

fervent thunder
#

kinda, im not the best

fervent thunder
# young bone Do you know basic python?
import discord
from discord.ext import commands

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

class VerifyButton(discord.ui.Button):
    def __init__(self):
        super().__init__(
            label="Verify",
            style=discord.ButtonStyle.green,
            row=1
        )
        
    async def callback(self, interaction: discord.Interaction):
        # Replace this with your modal code if you have one
        await interaction.response.send_message("Verification modal opened.")

@bot.slash_command()
async def create_embed(ctx):
    embed = discord.Embed(
        title="Test",
        description="",
        color=discord.Color.og_blurple()
    )
    embed.set_author(name="")
    embed.set_image(url="")

    embed.add_field(name="Why do you need to verify?", value="Test", inline=False)
    embed.add_field(name="Test", inline=False)
    embed.set_footer(text="")
    view = discord.ui.View().
    view.add_item(VerifyButton())
    
    await ctx.send(embed=embed, view=view)

bot.run("My Bot Token!")
#

I made it where's their a verify button, but I want to open a menu

#
import discord
from discord.ext import commands

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

class VerifyButton(discord.ui.Button):
    def __init__(self):
        super().__init__(
            label="Verify",
            style=discord.ButtonStyle.green,
            row=1
        )
        
    async def callback(self, interaction: discord.Interaction):
        modal = VerificationModal()
        await modal.start(interaction)
        

class VerificationModal(discord.ui.Modal):
    def __init__(self, title="Verification", *args, **kwargs) -> None:
        super().__init__(title=title, *args, **kwargs)
        
        input_short = discord.ui.Input(
            label="Short Input",
            placeholder="Placeholder Test",
        )
        input_long = discord.ui.Input(
            label="Longer Input",
            placeholder="Placeholder Test",
            multiline=True,
        )
        
        self.add_item(input_short)
        self.add_item(input_long)

        
@bot.slash_command()
async def create_embed(ctx):
    embed = discord.Embed(
        title="Test",
        description="",
        color=discord.Color.og_blurple()
    )
    embed.set_author(name="")
    embed.set_image(url="")

    embed.add_field(name="Test", value="Test", inline=False)
    embed.add_field(name="Test", value="Test", inline=False)
    embed.set_footer(text="")
    view = discord.ui.View()
    view.add_item(VerifyButton())
    
    await ctx.send(embed=embed, view=view)

bot.run("My Bot Token!")
#

What's wrong with this code

proud mason
#

interaction.response.send_message to send the modal

#

The name for input text is discord.ui.InputText

#

Also as the other guy said, don't use / as a prefix. It will be a pain in the ass to use the prefix cmds of the bot

fervent thunder
#

But, how would I fix this code to be a button that opens open a modal?

#

the menu
class VerificationModal(discord.ui.Modal):
def init(self, title="Verification", *args, **kwargs) -> None:
super().init(title=title, *args, **kwargs)

    input_short = discord.ui.Input(
        label="Short Input",
        placeholder="Placeholder Test",
    )
    input_long = discord.ui.Input(
        label="Longer Input",
        placeholder="Placeholder Test",
        multiline=True,
    )
    
    self.add_item(input_short)
    self.add_item(input_long)
proud mason
#

.rtfm response.send_modal

winter condorBOT
errant craneBOT
#

Here's the modal dialogs example.

fervent thunder
#

TypeError: BotBase.init() missing 1 required keyword-only argument: 'intents'
PS C:\Users\miche\OneDrive\Desktop\test

proud mason
#

?tag intents

obtuse juncoBOT
#

https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents

import discord
from discord.ext import commands

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

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

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

# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

ornate current
#

How do i continue an asyncio.sleep() if the bot restarts??

young bone
#

Do you have it in a command than no

ornate current
#

i wanna make a giveaway bot

#

and the asyncio.sleep() stops when the bot stops

#

i dont want that

cyan quail
#

save the relative times in a file or db and use tasks to check if the time has passed

young bone
#

^

novel yacht
#

how fix?

import discord
from discord.ext import commands

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

    @discord.command(name='poll', description='poll', guild_ids=[796804050305417276])
    async def poll(self, ctx, *, question):
        embed = discord.Embed(title=question)
        message = await ctx.send(embed=embed)
        reactions = [':white_check_mark:', ':x:']  # define reactions as a list of emojis
        for i in range(len(reactions)):
            await message.add_reaction(reactions[i])

            
def setup(bot):
    bot.add_cog(QuickPoll(bot))```
proud mason
#

and do message = await ctx.original_response() after responding

novel yacht
#
AttributeError: 'Interaction' object has no attribute 'add_reaction'

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

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/discord/bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 375, in invoke
    await injected(ctx)
  File "/usr/local/lib/python3.8/dist-packages/discord/commands/core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'Interaction' object has no attribute 'add_reaction'```
proud mason
#

you should also refactor this part

        for i in range(len(reactions)):
            await message.add_reaction(reactions[i])

python allows you to iterate over members of a list

so it should be

        for r in reactions:
            await message.add_reaction(r)
proud mason
novel yacht
#

thx

frail matrix
#

how do i convert role data thats stored in a database into role objects?

young bone
proud mason
#

Get role should be the best way to do it

young bone
frail matrix
#

i need to reference the guild for those, right?

#

whats the best way to do that?

heady fractal
#

could there be a memory leak in pycord? my i can see a steady increase in the ram usage on my bot in the last days

heady fractal
#

from the 4th of april it started at 72mb and it slowly increased up to 165 mb

#

message, servers and presence

#

so all 3

young bone
#

Or for what

frail matrix
#

i need it inside the on_ready function

young bone
#

What do you do at the on_ready funtion?

#

Other question

#

Will the bot be public or at a privat server

frail matrix
#

private

heady fractal
young bone
#

If the bot will be privat you can just use ```py
guild = client.get_guild(id)

frail matrix
#

oh you meant the other question lol

#

so i have some select menus that take arguments from the user through slash commands. to make them persistent, i need to add them to on_ready, but i need all the roles to pass into the view when i add them to on_ready. so i've stored all of the select menu's data in a database, but now i need to reconstruct the roles so i can put them in the view in on_ready

#

i dont know if that makes any sense

young bone
heady fractal
#

I don't have an exact number but i'd say over 300 @young bone

young bone
proud mason
proud mason
#

Try limiting the message cache size if you want

heady fractal
#

i'll monitor for a few more days and see if it plateaus out

proud mason
#

Does your ram keep rising and breach 200 MB ?

heady fractal
#

not yet

proud mason
heady fractal
#

it hasn't been running for that much yet

#

i'll keep monitoring for a few weeks and come back if it's an issue

proud mason
#

Sure 👍

frail matrix
#

ok i did it, i did self.get_guild() inside on_ready

young bone
frail matrix
#

inside a subclass of Bot

finite flame
frail matrix
#

whats the normal way?

finite flame
#

with a listener

frail matrix
#

im confused

#

what the proper way i should be doing this?

young bone
#

.rtfm listener

young bone
frail matrix
#

uhhh ok this seems like something i shouldve been doing

fervent cradle
#

What about use of discord.Enums as option types, I can’t get it to work, when I try the slash command it is recognized as a string option

young bone
frail matrix
#

hahah

young bone
#

this one should help

proud mason
#

.rtfm slashcommandoptiontype

proud mason
# novel yacht what you mean?

blobpain
unlike ctx.send, ctx.respond doesnt return the message object

you need to get the message object using await ctx.original_response()

frail matrix
young bone
#

bot.listen or bot.event but I dont right really which one it better to use

proud mason
proud mason
frail matrix
#

ok im going to read everything, thanks for the help everyone

#

be back tomorrow with more questions

ornate current
silver moat
ornate current
#

...

limber urchin
#

They're both discord API wrappers, one of them isn't going to have some magic feature that the other doesn't

#

They're different implementations of the same API.

proud mason
#

they are largely the same except app cmds lol

silver moat
#

I think that’s it

proud mason
merry dune
#

I have question how create indefinite timeout here

class MyView(discord.ui.View): 
    @discord.ui.button(label="Verify", style=discord.ButtonStyle.primary, emoji="😎")
    async def button_callback(self, button, interaction):
        user = interaction.user
        dt1 = user.joined_at.date()
        dt2 = datetime.date.today()
        tdelta = (dt2 - dt1)
        mindate = datetime.timedelta(days=30)
        if tdelta >= mindate:
            await interaction.response.send_message(f"{user} you verification started, wait couple minutes for check u profile", ephemeral = True)
            for channel in interaction.guild.text_channels:
                counter = 0
                async for message in channel.history(limit = 1000):
                   if message.author == bot.user:
                       counter += 1
            if counter >= 100:
                 await interaction.user.send("you verified")
                 roleid = 856942394862600273
                 role = interaction.guild.get_role(roleid)
                 await user.add_roles(role)
            else:
                 await interaction.use.send("you verify denied")
        else:
            await interaction.response.send_message(f"{user} you verification denied", ephemeral = True)
        
@bot.slash_command() 
async def button(ctx):
    embed = discord.Embed(title="Verify on Events", description="")
    await ctx.respond("Click the button to verify participation in events", view=MyView(), timeout=None) 

And my code ended and works finepogthumbsup

proud mason
novel yacht
#

Who made timeout command?

fervent thunder
#

what's happening here? no error

limber urchin
#

ctx.respond, not ctx.send

fervent thunder
#

ok

fervent thunder
# limber urchin ctx.respond, not ctx.send
 File "C:\Users\miche\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\miche\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\miche\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'respond'
limber urchin
#

Are you not using slash commands?

fervent thunder
#

no

#

should i?

limber urchin
#

Do you want to?

fervent thunder
#

no not really, but does it affect the code?

fervent thunder
#

i would

limber urchin
#

Are you getting the error after sending the command?

#

You need to explain more, we can't just guess from a screenshot

fervent thunder
#

after sending the command