#Basic Pycord Help (Quick Questions Only)

1 messages · Page 27 of 1

undone falcon
#

I had a typo in the message sorry, I never use debug_guilds

cyan quail
#

upgrade to 2.2.2

undone falcon
cyan quail
#

(honestly not sure why you're on 2.2.1, 2.2.2 released 40 minutes after)

#

what if you change the position of the Option? like move it earlier

undone falcon
#

the commands wont even register back

#

it disappeared when I commented it

#

And when I decommented it, it does not come back

cyan quail
#

is this in all guilds?

undone falcon
#

no with guild_ids

#

with my test guild inside

cyan quail
#

could you try adding another guild?

undone falcon
#

I can yes, but that bot is in only that guild

#

it is a test bot

undone falcon
cyan quail
#

hmmm odd

#

can you show your main file?

undone falcon
#

I am gonna show the start only

#

because a bit big

#
import asyncio
from datetime import datetime, timedelta
import discord
import os
from discord.ext.commands.errors import MissingPermissions
from BackupGenerator import BackupGenerator
from MarkdownDiscord import Message
from RoleTimeOutChecker import RoleTimeOutChecker
from cogs.AddCog import AddCog
from cogs.RemoveCog import RemoveCog
from cogs.ShowCog import ShowCog
from cogs.TimezoneCog import TimezoneCog
from data import Data
from discord.ext.commands import Bot
import logging
from constant import LOCAL_TIME_ZONE, TOKEN, guildIds
from data_structure.TimedRole import TimedRole

logging.Formatter.converter = lambda *args: datetime.now(tz=LOCAL_TIME_ZONE).timetuple()


#logging
logger = logging.getLogger("discord_commands")
logger.setLevel(logging.ERROR)
file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "logs", "commands.log")
handler = logging.FileHandler(filename=file, encoding="utf-8", mode="w")
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)

loggerStart = logging.getLogger("discord_start")
loggerStart.setLevel(logging.INFO)
loggerStart
file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "logs", "start.log")
handler = logging.FileHandler(filename=file, encoding="utf-8", mode="w")
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
loggerStart.addHandler(handler)


intents = discord.Intents.none()
intents.members = True
intents.guilds = True

bot: Bot = Bot(intents=intents)
data = Data()
timeChecker = RoleTimeOutChecker(data, bot)
backup = BackupGenerator(data)

bot.add_cog(TimezoneCog(bot, data))
bot.add_cog(ShowCog(bot, data))
bot.add_cog(RemoveCog(bot, data))
bot.add_cog(AddCog(bot))
#

and of course in the end bot.run(TOKEN)

cyan quail
#

have you overridden any events?

undone falcon
#

yes multiple

cyan quail
#

can you show them

#

or if it's too long, just name the ones you've overridden

undone falcon
#
@bot.event
async def on_guild_join(guild: discord.Guild):
    loggerStart.log(logging.INFO, "Bot just joined {}. The bot is now in {} guilds. Guilds: {}".format(guild.name, len(bot.guilds), bot.guilds))

@bot.event
async def on_guild_remove(guild: discord.Guild):
    loggerStart.log(logging.INFO, "Bot just left {}. The bot is now in {} guilds. Guilds: {}".format(guild.name, len(bot.guilds), bot.guilds))
    server = data.getServer(guild.id)
    data.servers.remove(server)
    data.saveData()

@bot.event  
async def on_guild_role_delete(role: discord.Role):
    # No need to remove role from members, because the on_member_update event will be trigger for each member who lost the role
    data.delete_time_role(role.id, role.guild.id, remove_role_in_members=False)
    
@bot.event     
async def on_member_remove(member: discord.Member):
    data.remove_member(member.id, member.guild.id)

bot_start_time = None
@bot.event
async def on_connect():
    global bot_start_time
    bot_start_time = datetime.now(LOCAL_TIME_ZONE)

cyan quail
#

aaand there it is

undone falcon
#

there is also on_application_command_error, on_member_update, on_ready

cyan quail
#

if you override on_connect, you must include await bot.sync_commands()

undone falcon
cyan quail
#

allgood

harsh dust
#

is there a way to prevent random "The application did not respond" errors?

#

I use await ctx.defer() in every command

#

and sometimes it runs fine but then it throws an error when trying to do await ctx.respond()

cyan quail
#

if it's random then it's likely a network issue

#

or you have potentially blocking code that runs before the callback

drifting sleet
#

Is it possible to convert discord emoji into raw/unicode emoji? like :thumbsup: > 👍

frozen salmon
drifting sleet
drifting sleet
frozen salmon
#

Could you explain more?

drifting sleet
#

I need an actual 👍, not 👍 or \👍

frozen salmon
#

OH

frozen salmon
drifting sleet
#

well I'm asking because my bot generates flags, based on country code by adding it to :flag_xx:, but now I need that emoji to be added into discord.ui.Select option label, which doesn't resolve :emojis:

#

unicode emojis work there, but not sure if there's an easy conversion

cyan quail
#

partialemoji should work

drifting sleet
#

InvalidArgument: PartialEmoji is not a custom emoji

pallid token
#

Just wondering if there's a way to create a group of commands and sub-commands in which someone could execute the main command or a sub-command. E.g.:
</queue:1234>
</queue clear:1234>
</queue remove:1234>

I see a way in which you could have the sub-command groups, but not the actual main command.

pallid token
# full basin You can't. Discord limitation

Thought so... Thanks though 🙂
Pretty dumb tbh.
Any word on if they will implement it? As I recall there was some form of controversy around it when slash commands first launched.

silver moat
pallid token
#

One more question, if you don't mind... Is SlashCommandGroup#command() compatible with the same usage as commands.slash_command()? Like can you specify a name and description in the same manner?
E.g.:

@<SlashCommandGroupObj>.command(name="list", description="Get a list of songs in the queue.")
cyan quail
#

yeah

pallid token
#

Thanks 😄

spice oyster
silver moat
spice oyster
indigo badger
#

Is there a way to add a column with aiosqlite without Useing the app and locking the db?

#

As I am trying to add one as part of a update to my warning system and I run the bot and nothing happens.

#

I would use the app but last time I used that it locked the db.

#

If anyone knows and could tell me that would be great:

#

Or even if there is not a way let me know.

rugged lantern
#

wym locking the database? why would it get locked over adding a new column

#

if that's the case then you should get your skills checked

rugged lantern
indigo badger
#

The SQLite app.

rugged lantern
#

then you probably didn't click the obvious 'write changes' button on top

#

i assume u mean in db browser

indigo badger
#

Yes.

rugged lantern
#

yeah so the issue is a skill issue- u need to actually commit whatever you're writing. i see no other reason why it'd lock up

indigo badger
#

The thing is when I go to click the thing that says write changes it’s greyed out.

lost valley
#

Bot wont send a variable as a message. For example x = "hey there", the bot just says x instead of the value,

await channel.send(kd)
copper dew
lost valley
#

yeah im just dumb figured it out 💀 nvm ty

rare ice
#

ok

indigo badger
#

For some reason, my code keeps erroring the line where it says
async def unwarn(ctx: commands.Context, *, ID)
And that worked in the past with getting context with a slash command.

#

But now it is erroring.

#

I would send the error, but my Discord on my computer is not working

#

Validation Error.

#

If anyone knows a solution to this that would be great.

#

And that worked in the past, so that’s why I’m confused.

#

If anyone knows ping me.

silver moat
#

send full traceback

indigo badger
#

What do you mean by self full trace back?

silver moat
#

autocorrect

indigo badger
#

Ok hold on computer is being a bit slow.

