#Basic Pycord Help (Quick Questions Only)
1 messages · Page 27 of 1
upgrade to 2.2.2
did not change anything, just tried it
(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
the commands wont even register back
it disappeared when I commented it
And when I decommented it, it does not come back
is this in all guilds?
could you try adding another guild?
I reinvited the bot, andn ow there is no commands at all register
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)
have you overridden any events?
yes multiple
@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)
aaand there it is
there is also on_application_command_error, on_member_update, on_ready
if you override on_connect, you must include await bot.sync_commands()
thanks you !!! it worked !
allgood
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()
if it's random then it's likely a network issue
or you have potentially blocking code that runs before the callback
Is it possible to convert discord emoji into raw/unicode emoji? like :thumbsup: > 👍
Yes, await ctx.send('\:thumbsup:')
rn looking at https://docs.pycord.dev/en/master/api.html#partialemoji, is it good approach?
not exactly what I mean I think
Could you explain more?
I need an actual 👍, not 👍 or \👍
OH
Im not sure how you are sending that, so i cant help you. Maybe an actual helper can
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
partialemoji should work
InvalidArgument: PartialEmoji is not a custom emoji
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.
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.
pretty sure they aren’t planning to
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.")
yeah
Thanks 😄
I hate that limitation. 
there's also a skill limitation
I can deal with that. 
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.
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
wym used the app
The SQLite app.
then you probably didn't click the obvious 'write changes' button on top
i assume u mean in db browser
Yes.
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
The thing is when I go to click the thing that says write changes it’s greyed out.
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)
would this work?
async def cmd(self, ctx):
x = "hey there"
await ctx.send(x)
Send your full code.
yeah im just dumb figured it out 💀 nvm ty
ok
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.
send full traceback
What do you mean by self full trace back?
autocorrect
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
There you go.
Oh shoot forgot to turn off the ping sorry.
what's your decorator(s)
@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.
you are taking multi-word options in slash commands, which doesn't exist. remove the *,
So would Id just work the same?
yes
also you may want to typehint correctly. ctx is a discord.ApplicationContext
Oh so the *, is probably what was setting it off, right?
yes
full traceback?
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.
Im trying to get a bot to fetch the contents of a reference message. Can i not use slash commands for this?
How can I get the channel id of the channel in which a slash command is used in
ctx.channel i believe
worked ty
you could try:
ctx: discord.ApplicationContext, id: Option(discord.User, "User to unwarn")
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
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
Did you type "but I can" instead of "but I can't"? Anyways, I don't know how to do that, if even possible.
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.
Actually, there is a solid a workaround for it that I've used in my code, but it goes outside of the View.
view = self.MyView(self.bot)
view.children[0].label = test
Instead of passing it as parameter, you change the value for that field after creating the View.
oh ok, that could work, thanks
Hey @spice oyster want to help me in #1028563234552283156 ?
I can try but I've never used bridges.
OK
I can't run two task loops at once, only the first one I say .start() to runs
Does anyone know how to disable this error?
Because this error is spamming my console
maybe update aiohttp?
How do I accept all channel types in discord.Option except voice
for slowmode command
discord.TextChannel
i'd say use discord.TextChannel as the main type, then use the channel_types arg to fill in the rest with discord.ChannelType, e.g. py from discord import ChannelType ... channel: Option(discord.TextChannel, "Select a channel", channel_types=[ChannelType.text, ChannelType.category, ChannelType.forum, ...])https://docs.pycord.dev/en/master/api.html#discord.ChannelType
ok ty
also how do i create a subgroup of a subgroup
but some bots have three
i want that
then do group.create_subgroup
group is main slashcmd group
didnt work
it said a subgroup cant have a subgroup
can you show the code?
well i did it 1 week ago
make sure you're on 2.2.2
i did:
group = discord.SlashCommandGroup("group", "group desc")
sub = group.create_subgroup("sub", "sub group")
j = sub.create_subgroup("j", "j desc")
...as i said, the max is group subgroup command
a subgroup can't have another subgroup
oh
well
how do i get the space between subgroup and command
? it does that for you...
you just make a command under the subgroup like @sub.command(...)
ok i think im dumb, im sorry
how to make the slash command not displayed to ordinary users?
you mean only for the users with the permission?
Here's the slash perms example.
Yes. So that the rest of the team would not be visible
these commands will not be seen by those who do not have access?
they won't be visible at all for the most part
Since when? Why for the most part?
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
like several months ago
Do you mean Discord version?
Here's the basic voice example.
Can I make a Slash Command not visible/usable to users that aren't in a list? I can't use Roles.
can be done from guild settings > integrations
Is it impossible to do via the bot itself?
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.
beingdatetime.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 usedatetime.now(timezone.utc).
Luckily, this is built into the library asdiscord.utils.utcnow()
and how to disable it in certain channels?
can only be done in guild settings > integrations
@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?
well you still need to respond with a message
Thought that was what the followup was
Hm so can I just throw another followup in the except?
as i said, discord.utils.utcnow() is a shortcut for this
you could combine dir(self) which returns all class attributes and methods with typing.callable which returns true if an object is callable
remove the return?
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?
Delete the indentation near that line and write it again by using the same characters used for other lines.
you don’t validate it, you just have to check the format
?tag tokens
ok
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
Not sure abt this, but I presume it's being cached or something
and the code for the command may also be caching the results and stuff
How can I do that when executing the command the user and the serer where it was executed put the cooldown
for caching that ? probably would have to cache the results on redis
Nope that did not work.
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.
This is the error.
Ping me if you have any ideas on that.
you have Id, change it to id
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?
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:
Code?
I know it is a pic but I am not at my pc right now so I can’t send the exact code.
I am trying to have all three data columns in one field.
Your query is returning only 2 columns but you are proceeding like if they are 3.
SELECT reason, time and?
Oh that is what I am forgetting I will fix tonight.
I can’t believe I was that stupid to forget that.
Happens to the best too. 
Can I use the same custom_id for Buttons that are in separate Views and have to do different things? 
?tag tias
Thank you. I'll remember this. 
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
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
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?
internet?
idk then
do you know what wrong here
.
can u help me
.
.
please bro like just help me
?tag lp
Official Beginner's Guide: https://wiki.python.org/moin/BeginnersGuide
Official Tutorial: https://docs.python.org/3/tutorial/
Shortcuts:
https://wiki.python.org/moin/BeginnersGuide/NonProgrammers
https://wiki.python.org/moin/BeginnersGuide/Programmers
Learn Python:
https://automatetheboringstuff.com/ (for complete beginners to programming)
https://learnxinyminutes.com/docs/python3/ (for people who know programming already)
https://docs.python.org/3/tutorial/ (official tutorial)
http://python.swaroopch.com/ (useful book)
http://www.codeabbey.com/ (exercises for beginners)
oh wow thats uhh yeah wow
this feels very logos + duplox
u may want to look into this package: https://pypi.org/project/art/
o.O
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
Yes, it's stable.
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
You are using ctx above. Don't mix.
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
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
why not just call the function/method itself from the code?
Don't mind my stupidity 😄
I guess you are passing a SlashCommand as parameter but then treating it as something else, probably due to a wrong number of parameters.
Then debug it
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
5000 fucking lines in your main holy
Where's your guild defined
wait
guild_id = int(guild_id)
tolv = self.bot.fetch_guild(guild_id)
@full basin
Fetch guild is a coroutine
oh i forgor
also how do i get the count of text channels
So ctx.message.delete()?
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
Did you change anything recently? Make sure that you aren't overriding on_connect() and that you don't have debug_guilds for your bot.
oh yeah i am overriding on_connect, should I not do that? And no I dont have debug_guilds
code for reference
You can, but have to add this inside it.
if bot.auto_sync_commands:
await bot.sync_commands()
ah thank you!
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
in progress ##1636
Does deferring work for buttons?
yes
Ok thanks
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?
is there any example or anything for dynamic cooldowns?
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)
I didn't know about invisible existing! I should try that for one of my commands. 
You must pass embeds, as a list.
How could I put the commands in a seperate folder
Search for "cogs" in the guide.
okay thanks!
But it still shows that the bot is thinking. I'm confused. 
https://docs.pycord.dev/en/master/api.html#discord.InteractionResponse.defer
This parameter does not apply to interactions of type InteractionType.application_command.
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.
use utils.snowflake_time to convert ctx.interaction.id to datetime
https://docs.pycord.dev/en/master/api.html#discord.utils.snowflake_time
maybe we should also have interaction.created_at? idk
This is what it looks like right now.
is format_dt not working...?
Are you using created_at? Show some code.
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?
well you need to use unix time stamp in... timestamps
So how would I do that then as I have not worked with those yet?
this will give you unix timestamp
timetuple takes datetime object
So I would change the datetime.now() to datetime.timetuple?
And what would I change the part of the embed to?
I am confused.
What do I have to change and to what?
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
this also (just sharing the way i do and it works for me)
yeah fair
So where would I put that?
you also don't need to use timetuple, you can do datetime.now().timestamp() for the unix int
And anything I need to change here?
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?
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.
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
Exactly. I was going to say the same.
timestamp = int(datetime.datetime.now().timestamp())
await context.respond(content = f"<t:{timestamp}:f>")
pretty much
basically here, change it to int(datetime.now().timestamp()) and that'd be it i guess
unless you run into some clash with datatypes, in which case either change the column's type or store it as str(int(...))
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.
I was hoping for a better solution but I guess it's not possible to count on Discord API for that.
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
ok thx
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?
if it lags, your entire bot will be waiting on that thing to finish
or if 3 people use it, it will take 3 times as long
it would be better to use sqlalc. asyncio
Thats what I figured. I'll work on converting everything over
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
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
- https://docs.pycord.dev/en/stable/api.html#discord.Member.timeout_for
- probably automod but idk
ty
np
so it'd look like
it would be
await message.author.timeout_for(datetime.timedelta(minutes=5))
import datetime ?
hey, i'm trying to use dynamic cooldown in slash commands but the cooldown doesn't work , can someone help me
code ?
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
k i'll remove the json file and try
ideally you'll want to store the data in a db instead of a json file
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
hm ok
this doesn't work either
then im not sure tbh
How do you get the modal's contents after submission? Am I supposed to use interaction.data?
Nvm, I got it. It's accessed through children.value
Does anyone know how to fix this?
by reading
?tag codeblocks
No tag codeblocks found.
?tag codeblock
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.")
How can I log every slash command when someone uses it in a specific discord server channel
without breaking anything
use the on_application_command event
https://docs.pycord.dev/en/master/api.html#discord.on_application_command
wont pycord have something default like:
run the application cmd or smth
no, it's an extra event
oki
you can use it safely
ok ty
how do i get who invoked the cmd
do i just input ctx
the event takes ctx as its argument, which is the standard ApplicationContext you see in commands
ok
and how do i get which cmd
is edit_original_message changed to edit_original_response?
ctx.command
oki
yes, but edit_original_message will still stay as an aias
also it is not working
i want to edit the view
i want to edit the message in which the button is a component
unkown webhook error
you should do interaction.response.edit_message
ohk
edit_original_message is for edits to the response, not the original message
it always confuse me whenever i come across it, make this clear when?
hence why it was renamed to edit_original_response
ok this works, but then shouldnt be the interaction.response name be also changed?
Can my bot fetch users who arent in any of its guilds? If so, how?
v3 is not near lmfao
Well yeah, I was just saying it will be removed in v3
bot.fetch_user
lol
No, as interaction.response is the actual interface that deals with responding
I mean you can do that if you want
can i also use this for hackban
I guess?
alr
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
returns: Unknown User
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 ^
You have to convert to int
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. 
i did
Doesn't look like it
member_id = int(member_id)
also why isnt bans = await ctx.guild.bans() not working
bans = await ctx.guild.bans()
TypeError: object BanIterator can't be used in 'await' expression
Use .flatten()
It will return a list
Idk then, must be wrong
Exactly you need to flatten it
lemme try
What version are you on
await ctx.guild.bans().flatten?
.tag tias
2.2.2
You need to call flatten
ik just asking
the position
await ctx.guild.bans().flatten()
how would i get all the user's name and ID
async for?
No
then?
Not async once it’s a list
oki
interaction.message gets the message the interaction was initiated from, while original_message gets the first response message from the bot, which is why it was renamed to original_response
So, if I click on a button and immediately call original_response() in the callback, do I get nothing?
It will error
What's the difference between interaction.response and interaction.original_response() then?
interaction.response is used for responding
Oh, right! Dumb question. 
Now, if I do Solved.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.
I know why! I'll try using interaction.message.raw_mentions[0] because docs says it's the way to go in private messages.
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
What's the difference between Bot.cogs and Bot.extensions attributes?
Write guild_permissions instead of permissions.
I now get 'ApplicationContext' object has no attribute 'guild_permissions'
its not getting the bots permission. its now trying to get the permission of ctx, which isnt a thing
Try removing .guild and start with ctx.me instead.
figured it out, it was if ctx.guild.me.guild_permissions that did the trick
Yes, that's what I meant the first time. Good, good.
wait is edit_original_message fully removed from v2.2.0?
No
I'm guessing it won't ever be removed right?
It will remain for the entirety of v2
for v3 it'll be removed?
Yes
alr thanks 👍
v3 will likely have larger breaking changes to worry about, but that's not for a while
I see, thanks for the quick response!
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
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()
I'll check it out
I'm really struggling with the UI so it might be complicated
see this example, it should help you https://github.com/Pycord-Development/pycord/blob/master/examples/views/button_roles.py
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/button_roles.py at master · Pycord-Development/pycord
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
bots cannot have rich presence
if you want to change a user’s rich presence, see https://github.com/qwertyquerty/pypresence
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
at least you can use the time formatting for them only in about me rip
oh also, you cannot have start and end times. Either a start or an end.
Oh really? An end time would make more sense but I could've sworn there were two fields for "start playing at" and "round finishes" etc
I can just have a command or message trigger for that one 😅
Does the event on_scheduled_event_delete get fired after the ScheduledEvent end_time has passed?
i'd assume no unless the event deletes itself after the end_time has passed
which i don't think it does...?
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.
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
Ah, maybe it'll auto-update. Thanks for the thought
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.
nice
Why do channel mentions show up as #deleted-channel on the mobile client
Thank you so much for taking the time to help me! I have succeeded
you're welcome
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
try printing out things you pull from json
may be you are missing out on something
yeah its printing the right guild
what pycord version are you using?
pip show py-cord
you should try updating
but it may break somethings for you
the latest version is 2.2.2 iirc
?tag commandnoshow
My slash/message/user commands aren't visible. Why?
- 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)
- 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)
-
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 callself.sync_commands()to ensure this is done. -
Discord sometimes gets confused on the client side. If you've checked all of these, hit ctrl-R to force a reload.
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
channel isn't cached by the client
Oh really? That’s how that works? So if I killed my desktop client process and it posted a new embed with a channel mention. It would do the same?
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?
why do you want to delete it? just send it ephemerally
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
Can you use delete_after?
no because then the amount of time the menu is open will be fixed
That's fair.
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
thats applicationContext
it’s just not called delete
isnt that different from delete?
What's the recommended way to implement a function that accepts two types for the same parameter in Python? Should I use overloading?
just take both and figure it out within your code
Do you mean like this?
def send_log(
context: discord.ApplicationContext or discord.Interaction,
event: str
):
it should be typing.Union[a,b]
iirc
Do I need to import Union? I've never used it. 
also vscode was trolling me big time
if you have any modern IDE it should give solutions.
vscode has pretty bad autocomplete imo
i mean its fine when i type everything
static typing ftw
but in this case i did not and i got trolled by it
Found it: from typing import Union.
Is it weird to still call it context in that case? 
yeah
that’s normal
Thanks! Now it's more elegant compared to when I was using overloading.
typically the clients cache try to cache all possible channels on startup, but it can fail/miss some
if you're on python 3.10 you can just use vertical bar py context: ApplicationContext | Interaction
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)
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.
I didn't switch yet because I'm not sure the server where I host my bot supports it. When I run the bot, it says "Python 3.7" in the command prompt. 
Actually, they support 3.10 too! It took me a while to find it. The interface wasn't showing it because it's a new feature, so I have to edit a file for enabling it.
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
I made my bot as a hobby project about a year ago, then took a long break and started coding again last month, so I didn't immediately realize Python 3.10 was a thing. You are pro. 
a friend of mine helped me optimize my dockerfiles, and i've slowly tweaked those over the following months. i've started making bots around 1 year ago and haven't stopped, which is probably the reason why i've been keeping track of the updates
python 3.11 is scheduled to come out 10/24/2022, so gotta prep my packages and bots to update later
I am making a class that inherits from discord.Bot
What is the decorator for methods that need to be slash command?
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
Ok, that's without inheriting
Oh, I don't know. Either that way or like in Cogs. 
Cogs, often known as modules or extensions, are used to organize commands into groups. This is useful
does any one know how to fix
AttributeError: partially initialized module 'discord' has no attribute 'Client' (most likely due to a circular import)
Use pip freeze and paste the results here.
Stay in one channel pls
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>
more than likely u have a file named discord.py (the actual file name, not dpy), and that's causing namespace issues. Rename that file to something like bot.py and it should fix the error
This is fine. I see no conflicts.
the reason why I know that's probably the issue is that it has happened to me before
thx it worked
np !
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
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?
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
I'll try it, thanks for the reply
you are welcome
How can I get the voice channel to which a user is connected with an interaction discord.Interaction?
interaction.user.voice.channel
Why in and not >? 
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?
async def report(ctx, user : discord.Member, reason : str):
Try this
first or second?
first
You should display your code in python next time, it's easier to understand
Are you really creating a list with numbers? Just do if variable > 50 and variable < 100
Or even better,
if 50 <= variable <= 100:
Worthy mention, likely slower
if variable in range(50,100)
"Unknown column guildId"
You made a typo: guilID instead of guildID.
this guy should get his own help channel
or hire a mentor to hold his hand through every step he takes
now im starting to wonder what all stuff will we get in v3
bro fr
After updating to Python 3.10, my remote server gives me this error: ModuleNotFoundError: No module named 'discord' Why? 
how are you installing the requirements?
make sure to do it like python3.10 -m pip .....
Same as before, via a requirements.txt that's automatically being loaded by the hosting provider.
i just broke my head over that 2 days ago cuz apparently my python3 --version was still 3.8 on my vm
this forces it to use 3.10 while installing the requirements
I'll ask on their Discord server because it looks like the issue is on their end.
👍
try python3 --version and if thats not 3.10 then do this ^
how can we gracefully exit a bot in pycord without the error: RuntimeError: Event loop is closed
call await bot.close()
and the library should do everything about the event loop
i wanna use it when someone keyboard interrupts
also btw that also raises the event loop error
i just cant understand how i can close a bot gracefully without raising all these errors
ok
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
They will look into that issue. I'll run it on the previous version for now.
What are the parameters given in on_error? the docs say event_method, *args and **kwargs. Not sure if ctx is included.
I don't think it's included in that, but you can get it from on_application_command_error().
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
send a blank response (make sure to try/catch or contextlib.suppress the inevitable HTTPError). It's a hack, but it's currently the only way that I'm aware of.
class MyModal(Modal):
async def callback(self, interaction: discord.Interaction):
# ...
with contextlib.suppress(discord.HTTPException):
await interaction.response.send_message()
Did you try to make it hidden with ephemeral = True? I'm not sure if it fits your needs.
Because if the person receives 13 ephemeral messages it's always so disgusting
I'll give it a try, it doesn't promise to be perfect
thx 🙂
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
but mobile support?
Discord is wasting so much screen space on mobile. 
It work perfectly, thanks ! 🙂
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()
you need to get server.start() outside of function
delete or what do you mean?
you're calling a function inside of function
@tasks.loop(hours=5)
async def server():
...
server.start()
Here's the background task example.
can someone help me out here please
i dont understand it 😦
Concept
yea but it dont work
can someone please help me out here, i am struggling with this
you can use loop_until_conplete
where and how?
this article explains it better: https://pythonalgos.com/python-asyncio-run-vs-run-until-complete/?amp=1
can someone help me
wait no that wont work, to break it down the problem is i need to use a synchronous function , i.e., def and not async def and in that function i need to run another imported function which is asynchronous and needs to be awaited and i cant await it since the main function is synchronous
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 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
def nuke_cooldown(ctx):
premium_check = asyncio.new_event_loop().run_until_complete(db.check_premium(ctx.guild.id))
if premium_check == True:
return None
else:
return commands.Cooldown(1, 60)
launches the runtime error: Cannot run event loop while another loop is running and the runtime warning: Enable tracemalloc to get the object allocation traceback
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)
get nest_asyncio
and what’s not working
when i start it nothing happens
did you run server.start()
here
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")
?
wdym
the Discord activity script is in an on_ready and not working if i put the server.start() in a on_ready
I don’t see the problem
look
you can put it after the presence change
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
you can put both in one on_ready
you’re welcome
Can you you have slashcommand choices pulled from a list?
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
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
self?
it should take 3 args: self, ctx, and error
oh wait yea, forgot that thank you so much for the help
Sorry to interrupt, could I have an answer to my question? 
Interactions must be responded within 3 seconds without defer or within 15 minutes with defer.
Other than that, I'm pretty sure that editing a message doesn't have a time limit.
is there a Option in bridge_command ?
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 ?
Is there a limit on how many tables should be in one file for aiosqlite DB’s?
like 2^32-1?
And your disk space. 
if needed, you can also move the db to something like postgres or mariadb
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
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
How do you get options for a slash command eg. on a ban command
.docslink discord.Option
?tag guide
Full traceback
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
How would I check if the message came from the authors DM?
You could check if the message.guild attribute is None
I am making a loop, that runs multiple bots using 1 file
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
@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.
It looks like you ran it twice, ran the command twice
I didn’t trust me.
Is this the only command that does this?
u didnt trust u?
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.
Does the prefix command do that? If it does, you probably have 2 instances of the bot running.
It does but see I don’t have two instances running tho.
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?
it 100% is two instances running, so the best you can do is cope
Regenerate your token.
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
You should be type hinting Option
Also I try doing the bridge command and it says that context object has no attribute ‘respond’
.docslink discord.BridgeContext
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……
sorry, can you give me an example, because i dont know what hinting means
.tag learnpython
Official Beginner's Guide: https://wiki.python.org/moin/BeginnersGuide
Official Tutorial: https://docs.python.org/3/tutorial/
Shortcuts:
https://wiki.python.org/moin/BeginnersGuide/NonProgrammers
https://wiki.python.org/moin/BeginnersGuide/Programmers
Learn Python:
https://automatetheboringstuff.com/ (for complete beginners to programming)
https://learnxinyminutes.com/docs/python3/ (for people who know programming already)
https://docs.python.org/3/tutorial/ (official tutorial)
http://python.swaroopch.com/ (useful book)
http://www.codeabbey.com/ (exercises for beginners)
You should know how to type hint as it’s a simple aspect of python.
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?
yes it would be
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
I'll put the processing aside for now, can I have it spit out a text file instead of a message?
yep
probably would want to use the file parameter when sending the results
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)
something like this (note that this has not been tested yet, may not work):
import discord
import io
# Assumes the rest of the setup code has been declared
file = discord.File(fp=io.BytesIO(bytes(json.dumps(dict(img.text.items()), indent=4))), filename="results.json")
await ctx.respond(file=file)
ideally the results should be sent as a embed
but the results are parsed and formatted so it isn't raw json
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
oops probably should be this:
file = discord.File(fp=io.BytesIO(bytes(json.dumps(dict(img.text.items()), indent=4), encoding="utf-8")), filename="results.json")
Yep that works, thanks. Any way to include the url both before the metadata in the file and/or as the filename?
for the filename, just replace the filename arg with something like this: filename=f"{url}".json
for the metadata in the file, probably want to dump both the img.text.items() dict and a dict containing the metadata url as well
So just add another dict with the url after the img.text.items?
yeah
since json.dumps accepts only 1 object, you would have to add the metadata to the dict of items as well
Anyone have experience hosting with Digital Ocean? I'm STRUGGLING to set this thing up because it isn't recognizing my Procfile 
Trying to figure it out
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)
digital ocean doesn't use procfiles
Right - so what do I use instead? >.<
2 ways: Dockerize your app and deploy as an app on digitalocean, or get a droplet and run it manually in the droplet
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
Thanks for this info
Going to look up " how to dockerize " hehehehe
np ! i deploy all of my bots using Docker for prod
hmm
probably forgot to add a ) at the end
It's highlighted
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```
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")
have you imported discord.ext.commands ?
yep i have
Runs but returns this when feeding it a url discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NameError: name 'item' is not defined
might want to add this. the only way to append a dict is to use the update() method:
url = "https://example.com" # This is the metadata url
itemData = dict(img.text.items())
item.update({"url": url})
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)```
might want to swap the order of both decorators
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}")
Yep that works, thanks a bunch
np
Oh yeah, where do I have to define the command's description?
The one that pops up when typing it out
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"""
Yeah I did it with the description, was the simplest
ok !
"This command is outdated, please try again in a few minutes" huh
generally when that happens wait a couple of minutes. this happens when you are loading the command globally, and it needs some time to update. if you are just testing it, you can pass in guild_ids=[] (in @bot.slash_command()) to load it only in your guild
Aah, got it
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)
One last question, how come there are tons of backslashes in the .json?
probably has not been escaped yet. not sure how to escape the data tho
Got it
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
Let me know if you find out
here are some options:
- AWS
- Azure
- GCP
- Oracle
- DigitalOcean
ok
Would using another file format work?
it might but im not sure
Tried to change the extension to .txt earlier (after the filename) and it worked but still had the backslashes
probably the reason why is that it's not escaping the data since it's directly being piped in as bytes
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")
ok !
Railway and heroku are almost the same
Railway probably shares ip too
ok got it
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
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")`
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
and you don't call the function inside dynamic_cooldown, it should just be my_cooldown
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
are you sure the cog is loading?
so?
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
what pycord version
py-cord==2.0.0b7
upgrade to 2.2.2
how?
pip install -U py-cord==2.2.2
okay
hello i need help when i want to send the level up message to a specific channel i get the following error
channel = bot.get_channel(1030800368197718036)
NameError: name 'bot' is not defined
self.bot_get_channel(...)
Is it possible to have the slash command options to change depending on the first option?
Do you mean the values or the names?
The number of options actually
I'm pretty sure that's static.
You can make all of them optional and check on execution.

If you want a given option to only show when another one is being selected, it's probably better to register another command.
how u gonna judge others when every single time you try to do something you need someone to hold your hand?
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
User.roles
returns a list of roles
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)
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:
whats arg1, arg2 and arg3
strings
and how do you want them? as the name of the input texts?
ah simplee
so what you do is
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?
I should do that
class Modal(discord.ui.Modal):
def __init__(self, name, value, inline, **kwargs):
super().__init__(**kwargs)
It seems like what you called channel is not a channel.
Yep that should work
Tias
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?
on_message_delete? or wait_for("message_delete")
raw_message_delete may be better for caching reasons
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.
Oh thanks!
I can't find the attribute that tells me who deleted the message. Any clue?
wdym
How do I know who deleted a message?
It's ridiculous but I don't know and I don't find
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()
The "delete_after" is not displayed in the logs....

if you are using delete_after, then the user who deleted the message is obviously the bot
I want to start a function when my message is deleted, how do I do that with a "delete_after"?
well... i'm pretty sure you can use wait_for
as Nelo said
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/wait_for_event.py at master · Pycord-Development/pycord
just use message_delete instead of message
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
i will try
everytime i start the bot
you can't place unrequired options before required ones
i think i understood the error, but apparently its not pointing me to anywere where i might have made the mistake.
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
check your commands
commands are not slash, they are normal, and commands does not raise any error upon startup of the bot. they raise errors when used
but the error triggers on sync_commands
may be you have some that you forgot about
The "wait_for" will have been the solution
@cyan quail @simple canopy
Thank you for the time you gave me! 🙂
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”]
Main Discord Bot of "DTVU" https://discord.gg/FgCHydMram - T84/Dockerfile at master · TheGiga/T84
i have something like this, it worked last time
I'm just so confused because it will not let me build the image with
docker build -t my-bot .
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 :/
Would that be the relative location of my main.py?
so like KOTA\kidsoftheapocalypse\main.py
it's the directory you want everything to run in

is the most reacted reaction on this post