#
  File "C:\Users\\OneDrive\Documents\Bata-Bot\Bot.py", line 469, in <module>
    async def unwarn(ctx: commands.Context, *, Id ):
  File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py    return cls(func, **attrs)
  File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 628, in __init__    self.options: List[Option] = self._parse_options(params)
  File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 689, in _parse_options    validate_chat_input_name(option.name)
  File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 1633, in validate_chat_input_name    raise ValidationError(
discord.errors.ValidationError
indigo badger
#

Oh shoot forgot to turn off the ping sorry.

silver moat
#

what's your decorator(s)

indigo badger
#
@Client.slash_command()
@commands.has_permissions(manage_guild=True)
async def unwarn(ctx: commands.Context, *, Id ):
  async with Client.db.cursor() as cursor:
    await cursor.execute("SELECT reason FROM warns WHERE WarnID = ? AND guild_id = ?", (Id, ctx.guild.id,))
    stuff = await cursor.fetchone()
    if stuff:
      await cursor.execute("DELETE FROM warns WHERE WarnID = ? AND guild_id = ?", (Id, ctx.guild.id,))
      await ctx.send("This user has been unwarned")
    else:
      await ctx.send("This user has no warnings")
  await Client.db.commit()
#

There is the code if that helps.

silver moat
#

you are taking multi-word options in slash commands, which doesn't exist. remove the *,

indigo badger
#

So would Id just work the same?

silver moat
#

also you may want to typehint correctly. ctx is a discord.ApplicationContext

indigo badger
#

Oh so the *, is probably what was setting it off, right?

silver moat
#

full traceback?

indigo badger
#
Traceback (most recent call last):
  File "C:\Users\\OneDrive\Documents\Bata-Bot\Bot.py", line 469, in <module>
    async def unwarn(ctx: commands.Context, Id ):
  File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 914, in decorator
    result = command(**kwargs)(func)
  File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 1551, in decorator
    return cls(func, **attrs)
  File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 628, in __init__
    self.options: List[Option] = self._parse_options(params)
  File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 689, in _parse_options
    validate_chat_input_name(option.name)
  File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 1633, in validate_chat_input_name
    raise ValidationError(
discord.errors.ValidationError
#

Now it is.

#
@Client.slash_command()
@commands.has_permissions(manage_guild=True)
async def unwarn(ctx: commands.Context, Id ):
  async with Client.db.cursor() as cursor:
    await cursor.execute("SELECT reason FROM warns WHERE WarnID = ? AND guild_id = ?", (Id, ctx.guild.id,))
    stuff = await cursor.fetchone()
    if stuff:
      await cursor.execute("DELETE FROM warns WHERE WarnID = ? AND guild_id = ?", (Id, ctx.guild.id,))
      await ctx.send("This user has been unwarned")
    else:
      await ctx.send("This user has no warnings")
  await Client.db.commit()
#

And that is the code after changes.

#

It should work shouldn’t it?

#

Let me know if you find anything that could be wrong as I do not see anything.

indigo badger
#

You still there?

shell jetty
#

Im trying to get a bot to fetch the contents of a reference message. Can i not use slash commands for this?

lost valley
#

How can I get the channel id of the channel in which a slash command is used in

lost valley
#

worked ty

naive steppe
#

im just assuming you are using the wrong ctx since its a slash (ive never used anything outside of ApplicationContext so maybe others work)

#

id one is unessassery but more user friendly

white wadi
#

is it possible to somehow put inside the view an argument or varible that is defined in a function that calls the view

    def __init__(self, ctx, test):
        super().__init__(timeout=60)
        self.ctx = ctx
        self.test = test
        print(self.test)


    @discord.ui.button(style=discord.ButtonStyle.blurple, label=f"{test}", disabled=False)
    async def _1_button_callback(self, button, interaction):
        await interaction.response.edit_message(content=" ", delete_after=0.1)
        print(self.test)`
#

i can acces the "test" variable inside a function with self.test, but i cant do that for the label

spice oyster
spice oyster
# white wadi yeah, missclick...

I have a similar problem when creating commands, as I need the result of a coroutine inside the decorator.
#1029292189399928863

#

One of my options is initializing the value, but then I cannot see it like it happens in your case.

spice oyster
#

Instead of passing it as parameter, you change the value for that field after creating the View.

white wadi
fringe socket
#

Hey @spice oyster want to help me in #1028563234552283156 ?

spice oyster
fringe socket
#

OK

slim nebula
#

I can't run two task loops at once, only the first one I say .start() to runs

signal stratus
#

Does anyone know how to disable this error?

#

Because this error is spamming my console

cyan quail
cobalt tangle
#

How do I accept all channel types in discord.Option except voice

cobalt tangle
cyan quail
cobalt tangle
#

also how do i create a subgroup of a subgroup

cyan quail
#

uhh you can only have one subgroup

#

the max is group subgroup command

cobalt tangle
cobalt tangle
cyan quail
#

then do group.create_subgroup

cobalt tangle
#

group is main slashcmd group

cobalt tangle
cobalt tangle
#

it said a subgroup cant have a subgroup

cyan quail
#

can you show the code?

cobalt tangle
cyan quail
#

make sure you're on 2.2.2

cobalt tangle
#

i did:

group = discord.SlashCommandGroup("group", "group desc")
sub = group.create_subgroup("sub", "sub group")
j = sub.create_subgroup("j", "j desc")
cobalt tangle
#

yes i am

cyan quail
#

...as i said, the max is group subgroup command

#

a subgroup can't have another subgroup

cobalt tangle
#

well

#

how do i get the space between subgroup and command

cyan quail
#

? it does that for you...

#

you just make a command under the subgroup like @sub.command(...)

cobalt tangle
#

ok i think im dumb, im sorry

merry briar
#

how to make the slash command not displayed to ordinary users?

young bone
errant craneBOT
#

Here's the slash perms example.

merry briar
merry briar
cyan quail
#

they won't be visible at all for the most part

spice oyster
#

Since when? Why for the most part?

cyan quail
#

if they have a particularly outdated version then maybe they could see the command, but otherwise users without the permissions can't see the command

cyan quail
spice oyster
errant craneBOT
#

Here's the basic voice example.

spice oyster
cyan quail
spice oyster
cyan quail
#

yes

#

created_at returns a UTC-aware timestamp. Reading datetime.today https://docs.python.org/3/library/datetime.html#datetime.datetime.today

This method is functionally equivalent to now(), but without a tz parameter.
being datetime.now(tz=None), but this is also not UTC-aware. Comparing aware and unaware timestamps results in an error, and as such you should instead use datetime.now(timezone.utc).
Luckily, this is built into the library as discord.utils.utcnow()

cyan quail
#

you didn't finish your try/except statement

#

yeah

merry briar
cyan quail
#

can only be done in guild settings > integrations

lost valley
#
@bot.command(description="Look's up a player's KD.")
@commands.cooldown(1, 10, commands.BucketType.user)
async def kd(ctx, name: discord.Option(discord.SlashCommandOptionType.string)):
    try:
        print("USERNAME: ", name)
        await ctx.response.defer(ephemeral=False)
        find(name)
        
        from webscrapeTest import kd
        #channel = ctx.channel
    
        await ctx.followup.send(f"{name}'s KD is: {kd}")
        #channel = bot.get_channel(978423778944114690)
        #await channel.send(f"{kd} K/D")

    except (ImportError, NoSuchElementException):
        print("error")
        

Whenever there is an error it'll "think" forever. Is there a way to delete the message on error?

cyan quail
lost valley
cyan quail
#

yeah but if it errors you never respond

#

so you need to respond there

lost valley
#

Hm so can I just throw another followup in the except?

cyan quail
#

as i said, discord.utils.utcnow() is a shortcut for this

simple canopy
#

how do i get all functions of a class

#

preferably from self (if its possible)

cyan quail
simple canopy
#

👍🏻

#

thanks

young bone
#

remove the return?

fervent cradle
#

i want this feature in my bot, i have everything figured out except i cant seem to understand how can make my bot detect whether a message sent is a token or not?

spice oyster
#

Delete the indentation near that line and write it again by using the same characters used for other lines.

silver moat
#

?tag tokens

fervent cradle
#

ok

drifting sleet
#

Just curious - when you send a time-consuming command for the first time (typically after bot started) it takes long to process, but second time you use that command and it's way shorter, why is that

copper dew
#

and the code for the command may also be caching the results and stuff

fervent cradle
#

How can I do that when executing the command the user and the serer where it was executed put the cooldown

copper dew
#

for caching that ? probably would have to cache the results on redis

indigo badger
#

And I am not getting the user I am getting a ID the is 16 characters that is stored in a database.

#

Anyone else have any ideas?

#

Or anything?

#

And yes it is still popping up the same error.

indigo badger
#

Ping me if you have any ideas on that.

young bone
#

you have Id, change it to id

indigo badger
#

Your a life saver.

ionic snow
#

Is there a way to make the bot invoke a command? if so, how can I detect from the command if the program invoked it or a user did?

indigo badger
#

Is there a way to have three columns of data showing in one embed without it having a IndexError: tuple index out of range error?

#

Ping me if you know:

indigo badger
#

I am trying to have all three data columns in one field.

spice oyster
indigo badger
#

Yes I have three things that I I am trying to fetch.

#

Am I forgetting something?

spice oyster
#

SELECT reason, time and?

indigo badger
#

Oh that is what I am forgetting I will fix tonight.

#

I can’t believe I was that stupid to forget that.

spice oyster
#

Happens to the best too. hehehe

spice oyster
#

Can I use the same custom_id for Buttons that are in separate Views and have to do different things? eddaniSherlock

full basin
#

?tag tias

obtuse juncoBOT
spice oyster
#

Thank you. I'll remember this. blobpain

scenic elbow
#
from colorama import Fore

class MAIN:

      def Screen1():
        print(Fore.CYAN, end='')
        print(
                '░█████╗░██████╗░██████╗░░██████╗░░░░░░░█████╗░██╗░░██╗███████╗░█████╗░██╗░░██╗███████╗██████╗░'
             )
        print(
            '██╔══██╗██╔══██╗██╔══██╗██╔════╝░░░░░░██╔══██╗██║░░██║██╔════╝██╔══██╗██║░██╔╝██╔════╝██╔══██╗'
             )
        print(
            '██║░░╚═╝██████╔╝██████╔╝╚█████╗░█████╗██║░░╚═╝███████║█████╗░░██║░░╚═╝█████═╝░█████╗░░██████╔╝'
             )
        print(
            '██║░░██╗██╔═══╝░██╔══██╗░╚═══██╗╚════╝██║░░██╗██╔══██║██╔══╝░░██║░░██╗██╔═██╗░██╔══╝░░██╔══██╗'
             )
        print(
            '╚█████╔╝██║░░░░░██║░░██║██████╔╝░░░░░░╚█████╔╝██║░░██║███████╗╚█████╔╝██║░╚██╗███████╗██║░░██║'
             )
        print(
            '░╚════╝░╚═╝░░░░░╚═╝░░╚═╝╚═════╝░░░░░░░░╚════╝░╚═╝░░╚═╝╚══════╝░╚════╝░╚═╝░░╚═╝╚══════╝╚═╝░░╚═╝ v1'
            )

      async def Screen2(self):
        choice = input()
        if choice('1'):
          await self.screen1()
        elif choice('2'):
          await self.screen2()
        else:
          print('\n                                       ' + Fore.BLUE +
          '[' + Fore.CYAN + '/' + Fore.BLUE + '] ' + Fore.CYAN +
              'Invalid Choice!\n')
          await MAIN()

 
MAIN.Screen1()
MAIN.Screen2(self)```
#

idk what i did wrong

silver moat
#

please learn basic python thanks.

#

?tag python

obtuse juncoBOT
#

its is very difficult to help you if you don't understand python first.
As it stands, you do not or cannot show that you understand the basic fundamentals of Python. Please continue to learn Python first, as pycord is a Python framework and as such requires that you have a confident grasp on these fundamentals . For now, pause your current project and when you have learned enough Python you can then pick it back up and continue where you left off (if at all possible).** You cannot drive a truck if you do not know how to drive at all.**

cool free resources are
w3school
freecodecamp.org

there are also a lot of python programming tutorials out there a youtube search will give a lot awesome content. If you need help with python there is a python server for that where they will be more that happy to help you with these thing, you can also ask for python help in #881309540639997952.

python server: https://discord.gg/python

indigo badger
#

I keep getting this in as a error and am not sure why?

#

WARNING:discord.gateway:Shard ID None has stopped responding to the gateway. Closing and restarting.

#

What can I do to prevent this from happening?

silver moat
#

internet?

indigo badger
#

Nope.

#

Internet is vary fast and good.

silver moat
#

idk then

scenic elbow
silver moat
scenic elbow
silver moat
scenic elbow
#

i said pls

silver moat
scenic elbow
silver moat
#

?tag lp

obtuse juncoBOT
#
naive steppe
#

this feels very logos + duplox

copper dew
lost valley
woeful spindle
#

extra comma after you define color :)

#

ur extra comma is in the circle

loud holly
#

is 2.2.2 the latest stable version or is it needed to upgrade to 2.2.0?

#

I'm currently on 2.1.3

fringe socket
#

Does anybody know what's wrong with this code?

@bot.bridge_command(description="Report an issue to developers.")
async def report(ctx, title_of_report: str, report_type: str, content_of_message: str, message_link: str):
    await ctx.defer()
    achan = bot.get_channel(1022786892925775892)
    auser = await bot.fetch_user(694104689066639372)
    embed = discord.Embed(
        title=f"{title_of_report}",
        description=f"{content_of_message}",
        color=discord.Colour.nitro_pink(),
    )
    embed.add_field(name=f'Report Type', value=f'{report_type}',inline=True)
    embed.add_field(name="Message Link", value=f'{message_link}',inline=True)
    embed.set_author(name=f"Reported by {ctx.author}")
    await auser.send(embed=embed)
    await achan.send(embed=embed)
    await context.message.delete()
    await ctx.respond(f"Successfully filed report.")

Whenever I use the command in bridge form, the message that started the command isn't deleted.

#

@spice oyster @silver moat ?

#

basically, it is saying that "context.message.delete()" is not an existent coroutine

spice oyster
merry briar
#

How can I hide a team from the participants using the example of default_permission, but only with a role check? The usual has_role decorator does not hide the command, but only checks the resolution

ionic snow
#

Is there a way to invoke a command as the bot? like ctx.invoke but I want the author of the ctx to be the bot

tiny wagon
ionic snow
#

Don't mind my stupidity 😄

spice oyster
#

I guess you are passing a SlashCommand as parameter but then treating it as something else, probably due to a wrong number of parameters.

full basin
#

Then debug it

cobalt tangle
#

how do i make the bot leave a guild

#

await guild.leave() didnt work

#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'coroutine' object has no attribute 'leave' thats the error

rugged lantern
#

5000 fucking lines in your main holy

cobalt tangle
#

try cogs

cobalt tangle
#
        guild_id = int(guild_id)
        tolv = self.bot.fetch_guild(guild_id)
#

@full basin

full basin
#

Fetch guild is a coroutine

cobalt tangle
#

also how do i get the count of text channels

full basin
#

Guild.channels

#

Read the docs

fringe socket
vale coral
#

is anyone else having problems with getting the slash commands refreshed? I am having this problem just since a few hrs, wasn't having it before. For some reason, new slash commands arent coming when typing / and old slash commands (meaning the ones I remove from the code) are still there, been having this problem for a few hours even after trying both, supplying guild IDs and not supplying them

spice oyster
vale coral
#

code for reference

spice oyster
loud holly
#

Are adding tags to forums available? Or is the feature being worked on?

#

adding to this^^ as in the bot adding tags

#

I can't find anything related to adding tags in the discord.ForumChannel section

errant craneBOT
proud pagoda
#

Does deferring work for buttons?

silver moat
proud pagoda
#

Ok thanks

still helm
#

are there any problems with connections of the bots. i become serveral times restarts of my bot

#

or is there a way to get informations why the bot restarts?

fervent cradle
#

is there any example or anything for dynamic cooldowns?

lost valley
#

Error says that embed isn't a argument for your defer

#

pretty sure the parameters for defer are only ephemeral and invisible (this part could be totally wrong)

spice oyster
#

You must pass embeds, as a list.

obtuse patrol
#

How could I put the commands in a seperate folder

spice oyster
obtuse patrol
#

okay thanks!

spice oyster
cyan quail
indigo badger
#

I know there is a way to do this and make it set to the time that the command is run but I am not sure what the format is for that.

#
<t:1664318247:t>
<t:1664318247:T>
<t:1664318247:d>
<t:1664318247:D>
<t:1664318247:f>
<t:1664318247:F>
<t:1664318247:R>

<t:1664318247:t>
<t:1664318247:T>
<t:1664318247:d>
<t:1664318247:D>
<t:1664318247:f>
<t:1664318247:F>
<t:1664318247:R>

API Reference: https://github.com/discord/discord-api-docs/blob/ff4d9d8ea6493405a8823492338880c47fb02996/docs/Reference.md#timestamp-styles

See discord.utils.format_dt for the discord.py implementation.
https://docs.pycord.dev/en/stable/api.html#discord.utils.format_dt

#

Does anyone know?

#

I am trying to use it in my warnings command.

#

Where it will get that and put it into the embed with the time the command was ran.

cyan quail
#

maybe we should also have interaction.created_at? idk

indigo badger
#

This is what it looks like right now.

cyan quail
#

is format_dt not working...?

spice oyster
indigo badger
#

I think this may be why as this is what is storeing in to put there.

#

What would I put there to allow it to work though that is the problem.

#

Then this is the line the sends out the time part of the embed.

#

Any ideas/suggestions?

simple canopy
#

well you need to use unix time stamp in... timestamps

indigo badger
#

So how would I do that then as I have not worked with those yet?

simple canopy
#

timetuple takes datetime object

indigo badger
#

So I would change the datetime.now() to datetime.timetuple?

simple canopy
#

you need to get timetuple from datetime object

indigo badger
#

And what would I change the part of the embed to?

#

I am confused.

#

What do I have to change and to what?

cyan quail
#

utils.format_dt exists so you don't have to do all this

#

if you have a datetime object, it'll convert it into the correct string format for you

simple canopy
cyan quail
#

yeah fair

indigo badger
cyan quail
#

you also don't need to use timetuple, you can do datetime.now().timestamp() for the unix int

indigo badger
cyan quail
#

well you'd remove the <t: > part since format_dt returns it already

#

actually, does your table store the time as a string or as a datetime object?

indigo badger
#

Then put the format_dt where the data that gets stored in the db when the command is ran?

#

async def addwarn(ctx, reason, user):
x = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(16))
async with Client.db.cursor() as cursor:
await cursor.execute('''INSERT INTO warns(user_id, reason, time, guild_id, warnID) VALUES(?,?,?,?,?)''', (user.id, reason, datetime.now(), ctx.guild.id, x))
await Client.db.commit()

#

I am on mobile so I am not able to block it.

#

But that is how the info is stored in the db.

cyan quail
#

hmmm i guess giga's approach may be better in this case, storing the unix time and using that

#

in which case you wouldn't have to change your embed part

spice oyster
cyan quail
#

pretty much

cyan quail
#

unless you run into some clash with datatypes, in which case either change the column's type or store it as str(int(...))

spice oyster
#

What's the best way to auto-update old embeds sent via a given command in the past? My idea is to create a list of recent messages for that command alone and auto-update embeds every x hours.

simple canopy
#

i'd store message ids in db

#

and just task.loop once X minutes

#

and update

spice oyster
#

I was hoping for a better solution but I guess it's not possible to count on Discord API for that.

white wadi
#

Hi, can i trigger send_modal interaction on other modal submit?

#

so if user submits a modal he gets another?

#

i keeps getting me errors, so i wanna ask if its even possible or if i am just stupid and write it badly

white wadi
#

ok thx

rotund current
#

Ok. Quick opinion question. My bot uses fairly extensive integration with a postgresql database via sqlalchemy. I just realized that while all of the database calls are contained in async methods/functions, I am not using the sqlalchemy asyncio package. How bad is this in terms of my bot performance.

#

I am assuming that I need to go back through and convert everything into sqlalchemy asyncio. Right?

silver moat
#

or if 3 people use it, it will take 3 times as long

#

it would be better to use sqlalc. asyncio

rotund current
#

Thats what I figured. I'll work on converting everything over

ripe zodiac
#

Is it feasibly possible to modify the commands.default_commands() decorator to accept a boolean rather than a discord permission? Or just a generic predicate to show or not show a user a command?
We run our own permissions system that ties in with our database and our permissions don't equal discords permission so I'm trying to hide our hella big number of commands from normal people who don't need to see that whole mess

obtuse patrol
#

how can i timeout somebody when a certain command is passed\

#

without slash commands

#

like .timeout @user 5s

#

or if someone says a banned word, they'd be timed out for 5min or smt

copper dew
obtuse patrol
#

ty

copper dew
#

np

obtuse patrol
#

so it'd look like

silver moat
obtuse patrol
#

alright ty

#

would i have to import something, i'm getting an error

silver moat
#

import datetime ?

obtuse patrol
#

oh

#

worked, ty

fervent cradle
#

hey, i'm trying to use dynamic cooldown in slash commands but the cooldown doesn't work , can someone help me

fervent cradle
copper dew
# fervent cradle

something in the code is returning as none, which bypasses the whole system. this could be that the json file isn't there, or something else. or you can do it this way (not sure if this fixes it or not):

async def custom_cooldown(self, message: Message):
        returnValue = None
        with open('./utils/premium_members.json') as f:
            data = json.load(f)
        if message.author.id not in data['premium_members']:
            returnValue = commands.Cooldown(rate=1, per=86400)
        return returnValue
fervent cradle
copper dew
fervent cradle
#

i was just testing it, because my friend also had same problem

#

he was telling that cooldown works without options in slash commands but not with it

copper dew
#

hm ok

copper dew
tame rose
#

How do you get the modal's contents after submission? Am I supposed to use interaction.data?

tame rose
#

Nvm, I got it. It's accessed through children.value

signal stratus
#

Does anyone know how to fix this?

rugged lantern
#

by reading

fringe socket
#

?tag codeblocks

obtuse juncoBOT
#

dynoError No tag codeblocks found.

fringe socket
#

?tag codeblock

obtuse juncoBOT
#

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.")
cobalt tangle
#

How can I log every slash command when someone uses it in a specific discord server channel

#

without breaking anything

cobalt tangle
#

run the application cmd or smth

cyan quail
#

no, it's an extra event

cobalt tangle
#

oki

cyan quail
#

you can use it safely

cobalt tangle
cobalt tangle
#

do i just input ctx

cyan quail
cobalt tangle
#

and how do i get which cmd

tiny wagon
#

is edit_original_message changed to edit_original_response?

cyan quail
#

ctx.command

cobalt tangle
cyan quail
tiny wagon
cyan quail
#

until v3

#

elaborate?

tiny wagon
#

i want to edit the view

#

i want to edit the message in which the button is a component

#

unkown webhook error

cyan quail
#

you should do interaction.response.edit_message

tiny wagon
#

ohk

cyan quail
#

edit_original_message is for edits to the response, not the original message

tiny wagon
#

it always confuse me whenever i come across it, make this clear when?

cyan quail
#

hence why it was renamed to edit_original_response

tiny wagon
#

ok this works, but then shouldnt be the interaction.response name be also changed?

cobalt tangle
#

Can my bot fetch users who arent in any of its guilds? If so, how?

cobalt tangle
cyan quail
#

Well yeah, I was just saying it will be removed in v3

cobalt tangle
#

also imagine a bot with the prefix sudo

cyan quail
#

I mean you can do that if you want

cobalt tangle
cyan quail
#

I guess?

cobalt tangle
tame rose
#
modal = discord.ui.Modal(*fields, title = 'Form')
async def submit(itrc):
  await itrc.response.defer()
modal.callback = submit

await itrc.send_modal(modal)
await modal.wait()
#

Is this how it's supposed to be done?

#

The interaction is a slash command btw

cobalt tangle
#

the id is 100% correct

#
    @utility.command(description="Get user info on someone")
    @commands.cooldown(1, 30, commands.BucketType.user)
    async def userinfo(self, ctx, member: Option(discord.Member, 'User to get info on', required=False), member_id: Option(str, 'User ID to get info on', required=False)):
        if member == None and member_id == None:
            member = ctx.author
        elif member_id == None:
            member = member
        elif member == None:
            member_id == int(member_id)
            member = await self.bot.fetch_user(member_id)
#

^ code ^

spice oyster
#

What's the difference between interaction.message and interaction.original_message()? I read the docs, I've tried them, but I'm still not sure. blobpain

cobalt tangle
cyan quail
#

Doesn't look like it

cobalt tangle
cobalt tangle
#
    bans = await ctx.guild.bans()
TypeError: object BanIterator can't be used in 'await' expression
rare ice
#

It will return a list

cobalt tangle
#

get bans()

cyan quail
rare ice
#

Exactly you need to flatten it

cobalt tangle
cobalt tangle
#

await ctx.guild.bans().flatten?

rare ice
#

.tag tias

winter condorBOT
cobalt tangle
rare ice
#

You need to call flatten

cobalt tangle
cobalt tangle
rare ice
#

await ctx.guild.bans().flatten()

cobalt tangle
#

async for?

rare ice
#

No

cobalt tangle
rare ice
#

Not async once it’s a list

cobalt tangle
cyan quail
spice oyster
cyan quail
#

It will error

spice oyster
cyan quail
#

interaction.response is used for responding

spice oyster
#

Oh, right! Dumb question. eddaniDerp

spice oyster
#

Now, if I do interaction.message.mentions[0] on a private message sent from my bot, why do I get an IndexError? I believe it was working a few days ago but I'm not sure if I've accidentally changed something. Solved.

#

I know why! I'll try using interaction.message.raw_mentions[0] because docs says it's the way to go in private messages.

umbral island
#

How to check the permission of a bot inside of a cog?

I attempted

if ctx.guild.me.permissions.view_channels == True: print('True')

but this just outputs object member has no attribute permissions

spice oyster
#

What's the difference between Bot.cogs and Bot.extensions attributes?

spice oyster
umbral island
#

its not getting the bots permission. its now trying to get the permission of ctx, which isnt a thing

spice oyster
umbral island
spice oyster
loud holly
cyan quail
#

No

loud holly
#

I'm guessing it won't ever be removed right?

cyan quail
#

It will remain for the entirety of v2

loud holly
#

for v3 it'll be removed?

cyan quail
#

Yes

loud holly
#

alr thanks 👍

cyan quail
#

v3 will likely have larger breaking changes to worry about, but that's not for a while

loud holly
wary rover
#

Hello!
I would like to add buttons on an embed.
The only problem is that I would like to define the buttons from an array.
My question is, how to add a view to a message while giving a list to this view.

#

Something like this

simple canopy
#

you can use an discord.ui.Button class

#

iterate through list to create buttons, and then add them to the view via view.add_item()

wary rover
#

I'll check it out
I'm really struggling with the UI so it might be complicated

simple canopy
cold hamlet
#

How can I display start and end times and stuff in discord.Game?

#

I don't think its built into the lib is it

#

actually can you even do that with a bot account

silver moat
cold hamlet
#

Wow that sucks

#

cheers

silver moat
cold hamlet
#

Nah I wanted to display a "current lesson" style thing with my college's bot, I guess I can just write the start & end times in the status

cyan quail
#

at least you can use the time formatting for them only in about me rip

silver moat
cold hamlet
cold hamlet
gleaming falcon
#

Does the event on_scheduled_event_delete get fired after the ScheduledEvent end_time has passed?

cyan quail
#

which i don't think it does...?

gleaming falcon
#

I mean.. it no longer shows, so I would have expected it to be deleted. As a parallel, when a Forum Thread gets auto-archived, the edit event is fired. Was hoping something similar here.

cyan quail
#

well i'm not entirely sure myself since i don't work with them

#

but they have status.completed listed on the docs

#

so i'd assume they stick around

#

in which case just use on_scheduled_event_update and check after.status

gleaming falcon
#

Ah, maybe it'll auto-update. Thanks for the thought

gleaming falcon
# cyan quail in which case just use `on_scheduled_event_update` and check `after.status`

Okay, the docs were a little terrible to follow, but you are correct

Guild Scheduled Event Status Update Automation (<-- They should word this better)

[...]
An active scheduled event for a voice channel where all users have left the voice channel will automatically end a few minutes after the last user leaves the channel
When an event with 'status': ACTIVE and 'entity_type': VOICE has no users connected to the voice channel for a certain period of time (on the order of minutes), the event status will be automatically set to COMPLETED.

An external event will automatically end at its scheduled end time
An event with 'entity_type': EXTERNAL at its scheduled_end_time will automatically have status set to COMPLETED.
cyan quail
#

nice

west pebble
#

Why do channel mentions show up as #deleted-channel on the mobile client

wary rover
fervent cradle
#

to_update = update_guild_commands[guild_id]
KeyError: '1'

So how can I fix this?
The bots in the server and its the right guild id im pulling it from a json file

simple canopy
#

try printing out things you pull from json

#

may be you are missing out on something

fervent cradle
#

yeah its printing the right guild

simple canopy
#

can you show traceback?

#

whole error

fervent cradle
simple canopy
#

what pycord version are you using?

young bone
#

pip show py-cord

fervent cradle
simple canopy
#

you should try updating

#

but it may break somethings for you

#

the latest version is 2.2.2 iirc

fervent cradle
#

alr

#

ill upgrade

#

the bot goes online but it doesn't register commands

simple canopy
#

?tag commandnoshow

obtuse juncoBOT
#

My slash/message/user commands aren't visible. Why?

  1. Ensure that you've specified guild IDs in your decorator. If you don't, the command is "global" and could take an hour to show up. You should always be passing a list of guild IDs when developing new commands; you can trivially remove them later when you actually want global commands.
@bot.slash_command(name="hi", guild_ids=[...])  # create a slash command for the supplied guilds
@bot.slash_command(name="hi") # Not passing in guild_ids creates a global slash command (might take an hour to register)
  1. If you've been restarting your bot a lot to test commands, you may have hit any number of Discord API rate limits. Wait a couple of minutes before trying again. If you want to confirm this, do a basic logging setup in the beginning of your program and carefully watch the output of your bot when it starts:
import logging
logging.basicConfig(level=logging.INFO)
  1. If you defined an on_connect() function in a bot's class, you overrode the function that syncs commands to Discord. You'll need to call self.sync_commands() to ensure this is done.

  2. Discord sometimes gets confused on the client side. If you've checked all of these, hit ctrl-R to force a reload.

fervent cradle
#

yeah I found out what I was doing wrong and i feel really dumb
nothing on your end thank you for your help
but pretty much I was passing in guild_ids with only 1 guild specified and didn't realize I hadn't changed it to guild_id

cyan quail
west pebble
lost cypress
#

can someone help me out with the following:
I am trying to delete a message that has been created using the ApplicationContext.respond() function

self.message = await self.ctx.respond(
            embed=embed,
            view=self
        )```
returns an interaction, the value of interaction.message is None
```python
  await self.message.delete()
``` does obviously not work

However, after editing the message using:
```python
        await interaction.response.edit_message(
            embed=embed,
            view=self
        )
``` where the interaction is created by a buttonpress

```python
  await self.message.delete()
``` works.
However, can i also delete the original response message without it being edited?
silver moat
lost cypress
#

i want to delete it because its a view menu

#

and if the command is used again i want it to close the old menu

#

and open a new one

spice oyster
#

Can you use delete_after?

lost cypress
#

no because then the amount of time the menu is open will be fixed

spice oyster
#

That's fair.

lost cypress
#

its strange in the first place how an interaction can apparantly be deleted after i edit its message

#

my brain fails to comprehend that, the interaction class does not even have a .delete() function

silver moat
#

it literally does

lost cypress
#

thats applicationContext

silver moat
#

it’s just not called delete

lost cypress
#

isnt that different from delete?

silver moat
#

there’s a reason why readthedocs is the most reacted reaction on this post

lost cypress
#

they changed it

#

well ill try this

#

maybe it works

spice oyster
#

What's the recommended way to implement a function that accepts two types for the same parameter in Python? Should I use overloading?

silver moat
spice oyster
#

Do you mean like this?

def send_log(
    context: discord.ApplicationContext or discord.Interaction,
    event: str
):
silver moat
#

iirc

spice oyster
#

Do I need to import Union? I've never used it. eddaniDushno

lost cypress
silver moat
#

if you have any modern IDE it should give solutions.

silver moat
lost cypress
#

i mean its fine when i type everything

#

static typing ftw

#

but in this case i did not and i got trolled by it

spice oyster
#

Is it weird to still call it context in that case? eddaniSherlock

spice oyster
#

Thanks! Now it's more elegant compared to when I was using overloading.

cyan quail
cyan quail
gleaming falcon
#

The best part about 3.10 (or was it 3.9?) is being able to ditch typing almost altogether and typehint using standard classes (e.g. dict, int)

pallid token
#

Hey. I'm getting an error when trying to send my modal from an application command... Here is how I'm sending it:

modal = self.BirthdayForm(title="<title message>", timeout=None)
await ctx.response.send_modal(modal)

Here's a snippet of the error:

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components: This field is required

I can give a full traceback if someone wants

#

Forgot to mention that I get an "Application did not respond" error on Discord and no modal appears.

spice oyster
copper dew
#

hm interesting. i've based of all of my bot's docker images on python 3.10 (both alpine and bullseye-slim variants), so for me i've been running 3.10 for quite some time

spice oyster
copper dew
#

python 3.11 is scheduled to come out 10/24/2022, so gotta prep my packages and bots to update later

slender shuttle
#

I am making a class that inherits from discord.Bot
What is the decorator for methods that need to be slash command?

slender shuttle
spice oyster
#

Oh, I don't know. Either that way or like in Cogs. rooThink

smoky condor
#

does any one know how to fix

AttributeError: partially initialized module 'discord' has no attribute 'Client' (most likely due to a circular import)

spice oyster
young bone
#

Stay in one channel pls

smoky condor
#

aiohttp==3.8.3
aiosignal==1.2.0
async-timeout==4.0.2
attrs==22.1.0
charset-normalizer==2.1.1
frozenlist==1.3.1
idna==3.4
keyboard==0.13.5
MouseInfo==0.1.3
multidict==6.0.2
numpy==1.22.3
opencv-python==4.6.0.66
packaging==21.3
Pillow==9.2.0
py-cord==2.2.2
PyAutoGUI==0.9.53
pycodestyle==2.8.0
PyGetWindow==0.0.9
PyMsgBox==1.0.9
pynput==1.7.6
pyparsing==3.0.9
pyperclip==1.8.2
PyRect==0.2.0
PyScreeze==0.1.28
pytesseract==0.3.9
pytweening==1.0.4
six==1.16.0
toml==0.10.2
yarl==1.8.1
PS C:\Users\DELL\Desktop\discord-bot>

copper dew
spice oyster
copper dew
#

the reason why I know that's probably the issue is that it has happened to me before

copper dew
spice oyster
#

How can I get the description of a Slash Command that's in a group? Solved!

group = bot.get_application_command(group_name, type = discord.SlashCommandGroup)
commands = group.walk_commands()
for command in commands:
    if command_name == command.name:
        command_description = command.description
        break
vital blade
#

I am trying to give a user a role if a number is between 50-100. Can someone please tell me if and how this is possible?

fringe socket
#

OFC it is possible!

#

First create a variable for the number.

#

Then do an if/elif (depends on the context) statement checking whether

if variable in ['50', '51', '52', '53', 'etc.']:
  ...

Put your code where the ... is

#

@vital blade

vital blade
fringe socket
#

you are welcome

white scarab
#

How can I get the voice channel to which a user is connected with an interaction discord.Interaction?

cyan quail
minor pecan
#
code

@client.slash_command()
async def report(ctx, user : discord.Member, *reason):
    channel = client.get_channel(1030811271643283487)
    await channel.send(f"{user.mention} has reported {user}, reason: {reason}")
    await ctx.respond(f"{user.mention} reported!")
error

Traceback (most recent call last):
  File "C:\Users\sohey\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1009, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\sohey\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 359, in invoke
    await injected(ctx)
  File "C:\Users\sohey\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 135, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: report() got an unexpected keyword argument 'reason'

my report command is not working
cloud you help me on this?

wary rover
minor pecan
#

its worked nicee

#

tnxx

wary rover
minor pecan
#

first

wary rover
#

You should display your code in python next time, it's easier to understand

full basin
fringe socket
#

Meh

#

Wasn't thinking

gleaming falcon
#

Or even better,
if 50 <= variable <= 100:

Worthy mention, likely slower
if variable in range(50,100)

full basin
#

"Unknown column guildId"

spice oyster
#

You made a typo: guilID instead of guildID.

rugged lantern
#

this guy should get his own help channel

#

or hire a mentor to hold his hand through every step he takes

proud mason
spice oyster
proud mason
#

make sure to do it like python3.10 -m pip .....

spice oyster
#

Same as before, via a requirements.txt that's automatically being loaded by the hosting provider.

proud mason
proud mason
spice oyster
#

I'll ask on their Discord server because it looks like the issue is on their end.

proud mason
fervent cradle
#

how can we gracefully exit a bot in pycord without the error: RuntimeError: Event loop is closed

proud mason
#

and the library should do everything about the event loop

fervent cradle
#

i wanna use it when someone keyboard interrupts

fervent cradle
#

i just cant understand how i can close a bot gracefully without raising all these errors

round rivet
#

That's just a Windows thing

#

You can ignore it

fervent cradle
proud mason
#

For some reason, when i run my bot from vsc and stop it using the red Stop button, bot.close doesnt get called and i got no idea why

spice oyster
rare ice
#

What are the parameters given in on_error? the docs say event_method, *args and **kwargs. Not sure if ctx is included.

spice oyster
#

I don't think it's included in that, but you can get it from on_application_command_error().

wary rover
#

Hey,
Do you know how to bypass the obligation to make a response when sending a modal?

If not, do you have a solution to make the response completely invisible

gleaming falcon
spice oyster
wary rover
wary rover
#

I create an embed editor, given the number of fields it is complicated

#

It is in French for the moment but here is the idea

wary rover
spice oyster
# wary rover

Discord is wasting so much screen space on mobile. blobpain

fervent cradle
#

how can we use asynchronous functions for dynamic cooldowns? i tried using asyncio.run() too, but it gave me some event loop error

async def nuke_cooldown(ctx):
        premium_check = await db.check_premium(ctx.guild.id)
        if premium_check == True:
            return None
        else:
            return commands.Cooldown(1, 60)
#

i am using asyncpg so i must use await for running the check, but then this function is completely non asynchronous and doesnt support asyncio.run

#

So I tried that my bot writes, for example, every 5 hours: "How are you?" but nothing happens and there is no error could someone help me?

here is my try:

sätze = [" Was macht ihr so ^^ mir ist langweilig ",
                 " Habt ihr lust was mit jemanden zu zocken? fragt in #§⌨§_gamechat nach :) ", " Wie gehts euch :o? ",
                 " Komm schreibt mal was werdet nicht inaktiv pls^^ ", " Was habt ihr so gemacht ? o_o "]
@tasks.loop(hours=5)
async def server():
    channel = bot.get_channel(1030778721092780052)
    satz = random.choice(sätze)
    await channel.send(satz)
    server.start()
bronze vector
fervent cradle
bronze vector
#

you're calling a function inside of function

#
@tasks.loop(hours=5)
async def server():
    ...
server.start()
errant craneBOT
#

Here's the background task example.

fervent cradle
fervent cradle
fervent cradle
fervent cradle
silver moat
fervent cradle
silver moat
fervent cradle
fervent cradle
errant craneBOT
#

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.

silver moat
#

@fervent cradle ^

fervent cradle
#

So I would like that my bot send a message every 5 hours. So I specify different sentences and a random sentence should be sent by the bot every 5 hours

fervent cradle
fervent cradle
# fervent cradle So I would like that my bot send a message every 5 hours. So I specify differen...

my try look like this

@tasks.loop(seconds=1)
async def server():
    sätze = [" Was macht ihr so ^^ mir ist langweilig ",
             " Habt ihr lust was mit jemanden zu zocken? fragt in #§⌨§_gamechat nach :) ", " Wie gehts euch :o? ",
             " Komm schreibt mal was werdet nicht inaktiv pls^^ ", " Was habt ihr so gemacht ? o_o "]
    channel = bot.get_channel(1030778721092780052)
    satz = random.choice(sätze)
    await channel.send(satz)
fervent cradle
silver moat
#

did you run server.start()

silver moat
#

you run the server.start() outside of the loop

#

e.g. in on _ready

fervent cradle
# silver moat e.g. in on _ready

yeah it work but than dont work this


@bot.event
async def on_ready():
    activity = discord.Game(name="a/help für die commands etc.", type=3)
    await bot.change_presence(status=discord.Status.online, activity=activity)
    print("bin da ace")

fervent cradle
# silver moat wdym

the Discord activity script is in an on_ready and not working if i put the server.start() in a on_ready

silver moat
#

I don’t see the problem

fervent cradle
#

look

silver moat
#

you can put it after the presence change

fervent cradle
#

here if i put the @bot.event
async def on_ready():
server.start()
out of my code
there a activity

#

if i put it in

silver moat
#

you can put both in one on_ready

fervent cradle
#

it works thanks

silver moat
#

you’re welcome

west pebble
#

Can you you have slashcommand choices pulled from a list?

silver moat
#

yes

#

static list = options. dynamic list = autocomplete

west pebble
#

i have a list named "role_names" that gets populated on_ready.
the part i cant figure out is how to show the content as selectable in the discord client

wary rover
#

Little question,

#

What is the maximum time a bot has to edit a message?

fervent cradle
# silver moat get `nest_asyncio`

thank you it works now, just one last problem that i see the error handling is not working a lot nowadays, like this is the code

@nuke.error
    async def nuke_error(error):
        if isinstance(error, commands.CommandOnCooldown):
            ne_embed = discord.Embed('This command has a cooldown of 1 minute. If you want to remove the delay, you can request for a premium license key from the developer.', colour=discord.Colour.red())
            await ctx.respond(embed=ne_embed)
        else:
            ne_embed = discord.Embed('Something went wrong from the backend, please try again later.', colour=discord.Colour.red())
            raise error

but the interpreter acts like it doesnt even exist and raises an on_interaction error with the cooldown error along with another exception stating Moderation.nuke_error() takes one positional argument but three were given

silver moat
#

it should take 3 args: self, ctx, and error

fervent cradle
wary rover
spice oyster
still helm
#

is there a Option in bridge_command ?

hallow phoenix
#

hello, i have a question.
does discord.ext.commands.Bot.get_message() always find a message if a bot is on the server with that message? whether is there something related to the cache and after some time i won't be able to get this message with discord.ext.commands.Bot.get_message() anymore ?

indigo badger
#

Is there a limit on how many tables should be in one file for aiosqlite DB’s?

indigo badger
#

Ok good I am not at that amount yet.

#

But getting there.

spice oyster
indigo badger
#

I have that much on my host.

#

@spice oyster

copper dew
#

if needed, you can also move the db to something like postgres or mariadb

pallid token
# pallid token Hey. I'm getting an error when trying to send my modal from an application comma...

Hey. I'm getting an error when trying to send my modal from an application command... Here is how I'm sending it:

modal = self.BirthdayForm(title="<title message>", timeout=None)
await ctx.response.send_modal(modal)

Here's a snippet of the error:

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components: This field is required

Full traceback: https://hastebin.com/anariqoqok.properties

icy sinew
#

How do you get options for a slash command eg. on a ban command

rare ice
winter condorBOT
rare ice
#

?tag guide

obtuse juncoBOT
pallid token
frozen salmon
#

How would I check if the message came from the authors DM?

proud pagoda
frozen salmon
#
t=json.dumps(token)
while True:
    for x in t:
        try:
            bot.run(x)
        except:
            print(f"Invaild Token {x}")
        else:
            print(f"Sucessfully Loaded {x}")
``` The console prints out ``("Invaild Token )`` for every letter in the token
#

I printed token, and that returned a string

#

OH, THATS WHY

indigo badger
#


@Client.slash_command()
@commands.has_permissions(manage_guild=True)
async def warnings(ctx: commands.Context, member: discord.Member):
  async with Client.db.cursor() as cursor:
    await cursor.execute("SELECT reason, time, WarnID FROM warns WHERE user_id = ? AND guild_id = ?", (member.id, ctx.guild.id,))
    things = await cursor.fetchall()
    if things:
      embed = discord.Embed(title=f"{member.name}'s warnings", color=discord.Color.red())
      warnum = 0
      for table in things:
        warnum += 1
        embed.add_field(name=f"warning {warnum}", value=f"Reason: {table[0]}\nTime issued: <t:{(table[1])}:F>\nID: {(table[2])}")
      await ctx.respond(embed=embed)
    else:
      await ctx.respond("This user has no warnings")
  await Client.db.commit()

#

Not sure why but this sends two times.

#

And I can’t find anything that would make it do that.

frozen salmon
#

It looks like you ran it twice, ran the command twice

indigo badger
#

I didn’t trust me.

frozen salmon
#

Is this the only command that does this?

rugged lantern
#

u didnt trust u?

indigo badger
#

No it also does this for a bridge one too.

#

But the other commands it does not.

#

That is the bridge one.

#

So you can see why I am confused on why it is doing that.

#

If anyone knows why let me know why and how to fix it.

rare ice
#

Does the prefix command do that? If it does, you probably have 2 instances of the bot running.

indigo badger
#

I only have that code running on one host.

#

Sooo.

#

And the bridge command is only on the bot is code no other bot.

#

So I don’t know.

#

Any other ideas?

rugged lantern
#

it 100% is two instances running, so the best you can do is cope

indigo badger
#

Cope?

#

wdym?

full basin
icy sinew
# rare ice .docslink discord.Option

I have the following python @discord.slash_command(guild_ids=settings.guild_id) async def ban(self, ctx, member=Option(type=discord.User, description = "Who do you want to ban?"), reason=Option(type=str, description = "Why?", required = False)): await ctx.respond(member)
but I get the error discord.errors.ExtensionFailed: Extension 'cogs.moderation' raised an error: TypeError: at least one option string must be supplied

rare ice
#

You should be type hinting Option

indigo badger
#

Also I try doing the bridge command and it says that context object has no attribute ‘respond’

rare ice
#

.docslink discord.BridgeContext

indigo badger
#

But why was it working in the guide like that then?

#

So I changed it to reply and it worked with the prefix one but when I went to do the slash it would not run with that.

#

So not sure how to have it work both ways……

icy sinew
rare ice
#

You should know how to type hint as it’s a simple aspect of python.

indigo badger
#

Anything with my question.

#

?

echo pagoda
#

Hello, I'm trying to create a bot that reads exif metadata from an image URL and spits it back out at you. I know absolutely nothing about Python so a friend helped me out with the core of the bot (feed URL > get metadata as message) but he's pretty busy and I'd like to add some QoL stuff. Things like having it also spit out the output as a txt file attached to the message (or alternatively only as a text file which can be previewed from Discord itself), including the URL in said text file for future reference and more importantly having it format the metadata differently depending on what it detects in the "software" field of the exif tags. Would any of this be possible?

copper dew
#

you'll need to feed it through a metadata extracting lib, and do any processing needed. the way you do it is completely up to you and your friend, since i dont do image processing stuff in python

echo pagoda
copper dew
#

probably would want to use the file parameter when sending the results

echo pagoda
#

It's set up to return the data like this for now await ctx.respond(json.dumps(dict(img.text.items()), indent=4))

#

(also need it to include the original url)

copper dew
#

ideally the results should be sent as a embed

#

but the results are parsed and formatted so it isn't raw json

echo pagoda
#

Nope

#

Returns a bunch of errors, mainly file = discord.File(fp=io.BytesIO(bytes(json.dumps(dict(img.text.items()), indent=4))), filename="results.json") TypeError: string argument without an encoding

copper dew
echo pagoda
copper dew
echo pagoda
copper dew
#

since json.dumps accepts only 1 object, you would have to add the metadata to the dict of items as well

vapid pumice
#

Anyone have experience hosting with Digital Ocean? I'm STRUGGLING to set this thing up because it isn't recognizing my Procfile 1thisisfine

echo pagoda
#

Trying to figure it out

copper dew
#

so probably to do it, it would look like this:

import discord
import io

# Assumes the rest of the setup code has been declared
url = "https://example.com" # This is the metadata url
itemData = dict(img.text.items())
item.update({"url": url})

file = discord.File(fp=io.BytesIO(bytes(json.dumps(itemData, indent=4), encoding="utf-8")), filename=f"{url}.json")
await ctx.respond(file=file)
copper dew
vapid pumice
copper dew
#

i have all of my bots completely dockerized (and public, so ppl can self host their own version as well), so all that needs to be done is to pass in the env vars and then running it

vapid pumice
#

Going to look up " how to dockerize " hehehehe

copper dew
copper dew
echo pagoda
#

It's highlighted

spark lantern
#

ok this is going to sound like a supremely stupid question but why does this not work

@bot.slash_command(description='Ban a Member')
@commands.has_permissions(ban_members=True)
async def ban(ctx):
    await ctx.respond(f"Hello, {ctx.author}!")
    @bot.commands.has_permissions(ban_members=True)
NameError: name 'commands' is not defined```
copper dew
# echo pagoda It's highlighted

yeah i fixed it. here's the fixed version

file = discord.File(fp=io.BytesIO(bytes(json.dumps(itemData, indent=4), encoding="utf-8")), filename=f"{url}.json")
copper dew
spark lantern
echo pagoda
copper dew
echo pagoda
#

Uh

#

It's already there though?

#
bot = discord.Bot()
@bot.slash_command()
async def proompt (ctx, url: str):
    try:
        async with httpx.AsyncClient() as client:
            r = await client.get(url)
            data = r.content
            img = Image.open(io.BytesIO(data))
    except Exception as e:
        return await ctx.respond(f"Failed loading image {e}")
        itemData = dict(img.text.items())
    item.update({"url": url})
    file = discord.File(fp=io.BytesIO(bytes(json.dumps(itemData, indent=4), encoding="utf-8")), filename=f"{url}.json")
    await ctx.respond(file=file)```
copper dew
echo pagoda
#

Nvm I left something out

#

wait nope

copper dew
# echo pagoda ``` bot = discord.Bot() @bot.slash_command() async def proompt (ctx, url: str): ...
bot = discord.Bot()
@bot.slash_command()
async def proompt (ctx, url: str):
    try:
        async with httpx.AsyncClient() as client:
            r = await client.get(url)
            data = r.content
            img = Image.open(io.BytesIO(data))
            itemData = dict(img.text.items())
            itemData.update({"url": url})
            file = discord.File(fp=io.BytesIO(bytes(json.dumps(itemData, indent=4), encoding="utf-8")), filename=f"{url}.json")
            await ctx.respond(file=file)
    except Exception as e:
        return await ctx.respond(f"Failed loading image {e}")
echo pagoda
#

Yep that works, thanks a bunch

copper dew
echo pagoda
#

Oh yeah, where do I have to define the command's description?

#

The one that pops up when typing it out

copper dew
# echo pagoda Oh yeah, where do I have to define the command's description?

you can define it as a doc string or within the description parameter of the slash command

declaring it using the description parameter:

bot = discord.Bot()

@bot.slash_command(description="Description for the command")
async def proompt(ctx, url: str):
    ... 

declaring it with docstrings:

bot = discord.Bot()

@bot.slash_command()
async def proompt(ctx, url: str):
    """Description for the command"""
#

and to add an description to the options, here's an example:

from discord.commands import Option

bot = discord.Bot()

@bot.slash_command()
async def proompt(ctx, url: Option(str, "The url to feed")):
    """Description for the command"""
echo pagoda
#

Yeah I did it with the description, was the simplest

copper dew
#

ok !

echo pagoda
#

"This command is outdated, please try again in a few minutes" huh

copper dew
echo pagoda
#

Aah, got it

copper dew
#

and in the list, just add your guild id in there

#
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix=".", intents=intents)
echo pagoda
#

One last question, how come there are tons of backslashes in the .json?

copper dew
copper dew
#

nothing wrong from what i can see. heroku is known to mess some stuff up w/ discord bots

#

np

#

i'll say dont use replit or heroku

#

digitalocean, oracle free tier, gcp free tier, aws, azure, etc

#

if your in a bind then oracle free tier would work

#

yes

#

i would avoid staying away from replit and heroku

echo pagoda
copper dew
#

here are some options:

  • AWS
  • Azure
  • GCP
  • Oracle
  • DigitalOcean
copper dew
echo pagoda
copper dew
echo pagoda
#

Tried to change the extension to .txt earlier (after the filename) and it worked but still had the backslashes

copper dew
#

probably the reason why is that it's not escaping the data since it's directly being piped in as bytes

echo pagoda
#

So there's no workaround

#

Oh well

#

Someone @ me if there's a workaround

echo pagoda
#

figured it out

#

Friend helped
file = discord.File(fp=io.BytesIO(bytes(json.dumps(itemData, indent=4).replace("\\", ""), encoding="utf-8")), filename=f"{url}.json")

copper dew
#

ok !

proud mason
#

Railway probably shares ip too

copper dew
#

ok got it

fervent cradle
#

this is my code and i keep getting missing permission error though i already error handled it

@kick.error
    async def kick_error(self, ctx, error):
        if isinstance(error, discord.Forbidden):
            k_resp = discord.Embed(description=f'Error kicking user. Please check if the user is still on this server and my highest role is above their highest one.', colour=discord.Colour.red())
            await ctx.respond(embed=ke_resp)
        elif isinstance(error, commands.MissingPermissions):
            k_resp = discord.Embed(description=f'Error kicking user. Please check if the user is still on this server and my highest role is above their highest one.', colour=discord.Colour.red())
        else:
            k_resp = discord.Embed(description='Something went wrong from the backend', colour=discord.Colour.red())
            await ctx.respond(embed=k_resp)
            raise error
clever nova
#

is it possible to use slashcommand parameters in a dynamic cooldown?

`def my_cooldown(slash_command_parameter):
if slash_command_parameter == "pasword":
return None
else:
return commands.Cooldown(1, 30)

@bot.slash_command(name="cooldown_test", description="Test")
@commands.dynamic_cooldown(my_cooldown(slash_command_parameter), commands.BucketType.user)
async def cooldown_test(ctx: discord.ApplicationContext, slash_command_parameter: str):
print(dir(ctx))
await ctx.respond("message")`

clever nova
#

On a little bit more context: my users can send some parameter and if the paremeter is correct, the i want to give it a cooldown, and if not, they should be able to try again immediately

pseudo glen
fervent cradle
#

hello i need some help ^^
I have a rank system in a library not in the main.py file and I get the error when I want to run the "rank" command
discord.ext.commands.errors.CommandNotFound: Command "rank" is not found

here is the code

cyan quail
fervent cradle
cyan quail
#

what pycord version

fervent cradle
#

py-cord==2.0.0b7

cyan quail
#

upgrade to 2.2.2

fervent cradle
#

how?

pseudo glen
#
pip install -U py-cord==2.2.2
fervent cradle
#

okay

fervent cradle
pseudo glen
#
self.bot_get_channel(...)
fervent cradle
#

okay

#

the code is from a friend from me

tame rose
#

Is it possible to have the slash command options to change depending on the first option?

spice oyster
#

Do you mean the values or the names?

tame rose
#

The number of options actually

spice oyster
#

I'm pretty sure that's static.

#

You can make all of them optional and check on execution.

tame rose
spice oyster
#

If you want a given option to only show when another one is being selected, it's probably better to register another command.

rugged lantern
#

how u gonna judge others when every single time you try to do something you need someone to hold your hand?

sinful pivot
#

How can I check if a user has a role(and I'm not asking about .has_role(), I need to check it inside of the command callback

proud mason
#

returns a list of roles

wary rover
#

Hi there!
Do you know how to open a modal by setting the values when opening from a variable?

Something like this:

EditModal = Modal(title="Title", arg1, arg2, arg3)
proud mason
# proud mason returns a list of roles

you can then make a list of role ids the user has using list comprehension user_role_ids = [role.id for role in User.roles]

and then if you have the id of the role you want to check, if test_role_id in user_role_ids:

wary rover
proud mason
#

and how do you want them? as the name of the input texts?

proud mason
#

so what you do is

#

EditModal = Modal(title="Title", InputText(label=arg1), InputText(label=arg2, ...)

wary rover
# proud mason `EditModal = Modal(title="Title", InputText(label=arg1), InputText(label=arg2, ....
async def editField(editInteraction, originalInteraction, fieldEditID):
    EditModal = Modal(title="Modal Title")


class Modal(discord.ui.Modal):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        
        self.name = None
        self.value = None
        self.inline = None
        
        self.add_item(discord.ui.InputText(
            label="Title", 
            style=discord.InputTextStyle.short, 
            max_length=2048, required=True, 
            value=None))
        
        self.add_item(discord.ui.InputText(
            label="Value", 
            style=discord.InputTextStyle.long, 
            max_length=2048, 
            required=True, 
            value=None))
        
        self.add_item(discord.ui.InputText(
            label="Inline", 
            style=discord.InputTextStyle.long, 
            max_length=5, 
            required=False, 
            value=None)) 
        
        
    async def callback(self, interaction: discord.Interaction):
        ...
#

I got that for the moment

#

What should I change to define the values of the inputsText?

wary rover
#

I should do that

class Modal(discord.ui.Modal):
    def __init__(self, name, value, inline, **kwargs):
        super().__init__(**kwargs)
spice oyster
#

It seems like what you called channel is not a channel.

wary rover
#

If I delete a message after 10 minutes, is there a way to send a message after the automatic deletion?
Or to execute a function?

cyan quail
#

raw_message_delete may be better for caching reasons

thorny breach
#

How can i get a list of all application commands, Tried using client.application_commands but i want it to include commands from groups too. I looked in the documentation and couldn't find anything else.

thorny breach
#

Oh thanks!

wary rover
wary rover
#

It's ridiculous but I don't know and I don't find

simple canopy
#

i don't think it's possible, at least with on_message_delete

#

yeah, it's not possible

#

you can try looking up audit log to check for last record of someone deleting a message

#

that way, theoretically, you can do that

#

discord.Guild.audit_logs()

wary rover
simple canopy
#

if you are using delete_after, then the user who deleted the message is obviously the bot

wary rover
simple canopy
#

well... i'm pretty sure you can use wait_for

#

as Nelo said

#

just use message_delete instead of message

wild socket
#
Ignoring exception in on_connect
Traceback (most recent call last):
  File "G:\W\WitchlyDev\witchlydev\lib\site-packages\discord\client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "G:\W\WitchlyDev\witchlydev\lib\site-packages\discord\bot.py", line 1138, in on_connect
    await self.sync_commands()
  File "G:\W\WitchlyDev\witchlydev\lib\site-packages\discord\bot.py", line 692, in sync_commands
    registered_commands = await self.register_commands(
  File "G:\W\WitchlyDev\witchlydev\lib\site-packages\discord\bot.py", line 581, in register_commands
    registered = await register("bulk", data, _log=False)
  File "G:\W\WitchlyDev\witchlydev\lib\site-packages\discord\http.py", line 359, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In options.4: Required options must be placed before non-required options
#

i am oddly getting this error

wary rover
wild socket
#

everytime i start the bot

simple canopy
wild socket
#
class WitchlyBot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix = "!", intents = discord.Intents.all(), help_command = None)
``` i thought this to be problematic
#

but apparently its not

simple canopy
#

check your commands

wild socket
simple canopy
#

but the error triggers on sync_commands

#

may be you have some that you forgot about

wary rover
#

The "wait_for" will have been the solution

@cyan quail @simple canopy
Thank you for the time you gave me! 🙂

vapid pumice
#

Does anyone have a Dockerfile on hand that I can review? I'm struggling to build my first image.

#

currently:

FROM python:3.10-alpine

ADD main.py .

COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt

COPY . .

CMD [“python3”, “./main.py”] 
simple canopy
#

i have something like this, it worked last time

vapid pumice
#

I'm just so confused because it will not let me build the image with
docker build -t my-bot .

round rivet
#

is there an error

vapid pumice
# round rivet is there an error

failed to solve with frontend dockerfile.v0: failed to read dockerfile: open /var/lib/docker/tmp/buildkit-mount1079146588/Dockerfile: no such file or directory

#

I just am really lost in what I'm doing here tbh. This is very different than the sort of hosting I'm accustomed to :/

round rivet
#

You need to set a WORKDIR

#

I believe

vapid pumice
#

so like KOTA\kidsoftheapocalypse\main.py

round rivet
#

it's the directory you want everything to run in