#discord-bots
1 messages Β· Page 352 of 1
is it a case of you run a command, it replies with a view for you but other members are pressing buttons and running things meant for you?
buttons
Ohh didnt read that correctly.
No, its a "static" message.
Its a ticket bot so you can see what i mean by static message.
wdym by a static message?
Its a message that stays in the channel
yeah. whats the issue?
The message has a button, i want that button to have cooldown
Im using disnake
why does the button need a cooldown?
any stratus on user installed commands ?
maybe not in the stable branch but some other version (py-cord)

Members are spamming it...
so dont let them spam it by checking in the buttons if the interaction user is you
or the person that ran the command
I want it so everyone can press it.
you can make it disabled and then re-enable it
can i do it for certain user?
yeah
compare IDs or pass through the view __init__
I've created a Discord Modals bot that allows Discord users to fill out information in a Modals form. When users click on a designated button, the bot displays the Modals. However, when I don't submit any information and leave it for about 6 minutes, and I or others click the button again, it shows a 'Not Responding' alert. I want it to be always available. Whenever someone clicks on the designated button, the bot should always display the Modals to the user. (Can anyone help me?)
OHHH let me try that
(i recommend the view __init__)
they'll obviously expire after some time. that's what happens with views, although a 6-minute timeout is a bit strange, considering i believe the default is 15
why not just run the command again?
I've seen someone do this before, but I have no idea how they did it. They made the bot send an embed message to a text channel with a button at the bottom. No matter how long it's been, even months later, whenever someone clicks the button, the bot always displays the Modals to the user without sending any messages or restarting the bot every 15 minutes. I'm wondering if there's a way to do this
probably needs a persistent view
I understand that restarting the bot will make the button work (the button that displays modals), but I don't want to do it this way. I want the button to be always ready to work. Please tell me or give me some ideas
The way is with a persistent view. But you can't retroactively make this work with already-sent buttons, unless those buttons had a custom ID specified.
https://github.com/Rapptz/discord.py/blob/master/examples/views/persistent.py
beat me to it, i just tabbed back into discord 
Thanks for the ideas! I'll try them out first
also shilling my own guide on persistent views
https://gist.github.com/thegamecracks/0f9ab7ad3982e65ff4aa429acb39cc4e
worth mentioning that the dynamic buttons here aren't yet released
in dpy what type of channel is #1035199133436354600
!d discord.ForumChannel
class discord.ForumChannel```
Represents a Discord guild forum channel.
New in version 2.0.
x == y Checks if two forums are equal.
x != y Checks if two forums are not equal.
hash(x) Returns the forumβs hash.
str(x) Returns the forumβs name.
π₯
how do dpy embeds format datetimes?
i want it to say Today at X:XXxx
where xx is am or pm and X:XX is a 12h format
it depends on the user's locale, e.g. en-GB would show 24h while en-US shows 12h
assuming you're using Embed.timestamp or discord.utils.format_dt()
Embed.timestamp is what i'm using
does .format_dt() even work for this?
oh for the former you can only pass a datetime
format_dt() should format correctly in titles, descriptions, field names, and field values
should i set a timestamp or set a footer for what i want
err you can set both at the same time, but the timestamp markdown from format_dt() won't work in the footer
i just want this
then Embed.timestamp
will it come out the way i want?
^
i live in the UK but i want it to be 12h
embed = Embed(
description = 'something else',
timestamp = dt.now()
)
print(embed.timestamp)
# prints "2024-04-15 14:36:20.202777+01:00"```
discord only expects your bot to send a unix timestamp for the embed, but rendering it is entirely client-side
this is python's default representation of a datetime object, dpy doesnt fiddle with that
other than localizing it to your system timezone
yeah bro i saw 
Just do discord.utils.utcnow()
Always doing to much
yeah but what is it
@viscid hornet imma meet u irl and beat u up istg.
We gonna have a whole fight for the fuck of it lmao
what is your problem 
Idk
is it better than py for displaying tracebacks?
Just wanna bully u
this guy 
πππ
def not, its a different file format
Alr ill leave u alone now. Have a good day π
!pastebin
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
@pale zenith I've finally solved the Modals Time Out issue! Thanks for all the fresh ideas you provided
no problem π
@bot.command(name="claim")
async def claim(ctx):
user_id = str(ctx.author.id)
with open("user_data.json", 'r') as f:
user_data = json.load(f)
print("claiming!!!!")
if user_id not in user_data:
user_data[user_id] = {}
users_cards = user_data[user_id]
rng_num = random.randint(1,150)
print(rng_num)
if rng_num <= 9:
rng_num = "00" + str(rng_num)
elif 10 <= rng_num <= 99:
rng_num = "0" + str(rng_num)
else:
rng_num = str(rng_num)
print(rng_num)
with open("cards.json", "r") as character_data:
characters = json.load(character_data)
for character in characters:
if character["number"] == rng_num:
claimed_card_number = character["number"]
claimed_card_name = character["name"]
claimed_card_image_id = character["image"]
clamed_card_image = f"cards/{claimed_card_image_id}.png"
claimed_card_desc = character["description"]
break
users_cards[claimed_card_number] = users_cards.get(claimed_card_number, 0) + 1
user_data[user_id] = users_cards
with open("user_data.json", 'w') as f:
json.dump(user_data, f)
embed = discord.Embed(title=f"Claimed {claimed_card_name}!", description=claimed_card_desc, color=0xFFC0CB)
embed.add_field(name="Card Number:", value=claimed_card_number, inline=False)
embed.set_image(url=clamed_card_image)
await ctx.send(embed=embed)```
line 8 doesnt print anything so that means theres something wrong with when i open the json file but im not sure what
do you have any error handlers? also have you tried printing at the start of the command to verify that it's running?
hmm, that does seem odd
what version of discord.py are you using, and how do you run your bot? (minus token)
how do you check version
im running it locally on my laptop in pycharm
generally in the terminal you'd run pip show discord.py or py -m pip show discord.py, but pycharm has a way to check installed packages too
2.3.2
and how do you run your bot?
im wondering if perhaps the logging wasn't configured, cause that could prevent error messages from showing up
I don't understand what you mean... im running it on pycharm on my laptop
i mean like, do you use await bot.start()? or bot.run()
oh, bot.run()
and what arguments do you pass to it other than the token
hmm, that should have automatically configured logging of error messages then...
can you start a python console and try reading the file yourself? py import json with open("user_data.json", 'r') as f: json.load(f)
oh, so the file is empty
but doesnt if user_id not in user_data: user_data[user_id] = {}
add to it even tho its empty
oh wait
json.load() still needs something to be in the file, even if its an empty list or object
i guess you can write {} to your json file as a placeholder and try re-running your command
ah thank you it now prints although the command still doesn't work as intended π
i think i should be able to fix it tho
btw minor tip, there's a few simpler ways to pad an integer with zeros ```py
n = 19
str(n).zfill(3)
'019'
f"Your card is: {n:03d}"
'Your card is: 019'```
ah thank you that is helpful
third time's the charm
str(n).zfill(3) doesn't seem to work
you er, need to print it
oh i get what you mean
zfill returns a new string since strings are immutable
i guess you could say the same about str() too
OH WAIT how did i forget that
idk what immutable means
but i forgot to reassign it to the variable right?
mhm
perfect
when something is immutable, it means you can't change what values it has after you've created it, and that includes integers, floats, strings, and tuples
in contrast, stuff like lists and dictionaries are mutable because you can add new elements to the same object
https://realpython.com/python-mutable-vs-immutable-types/#mutability-vs-immutability
this article seems to be a highly comprehensive explanation of the difference
oh rightt i know
like u cant append and remov
https://discord.com/developers/docs/topics/oauth2#authorization-code-grant-access-token-exchange-example
looking at their example, it seems the client ID and secret have to be passed via basic authorization (auth=), rather than as part of the body
ye
claimed_card_image = discord.File(f"cards\{claimed_card_image_id}.png", filename=f"{claimed_card_image_id}.png")
I saw on the docs it said if you want to use local file for attatchment you have to do it like that but im not sure if this is allowed
embed.set_image(url=f"attachment://{claimed_card_image}.png")
there's two data definitions there, which one are you using?
!intents
the client_id and client_secret doesnt seem to be needed in the data, just auth
based on the api docs ya
attachment://<discord.file.File object at 0x000001D977764DC0>.png
after printing, it seems to just give the claimed_card_image variable as the object but I want the string
you could use file.filename to retrieve it, and that should already include its own .png file extension
so i can remove the .png?
filename=f"{claimed_card_image_id}.png"
to
filename=claimed_card_image_id
i dont mean in the File constructor, but where you use the attachment:// URI
file.filename will match whatever you had set filename in your File() constructor
ah so f"attatchment://{claimed_card_image.filename}"
without the extra t in attachment ye
thats how you spell attatchment
with 4 t
embed.set_image(url=f"attachment://{claimed_card_image.filename}")
is this correct? it no work
no
clearly someone doesn't know how to spell
uhh, I'd give it a quick google first before saying anything
this is how u spell attachment
perhaps it's you that needs the google search
attachment
/ΙΛtatΚm(Ι)nt/
1.
an extra part or extension that is or may be attached to something to perform a particular function.
"the processor comes complete with a blender attachment"
2.
affection, fondness, or sympathy for someone or something.
"she felt a sentimental attachment to the place creep over her"
I need your confidence in life
english words π₯΄
I can assure you that the word is most definitely spelt attatchment with 4 t, trust me I have A* in all my english
yeah I definitely need your confidence lmao
after, printing, it shows the correct file but it isn't sending it in the embed...
Want to upload a local file to discord?
# First create a discord.File object
myfile = discord.File('myfolder/my_local_file.png')
# or
myfile = discord.File(my_buffer_that_i_created_previously)
# and then send it via .send()
await ctx.send(file=myfile)
docs:
- discord.File: https://discordpy.readthedocs.io/en/latest/api.html#discord.File
- abc.Messageable.send: https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send
but I'd like to send it in the embed
oh right, you had a cards/ directory in your filepath... maybe dpy doesnt separate it from the .filename attribute?
well if thats the case, i guess you're forced to repeat just the filename in your url, e.g. f"attachment://{id}.png"
that's what I'm doing but it doesn't work...
embed.set_image(url=f"attachment://{claimed_card_image.filename}.png")
im saying that .filename might incorrectly have card/ in it, which isn't allowed by the discord API
nvm, dpy does seem to handle this correctly
when I print it, it just says "attachment://{image}.png"
in one case, it say attachment://tile115.png
can you show the code you have now?
@bot.command(
name="claim"
)
async def claim(ctx):
user_id = str(ctx.author.id)
with open("user_data.json", 'r') as f:
user_data = json.load(f)
if user_id not in user_data:
user_data[user_id] = {}
users_cards = user_data[user_id]
rng_num = random.randint(1,150)
print(rng_num)
rng_num = str(rng_num).zfill(3)
print(rng_num)
with open("cards.json", "r") as character_data:
characters = json.load(character_data)
for character in characters:
if character["number"] == rng_num:
claimed_card_number = character["number"]
claimed_card_name = character["name"]
claimed_card_image_id = character["image"]
claimed_card_image = discord.File(f"cards\{claimed_card_image_id}.png", filename=f"{claimed_card_image_id}.png")
claimed_card_desc = character["description"]
users_cards[claimed_card_number] = users_cards.get(claimed_card_number, 0) + 1
user_data[user_id] = users_cards
with open("user_data.json", 'w') as f:
json.dump(user_data, f)
embed = discord.Embed(title=f"Claimed {claimed_card_name}!", description=claimed_card_desc, color=0xFFC0CB)
embed.add_field(name="Card Number:", value=claimed_card_number, inline=True)
print(f"attachment://{claimed_card_image.filename}")
embed.set_image(url=f"attachment://{claimed_card_image.filename}.png")
await ctx.send(embed=embed)```
oh, if your print statement shows tile115.png, you dont need to add .png in your set_image url
otherwise it would result in tile115.png.png
im referring to ctx.send, basically all send methods in dpy support file=
!d commands.cooldown
No documentation found for the requested symbol.
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command)
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType).
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown) is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error) and the local error handler.
A command can only have a single cooldown.
there we go
thanks i got it working π
i need some advice, only recently ivebeen working with .json files and id like to add currency alongside card collection for the bot, and im aware in .json files u can have variables and/or elements
when should i use what
yo guys, why this error? i was coding levelling system
File "c:\Users\madma\OneDrive\Desktop\CrateBot\main.py", line 59, in <module>
@bot.event()
TypeError: Client.event() missing 1 required positional argument: 'coro'```
How do I report someone who is actively breaking TOS? π€
s o m e h o w
Thanks. Very helpful.
fr
show the code
k
@bot.event()
async def on_member_join(member):
with open('users.json', 'r') as f:
users = json.load(f)
await update_data(users, member)
with open('users.json', 'w') as f:
json.dump(users, f)
@bot.event()
async def on_message(message):
if message.author.bot == False:
with open('users.json', 'r') as f:
users = json.load(f)
await update_data(users, message.author)
await add_experience(users, message.author, 5)
await level_up(users, message.author, message)
with open('users.json', 'w') as f:
json.dump(users, f)
await bot.process_commands(message)
async def update_data(users, user):
if not f'{user.id}' in users:
users[f'{user.id}'] = {}
users[f'{user.id}']['experience'] = 0
users[f'{user.id}']['level'] = 1
async def add_experience(users, user, exp):
users[f'{user.id}']['experience'] += exp
async def level_up(users, user, message):
with open('levels.json', 'r') as g:
levels = json.load(g)
experience = users[f'{user.id}']['experience']
lvl_start = users[f'{user.id}']['level']
lvl_end = int(experience ** (1 / 4))
if lvl_start < lvl_end:
await message.channel.send(f'{user.mention} has leveled up to level {lvl_end}')
users[f'{user.id}']['level'] = lvl_end
@bot.command()
async def level(ctx, member: discord.Member = None):
if not member:
id = ctx.message.author.id
with open('users.json', 'r') as f:
users = json.load(f)
lvl = users[str(id)]['level']
await ctx.send(f'You are at level {lvl}!')
else:
id = member.id
with open('users.json', 'r') as f:
users = json.load(f)
lvl = users[str(id)]['level']
await ctx.send(f'{member} is at level {lvl}!')```
python bug 
You don't need to call the method, just put @bot.event
ok
worked thx
but another bug 
2024-04-15 22:19:34 ERROR discord.client Ignoring exception in on_message```
I mean
That's not a bug. That's an error
Which you should send
That doesn't help
thats an error header
its like if i said "hey guys, can you review my essay?" and i gave you just this:
The problem with British society
"what do you think of my essay?"
lol
and the command no longer work, im new to .jsons file so im not really familiar to going about it
How to remove this when sending message by a bot?
thank you
so im having a problem with my discord bot i fixed the async issue and now it says TypeError: 'coroutine' object is not subscriptable whenever i try to run my !create_character command or any other command thats not !random or !lookup i can send my code if you would like me to
send it
ill haste bine it
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
@bot.command(name="bal")
async def bal(ctx):
user_id = str(ctx.author.id)
pfp = ctx.message.author.avatar_url
with open("user_data.json", 'r') as f:
user_data = json.load(f)
with open("cards.json", 'r') as c:
cards = json.load(c)
if user_id not in user_data:
user_data[user_id] = {"cards": [], "rings": 1000}
user_cards = user_data[user_id]["cards"]
embed = discord.Embed(title=f"Inventory of {ctx.author}", description=f"The inventory of {ctx.author}, displaying owned cards and amount of which.", color=0xFFC0CB)
for user_card in user_cards:
card_number = user_card["number"]
card_amount = user_card["amount"]
for card in cards:
if card["number"] == card_number:
card_name = card["name"]
embed.add_field(name=card_name, value=f"Amount owned: {card_amount}")
embed.set_image(url=pfp)
await ctx.send(embed=embed)```
Trying to print anything after opening the first file fails, but printing before that will successfully print. I made sure that the files aren't empty this time.
@bot.command()
async def get_role(ctx):
activities = ctx.author.activities
for activity in activities:
if isinstance(activity, discord.CustomActivity) and "TEST" in activity.name:
member = ctx.author
add_role_id = ADD_ROLE_ID
remove_role_id = REMOVE_ROLE_ID
add_role = discord.utils.get(ctx.guild.roles, id=add_role_id)
remove_role = discord.utils.get(ctx.guild.roles, id=remove_role_id)
if add_role:
await member.add_roles(add_role)
await ctx.send(f"Role {add_role.name} added.")
else:
await ctx.send("The role to add does not exist.")
if remove_role and remove_role in member.roles:
await member.remove_roles(remove_role)
await ctx.send(f"Role {remove_role.name} removed.")
return
await ctx.send("You must have 'TEST' in your custom status to use this command.")
even with the TEST status it does nothing with the roles
you need to subsitute ADD_ROLE_ID and REMOVE_ROLE_ID for the actual role IDs
just get the role IDs of the 'add role' and 'remove role' and put them where ADD_ROLE_ID and _REMOVE_ROLE_ID are
the code doesn't really suggest what those roles are since they are just referred to as the add role and remove role in the variable names
///
this is already done
ADD_ROLE_ID = 1229097184306266166
REMOVE_ROLE_ID = 1226953019573407755
@bot.command()
async def get_role(ctx):
activities = ctx.author.activities
for activity in activities:
if isinstance(activity, discord.CustomActivity) and "TEST" in activity.name:
member = ctx.author
add_role_id = ADD_ROLE_ID
remove_role_id = REMOVE_ROLE_ID
add_role = discord.utils.get(ctx.guild.roles, id=add_role_id)
remove_role = discord.utils.get(ctx.guild.roles, id=remove_role_id)
if add_role:
await member.add_roles(add_role)
await ctx.send(f"Role {add_role.name} added.")
else:
await ctx.send("The role to add does not exist.")
if remove_role and remove_role in member.roles:
await member.remove_roles(remove_role)
await ctx.send(f"Role {remove_role.name} removed.")
return
await ctx.send("You must have 'TEST' in your custom status to use this command.")
guys is this right code?
why are you using double nesting? what's report[report[...]] and current_user[current_user[...]] supposed to do?
!code
File "C:\Users\lucia\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "C:\Users\lucia\Desktop\Bot Discord\Python\CosmicMC Network\main.py", line 216, in select_callback
if interaction.message.components[0].custom_id == "ticket_select":
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'ActionRow' object has no attribute 'custom_id'```
How is it possible to make global commands like in the screenshot? You can use the command in group chats and so on, and I know what is needed for it but I dont know how to basically 'code' it to work
One message removed from a suspended account.
Hey I want to make a warning system where the warns are stored in a database with the guild id as the identifier. I currently use aiosqlite but my brain isnβt letting me think how I would format it. Yet I know the exact format I would like in json.
{
"1234567890123456789": {
"prefix": "!",
"moderation": {
"warns": {},
"mutes": {}
}
},
"0987654321098765432": {
"prefix": "?",
"moderation": {
"warns": {},
"mutes": {}
}
}
}
group chats like dms?
these are user installable applications #discord-bots message
umbra has an article about it but i dont have the link on hand atm
oh i didnt notice they made an article about it
https://about.abstractumbra.dev/discord.py/2024/04/11/user-installable-applications.html
curiously all of the doc links point to the stable version rather than latest...
Could I use a mixture of aiosqlite and json? Iβm not sure which is the best use for a database here :/
usually SQL is quite suited for discord bots given how often you need relationships between different entities
in your case i'd probably have three tables, one to represent guilds, one to represent warns, and the last to represent mutes
Wait you can have multiple tables in a database file?
of course
Interesting..
for example: sql CREATE TABLE guild ( guild_id INTEGER PRIMARY KEY, prefix TEXT NOT NULL DEFAULT '!' ); CREATE TABLE warning ( guild_id INTEGER REFERENCES guild (guild_id), user_id INTEGER, reason TEXT, PRIMARY KEY (guild_id, user_id) ); CREATE TABLE mute (...);
it also might be a good idea to create a user table in case you need to store user-specific settings
I see, so how would these tables interact? I see there is a reference to the guild table, how does that work?
by default, foreign keys do nothing in sqlite until you run PRAGMA foreign_keys = ON; at the start of each connection, after which sqlite will verify that each warning references an existing row in the guildtable
you can also tack on ON DELETE CASCADE to tell sqlite to remove any associated warnings if you delete a guild from your table
btw these general SQL questions would be more suited for #databases
make it send the actual image file and not just a link
Yeah I understand, thank you for the help! π
hmm actually the primary key i described for the warning table isn't that good, it would mean each user can only have one warning in a guild
i guess no primary key is necessary, although having a warning_id probably would still be a good idea sql CREATE TABLE warning ( warning_id INTEGER PRIMARY KEY, guild_id INTEGER NOT NULL REFERENCES ..., user_id INTEGER NOT NULL, ... ); now it's worth having an extra index on (guild_id, user_id) to optimally look up warnings for a user in a guild
async def cmd(arg1, arg2=None):
#arg1 = Required
#arg2 = Optional```
although that is a pretty good question
@hushed galleon im gonna rely on you for this one
err yeah that's basically it
is the first file "user_data.json"?
also ctx.author is the same as ctx.message.author
also sorry for second ping but i finally got this working
do discord modals work in private messages ?
if not if you have any advice on how to setup a input for like 5 things in messages without spanning buttons or text
all the options are ofc optional
So I have a class:
class AddUser(View, nextcord.ui.Modal):
def __init__(self, channel):
super().__init__(
"Add User to Ticket",
timeout=300,
)
self.channel = channel
and in another class.onready I have my persistent veiw added:
@commands.Cog.listener()
async def on_ready(self):
if not self.persistent_veiw_added:
self.bot.add_view(AddUser())
self.persistent_veiw_added = True
but im getting this error:
self.bot.add_view(AddUser())
^^^^^^^^^
TypeError: AddUser.__init__() missing 1 required positional argument: 'channel'
and I dont know how to get the channel there
self bot
how tho
I tried more than once to do it in diffrent ways but didnt work
brother that's a direct violation of tos
hm?
this doesn't seem right, modals don't usually need to be persistent
Im doing it for a button
yes, it seems
it "seems"?
oh, then whats with it inheriting modal? also persistent views need to have timeout=None set, and a custom ID for all components
oh yeah i found the problem thanks
as for providing the channel, you can use self.get_channel(id) there since on_ready means it should have populated its channel cache
ah ok
how can i send multple embeds in 1 message
i tried using alist of embeds but got an error
embed1 = discord.Embed(color=e_color)
embed1.set_image(url="https://media.discordapp.net/attachments/1229266841688346654/1229558823778258974/coinmined.png?ex=66301ee3&is=661da9e3&hm=7f8816203721ff87c41ef5fde76bbfdc834582b8f720fcc1feb9fb9ebd076f58&=&format=webp&quality=lossless&width=550&height=143")
embed2 = discord.Embed(title="Coin Mined", color=e_color, timestamp=datetime.now(), description=f"""
β
**COIN:**
:dot1: Example Coin
:dot1: 0.1 Mined
:dot1: Mined by {ctx.author.mention}
β
""")
embed2.set_footer(text="Earn your fortune today - CEX")
list = [embed1, embed2]
await ctx.send(content=f"{ctx.author.mention}",embed=[list])```
class MyModal(discord.ui.Modal, title='Feedback'):
# Our modal classes MUST subclass `discord.ui.Modal`,
# but the title can be whatever you want.
# This will be a short input, where the user can enter their name
# It will also have a placeholder, as denoted by the `placeholder` kwarg.
# By default, it is required and is a short-style input which is exactly
# what we want.
name = discord.ui.TextInput(
label='Name',
placeholder='Your name here...',
)
# This is a longer, paragraph style input, where user can submit feedback
# Unlike the name, it is not required. If filled out, however, it will
# only accept a maximum of 300 characters, as denoted by the
# `max_length=300` kwarg.
feedback = discord.ui.TextInput(
label='What do you think of this new feature?',
style=discord.TextStyle.long,
placeholder='Type your feedback here...',
required=False,
max_length=300,
)
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message(f'Thanks for your feedback, {self.name.value}!', ephemeral=True)
async def on_error(self, interaction: discord.Interaction, error: Exception) -> None:
await interaction.response.send_message('Oops! Something went wrong.', ephemeral=True)
# Make sure we know what the error actually is
traceback.print_exception(type(error), error, error.__traceback__)
modal = MyModal()
await message.channel.send('Modal Opened!', view=modal)
How I'm firing it I get a
In components.0.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
In components.1.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
^
are you using the embed= argument or embeds=? only the latter will accept your list
as per the example that jaden sent, you need an interaction in order to send a modal to someone - either by slash command, or a button from a regular View
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
er, it seems you have a list inside your list
this is my code
oh ya you do
you can remove the square brackets around [list] since it's already a list
ty
yup
and modals can't be chained with the same interaction you receive from the modal submission
Can I ask for a suggestion then? Because I need 6.. how can I improve this to have 5 but cover all 6?
could you receive the user ID another way, like from a slash command parameter or user context menu?
i would imagine instead of one big modal, you could have a message containing a template embed and a select menu listing out each field the user can edit, one by one
What I did, was make the command grab the Userid. So now the command has to do it! But thank you, I might do the select menu some other time!!
with dpy? you'll need a discord.User or discord.Member object, then you can retrieve their .display_avatar.url and set it as the url for your embed thumbnail
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
did you sync the commands and restart your client? (i dont know if restarting the client does anything i just do it for goodluck)
using @app_commands.command deco makes it a slash command, but it doesnt add it to your tree, so even if you sync it wont appear, use @bot.tree.command(...) instead
after that, sync your tree by await bot.tree.sync()
read more about slash in dpy
general about app commands
app commands example
you don't added intents.message_content = True
Slash commands doesn't require it
app_commands.command() is for cogs, @bot.tree.command() is for main files
reactions = giveaway_message.reactions
# Initialize a list to store participants
participants = []
# Iterate over each reaction and get the users who reacted
for reaction in reactions:
async for user in await reaction.users().flatten():
# Exclude bot users
if user != self.bot.user:
participants.append(user)
# Ensure participants are unique
participants = list(set(participants))
print("Participants:", participants)
i cant pickup any participants
and i have no idea why, neither does gpt
it's normal for GPT to not know discord.py, dw. It's shit at it
one of the problesm is this:
https://discordpy.readthedocs.io/en/stable/migrating.html#moving-away-from-custom-asynciterator
flatten() isn't a thing. remove that (plus it doesn't make sense in that context anyway.)
yeah i didnt have that but gpt told me lol
# Exclude bot users
if user != self.bot.user:
this looks like it only exclude the bot itself. do if not user.bot:
You should NOT expect GPT to know discord.py
never trust gpt on something you don't know
IDK IT WORKED FINE PREVIOUSLY AnD ID FIX ANY SMALL ERRORS
small yeah. but still it can fix them awfully without you noticing
thing is, there's like 20 different discord.py forks and discord libraries, so since it doesn't know better, it mixes and matches knowledge that is either (1) decent or (2) outdated or (3) from a different library or (4) a bad code practice it picked up off someone else's shit code
i usually tell it im specifically using nextcord
An "I find what is the best word that goes after this one" algorithm doesn't really know what that means lol
So I have a lot of bots but I need one of my private meme bots to be converted to slash commands so it will work as a user app, can someone help convert it?
Pls
?
User installable apps are a new feature provided by Discord that allows you to use an applications global commands even if the application is not in the server. This also allows you to create commands that will work in DMs between users.
Support currently exists on a feature branch, but will be available on master soon and will officially release in version 2.4.
To install: pip install -U git+https://github.com/Rapptz/discord.py@feature/user_apps
See the bikeshedding post for the latest development information and to report bugs.
The following decorators have been added or changed to support this:
- app_commands.allowed_contexts
- app_commands.allowed_installs
- app_commands.guild_install
- app_commands.user_install
- app_commands.private_channel_only
- app_commands.dm_only
- app_commands.guild_only
Slash commands and context menus are supported.
By default, commands are installed to guilds only but permitted in any context for new commands.
ex.
@app_commands.command()
@app_commands.allowed_installs(guilds=True, users=True)
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
async def useable_anywhere(interaction: discord.Interaction):
await interaction.response.send_message("I can be used anywhere, and am installed to guilds and users.")
or
@app_commands.command()
@app_commands.allowed_installs(guilds=False, users=True)
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
async def useable_only_users(interaction: discord.Interaction):
await interaction.response.send_message("I am only be installed to users, but can be used anywhere.")
NOTE: The only information available when processing a command used by a user is what's available on the interaction itself. You will NOT receive any extra information that would normally be in cache (guild members, guild roles, etc.).
this gives you all the info you need @flat haven
so will it work with commands like !ping or !meme for example
no
slash commands are integrated with discord
prefix commands are just responding to certain messages
Okay thank you
class SellOrNo(discord.ui.View):
def __init__(self, card_name, card_number, card_value, user_id):
super().__init__()
with open("user_data.json", 'r') as f:
user_data = json.load(f)
user_cards = user_data[str(user_id)]["cards"]
selling_card = user_cards[card_number]
print("a")
user_rings = user_data[str(user_id)]["rings"]
self.card_name = card_name
self.card_value = card_value
self.card_number = selling_card
self.user_rings = user_rings
self.user_cards = user_cards
self.user_data = user_data
@discord.ui.button(label="Yes", style=discord.ButtonStyle.green)
async def yes(self, int: discord.Interaction, value):
self.user_cards.remove(self.card_number)
self.user_rings += self.card_value
with open("user_data.json", 'w') as f:
json.dump(self.user_data, f)
await int.response.send_message(f"Sold {self.card_name} [{self.card_number}] for {self.card_value} Rings!")
self.stop()
@discord.ui.button(label="No", style=discord.ButtonStyle.red)
async def no(self, int: discord.Interaction, value):
await int.response.send_message("Cancelled.")
self.stop()```
the print("a") statement doesn't print so that means there is something wrong with the line ` selling_card = user_cards[card_number]` as placing the print statement before that line successfully prints, but im not sure what the problem is
This is the command connected to it:
@bot.command(
name="sell"
)
async def sell(ctx, given_card):
user_id = ctx.message.author.id
with open("user_data.json", 'r') as f:
user_data = json.load(f)
with open("cards.json", 'r') as c:
cards = json.load(c)
if str(user_id) not in user_data:
user_data[str(user_id)] = {"cards": [], "rings": 1000}
user_cards = user_data[str(user_id)]["cards"]
for user_card in user_cards:
card_number = user_card["number"]
card_amount = user_card["amount"]
for card in cards:
if card["number"] == card_number:
card_number = card["number"]
card_name = card["name"]
card_value = card["value"]
if card_number == given_card:
embed = discord.Embed(title=f"Are you sure you want to sell *{card_name}*?", description=f"Selling one copy of *{card_name}* will return with {card_value} Rings.", color=0xFFC0CB)
embed.add_field(name="", value=f"Selling cards will permanently remove them from your inventory.")
print(card_name, card_number, card_value, user_id)
await ctx.channel.send(embed=embed, view=SellOrNo(card_name, card_number, card_value, user_id))
await SellOrNo().wait()```
well I need to learn / then
yes

they're not that hard
you just use interaction instead of ctx
oh really?
which comes with its quirks but it's still manageable
type hint is required
this time
from discord import app_commands, Interaction
# an example of a slash command
@app_commands.command(name = 'hello', description = 'Say hello!')
async def hello(self, interaction: Interaction):
await interaction.response.send_message("Hello!", ephemeral = True)```
Interesting, thank you. I will work on this
fr
i made a dictionary bot using user apps that i can use everywhere
trying to print user_cards[card_number] doesn't work either which means that is definitely the problem, but I can't seem to find what because printing user_cards and card_number individually works fine.
would I just delete
bot = commands.Bot(command_prefix='!', intents=intents)```
no??
thats the bot itself, i never said that π
it has the old prefix
slash commands are SEPARATE from prefix commands
Just change your command_prefix to / and you'll have your slash commands ||jk||
*slowly deletes paragraph*
you....
YOU....
YOU...
I'd like to know what it's called when a bot responds to a user with a private, dismissible message that only the user who interacted with the bot can see ?
What is it?
ephemeral
anyone know how to make discordbot website? i was thinking of using django or something like that but cant find any tutorials
Anyone have suggestions on how I could make this bug report system better and the respond system better?
Besides drop down, I plan on already doing that!
wdym by bot website?
guessing a website based on a bot.
Ban the reporter cuz nobody likes bugs π
Real
dashboard
django is for backend btw. you'll have to learn html, css and js for a decent frontend website
or you can use wordpress or something similar to construct a decent looking website
||squarespace ad incoming||
recommend not using wordpress
nothing wrong with it if you just want a nice frontend
nevermind shouldnt use wordpress for that
Thx
... almost like I said that 
yea but i want to show user servers and add db and all that
so i can have diffeent feutres and stuff]
gotta learn html css and js then
that it?
but how does bot show servers and that on website?
how does it get that?
thats to make said website
just start the webserver with your bot: ```py
async def bootup():
await bot.run('your_token')
await webserver.start()
webserver.bot = bot
that way you can call stuff on the bot like .guilds for a list of guilds (i think)
!d discord.ext.commands.Bot.guilds
property guilds```
The guilds that the connected client is a member of.
and how to link this to something like django?
how bout discord.ext.ipc?
what
just showed you
give the webserver class an attribute which is your bot
then you can run stuff related to your bot
like fetching the guilds it's in
so i can use it like api?
use it like you would in a normal bot
Do not do that.
Use a proper db
use an online db, which can have access on the website and on the bot
which then you can share data that way
Do not run a webserver with your bot, it will be using to much resources at once.
wheres the db info gonna come from
how bout using something like docker containers on a vps?
From a db?
You can use an ONLINE db, which both your bot and website use
Then boom, you have a connected db on both sides.
not really it's manageable you often do need a webserver running under your bot if you have integrations with say something like topgg which uses a webhook based system
If you are using a full on website, it will be to much, which can also lag your bot if its under the same process.
or any real time updates or triggers of sort
Which is why its not recommended
depends i don't think it would cause much lag if you run it as a seperate process
discord bots are pretty light
Nah it's fine, I run two webservers and it works pretty well
its mostly just network io
What does that mean?
yeah the webserver would still be under the bot you can either have it running in a thread or forked from your current bot process both of them count as under the same process
Idk bro, I truly don't recommend that
Β―_(γ)_/Β―
I don't get what "under the same process" is supposed to mean
If bot goes down, then website would be down too?
So i would recommend 2 servers for that
not the same
i was concerned more about the resources usage point regarding the webserver than the logistics of it
true not a full blown website but a few api endpoints or webhook triggers are fine
are there any tutorials on this?
running a webserver side by side your bot?
Stop relying on tutorials... you gotta learn it one way or another. Not to be rude, but tutorials teach you how to do it that way, if you learn yourself, you learn it your way.
how do i learn it then?
Reading, lots of readin
and just trying it out yourself
So in python, you are learning how to build discord bots, now if you are doing website, you would research how to do websites in a certain langugage
like you research discord bots, using their api docs
but in this case, you might not have api docs
you could either spin up your own server using something like aiohttp to manage routes (a bit of experience needed), as i said good for triggers and webhooks and utility endpoints
if u wanna make a full blown website you might wanna look into something like django or fastapi but this is pretty much a new framework with different architecture and modelling compared to a discord bot so its better of going into a new project
never heard fastapi before is it good?
You can research that, but someone saying its "good" is just an opinion
Its all preference
yeah fastapi is more to my liking or rather my go to new kid to the block, django on the other hand has a way larger ecosystem and community
as reject modders stated take a look at examples from docs of both frameworks and make your pick
^^
You can't rely on what others say, I could say PYCORD is the BEST wrapper for discord, then many others could state why its not.
You honestly just have to research and see what you like more. You can never just go off an opinion, well you can if you don't care, but personally I don't recommend that
why is the command not working
so like, i had look at fastapi
it seems good
i just dont understand how you could use it to log in user using discord and get their servers
Thats for a db to do
So for an example, on my website, I show Users, Servers and Channels. But for that to happen, I have a task loop for every 1 minute, which will grab that info inside of bot, then upload it to a db, then inside of the website, it grabs it from the db, then uploads that value every minute
Its not that hard, but thats one way to do it
Does their callback functions have the same names?
One message removed from a suspended account.
i want to use #1113
How do i install it?
you'll need to clone the feature branch in their repository and install it
if you already have Git installed, you should be able to do it in one line with: sh pip install git+https://github.com/TrapDrap/_nextcord@TrapDrap-nextcord-voice-recording (@ separates the repository url and branch name)
as with any development version, you might encounter bugs and find it difficult to get support or use it without looking at the source code
One message removed from a suspended account.
copy_global_to() won't remove your global commands, so you'll need to sync your global commands with an empty tree first
One message removed from a suspended account.
One message removed from a suspended account.
it mimics the slash command flow designed by discord where syncing is manually done via API requests, so if you want to gain a deeper understanding of it, you should also read the discord api documentation
https://discord.com/developers/docs/interactions/application-commands#registering-a-command
but anyway, i guess the easiest way is to write a second script so you don't have to remove the code for your commands: ```py
import discord, sys
from discord import app_commands
client = discord.Client(intents=discord.Intents.none())
tree = app_commands.CommandTree(client)
@client.event
async def setup_hook():
await tree.sync() # wipe global commands
sys.exit("Done syncing commands")
client.run(...)```
This is an older version
Installing collected packages: nextcord
Attempting uninstall: nextcord
Found existing installation: nextcord 2.6.0
Uninstalling nextcord-2.6.0:
Successfully uninstalled nextcord-2.6.0
Successfully installed nextcord-2.0.0rc429+ga00b3c6a```
Because now i get this error
File "c:\VSCode\Antonio-Beta\bot.py", line 26, in <module>
from discord.ext.ipc import Server, ClientPayload
File "C:\VSCode\Python\Lib\site-packages\discord\ext\ipc\__init__.py", line 13, in <module>
if discord.version_info.major < 2:
^^^^^^^^^^^^^^^^^^^^
AttributeError: module 'discord' has no attribute 'version_info'```
its not really an older version, it just appears that way because nextcord uses some dynamic versioning plugin and trapdrap's repo doesn't contain the most recent tag, v3.0.0a, from the upstream repo
plus, nextcord is removing the discord package
Okay but i used it in nextcord 2.6
right, a version where they still had that proxy package to help ease migration
I quess the error is here
from discord.ext.ipc import Server, ClientPayload
you can tell in the github that its no longer there in the development (master) version
in other words, nextcord 3.0 won't be compatible with discord-ext-ipc
Okay mhh i need this
For this part
@Server.route()
async def guild_count(self, _):
return str(len(self.guilds))
@Server.route()
async def bot_guilds(self, _):
guild_ids = [str(guild.id) for guild in self.guilds]
return {"data": guild_ids}
@Server.route()
async def guild_stats(self, data: ClientPayload):
guild = self.get_guild(data.guild_id)
if not guild:
return {
"member_count": "Unbekannt",
"name": "Unbekannt"
}
return {
"member_count": guild.member_count,
"name": guild.name,
}
async def on_ipc_error(self, endpoint: str, exc: Exception) -> None:
raise exc ```
btw discord-ext-ipc's development ceased 3 years ago now
And now, is it replacible?
dunno, i havent looked for a successor to it
the only alternative im aware of is rolling your own IPC with websockets, fastapi or whatever
discord-ext-ipc in particular seems to use aiohttp's web server if you want to try replicating its design
https://github.com/Ext-Creators/discord-ext-ipc/blob/main/discord/ext/ipc/server.py
Does someone know why when I sync to guild it duplicates the commands I have??
one set is for global, one set is for the guild
^
Okay, that is confusing lol
tbf their examples don't really explain it either
Thereβs examples? Iβm on the docs but it only says βcopies all global commands to the specified guildβ
yes it copies to the guild. it doesnt remove them from globally
think of it as ```py
commands = [...]
guild_commands = commands.copy()
in the UI
show(guild_commands + commands)```
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
bot.tree.sync() only syncs global commands
the guild= argument you had earlier is still needed
One message removed from a suspended account.
^ so now you have to "un-sync" your global commands
One message removed from a suspended account.
there's an example there
elif scope == "guild":
context.bot.tree.copy_global_to(guild = context.guild)
await context.bot.tree.sync(guild = context.guild)
embed = discord.Embed(
description = "Slash commands have been synchronized in this guild.",
color = Color.FELIX
)
await context.send(embed = embed)
just logged into my pi and i already have copy_global_to lol
ohh wait
One message removed from a suspended account.
er no, they require two separate API requests
one request to sync global commands, another one to sync guild commands
dont sync on on_ready
sync in a command
One message removed from a suspended account.
for a full expo, read this:
that would sync both yes, but the issue is that copy_global_to() hasn't deleted your global commands, it's only copied them to your guild, so syncing your global commands would still restore the same commands you had globally
this was probably overkill, my bad
thats why i suggested writing a second script that doesn't have any commands, so you can just run that to remove your global commands
One message removed from a suspended account.
mmm yes my discord.py tag being sent here, where ?tag isn't a thing
this dpy tag is a bit overkill about it; the ratelimit as i last checked was ~2/30s, and updates to existing commands won't count towards the global 200 commands per day/guild limit
not saying it isnt a bad practice, just that there are usually bigger concerns to discuss
and fwiw anecdotally, i haven't noticed commands breaking after a re-sync, mainly i see it when there's a new command
One message removed from a suspended account.
One message removed from a suspended account.
await bot.tree.sync()```
leonardo the goat
I've experienced that countless times before, hence me adding it to the tag. 
One message removed from a suspended account.
ah, thanks discord
yeah. It sure is a wonky platform
the @bot.command decorator needs parentheses at the end, ()
I'm still struggling with this, plz help
One message removed from a suspended account.
have you made a separate script to un-sync your global commands?
One message removed from a suspended account.
wait, this whole time are you telling me i couldve just ran my unsync command π
One message removed from a suspended account.
did you use commands.Bot? if so it already comes with a CommandTree that you can use instead of manually creating one
umm so i did a mixture of my sync commands and unsync comands and now no commands are showing at all..
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
there are no other slash commands in that file right? if so, you can run it and it should remove your global commands
One message removed from a suspended account.
separate
the point is to not have any commands registered in your tree so the next time you sync it, dpy tells discord that your bot has no global commands
afterwards you can run your bot with just the slash commands synced to your guild
One message removed from a suspended account.
One message removed from a suspended account.
π
er, i guess restart your bot and only sync to one place now (global/guild)
One message removed from a suspended account.
the official docs definitely still lack a full guide for getting people introduced to the library and how the discord API works (although there is a PR for it)
One message removed from a suspended account.
One message removed from a suspended account.
they're kind of the best places to learn libraries (usually)
this third party guide might help:
https://fallendeity.github.io/discord.py-masterclass/slash-commands/
see also API reference when necessary
https://discordpy.readthedocs.io/en/stable/interactions/api.html#decorators
One message removed from a suspended account.
you can add one either by writing it in your command docstring, or applying the describe() decorator
the latter's easier to understand so ill just show that: py @bot.tree.command(name="echo", description="Echoes a message.") @app_commands.describe(message="The message to echo.") async def echo(interaction: discord.Interaction, message: str) -> None: await interaction.response.send_message(message)
see also this part of the guide where i copied that example from
https://fallendeity.github.io/discord.py-masterclass/slash-commands/#creating-a-slash-command
One message removed from a suspended account.
One message removed from a suspended account.
yes
generally any changes you make to how a slash command's appearance on discord needs to be synced
(otherwise, how does discord know that you changed something?)
One message removed from a suspended account.
One message removed from a suspended account.
ergh, maybe discord's broke again
try ctrl+r to reload your client and see if that fixes it
One message removed from a suspended account.
One message removed from a suspended account.
did you save your file and restart your bot before syncing?
One message removed from a suspended account.
synced your guild commands, right
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
the separate script was just to get rid of the global commands, your main file where you have your subscribe command should be the one doing .copy_global_to() and .sync(guild=...)
One message removed from a suspended account.
@commands.command()
@commands.guild_only()
@commands.is_owner()
async def sync(self, ctx: commands.Context):
"""
Syncs all the commands to discord.
**Usage:** sync
"""
# Try to sync the commands
try:
synced_global = await ctx.bot.tree.sync()
sub_commands_count = len([subcommand.name for subcommand in self.bot.walk_commands() if subcommand.parent])
embed = discord.Embed(
title="Synchronization Complete",
description=f"Synced {len(synced_global)} slash commands and {sub_commands_count} sub-commands globally.",
timestamp=discord.utils.utcnow(),
color=config.main_color
)
embed.set_footer(text=config.footer_text, icon_url=self.bot.user.avatar.url)
await ctx.send(embed=embed)
# If an error occurs then send the error
except Exception as e:
embed = discord.Embed(title='β ERROR',
description=f'**The error occured due to following reasons.\n``{e}``',
color=config.error_color)
embed.set_footer(text=config.footer_text, icon_url=self.bot.user.avatar.url)
await ctx.send(embed=embed)
raise e```
right, if you tried syncing your guild commands from your other script like in your screenshot, it has no commands so it's going to remove the existing guild commands
One message removed from a suspended account.
One message removed from a suspended account.
and it still has the copy_global_to() line?
One message removed from a suspended account.
One message removed from a suspended account.
ephemeral messages
my bad for the ping messages didnt update
@commands.command(name = "reload", description = "Reloads the bot's cogs.")
@commands.is_owner()
async def reload(self, context: Context) -> None:
"""
Realods the bot's cogs.
:param context: The command context.
"""
try:
for cog in context.bot.cogs:
await context.bot.reload_extension(cog)
embed = discord.Embed(
description = "Successfully reloaded all cogs.",
color = Color.FELIX
)
except Exception as e:
embed = discord.Embed(
description = f"There was an error trying to reload cogs, with reason(s)\n``{e}``",
color = Color.RED
)
await context.send(embed = embed)
apparently cog owner is not loaded, yet the cog this command is in IS the owner cog
never seen anyone write context instead of ctx
e
Extension 'owner' has not been loaded.
6]: In command 'setnick' defined in function 'Moderation.setnick'
6]: In parameter 'newNick'
6]: name: Command name is invalid
what on earth.
@commands.hybrid_command(name = "setnick", description = "Changes your nickname.")
async def setnick(self, context: Context, *, newNick: str) -> None:
"""
Changes your nickname.
:param context: The hybrid command context.
"""
try:
await context.author.edit(nick = newNick)
embed = discord.Embed(
description = f"Nickname has been changed to `{newNick}` successfully!",
color = Color.FELIX
)
except Exception as e:
embed = discord.Embed(
description = f"There was an error trying to change nickname, with reason(s)\n``{e}``",
color = Color.RED
)
await context.send(embed = embed)
403 Forbidden (error code: 50013): Missing Permissions```
what
Ah, turns out the bot cant change the nickname of the server owner
But im still confused about this
since its a hybrid command i can still use like a normal command, so when i mention the bot and run the command is works fine??
@tasks.loop(hours=1)
async def daily_reset_task(self):
print("FUCKING RUNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN")
async with self.db.execute(
"SELECT user_id, last_daily_reset FROM users"
) as cursor:
users = await cursor.fetchall()
current_date = datetime.datetime.now(timezone).date()
for user_id, last_daily_reset in users:
# Check if it's the next day
if last_daily_reset:
last_daily_reset = datetime.datetime.strptime(last_daily_reset, "%Y-%m-%d").date()
else:
last_daily_reset = current_date
if last_daily_reset < current_date:
# Reset daily XP
await self.db.execute(
"UPDATE users SET daily_xp = 0, last_daily_reset = ? WHERE user_id = ?",
(str(current_date), user_id),
)
await self.db.commit()
@daily_reset_task.before_loop
async def before_daily_reset_task(self):
await self.bot.wait_until_ready()
It wont run the task...
Im trying to make that every day it will reset (its given the date in the database)
Lmao a lil rage insinde the code
There was an error trying to sync commands, with reason(s)
Failed to upload commands to Discord (HTTP status 400, error code 50035)
In command 'setnick' defined in function 'Moderation.setnick'
In parameter 'newNick'
name: Command name is invalid
Full error provided by except Exception
CHAT_INPUTcommand names and command option names must match the following regex^[-_\p{L}\p{N}\p{sc=Deva}\p{sc=Thai}]{1,32}$with the unicode flag set. If there is a lowercase variant of any letters used, you must use those.
in other words, capital letters in parameters aren't allowed, you should either rename the parameter itself, or use the rename() decorator to just change the name on discord's side:py @bot.tree.command(name="set-nick") @app_commands.rename(newNick="new-nick") async def set_nick(interaction, newNick): ...
I see, thank you very much
how do i hide admin slash commands
like if a person doesnt have permission to use it they cant see it when they do /
!d discord.app_commands.default_permissions
@discord.app_commands.default_permissions(**perms)```
A decorator that sets the default permissions needed to execute this command.
When this decorator is used, by default users must have these permissions to execute the command. However, an administrator can change the permissions needed to execute this command using the official client. Therefore, this only serves as a hint.
Setting an empty permissions field, including via calling this with no arguments, will disallow anyone except server administrators from using the command in a guild.
This is sent to Discord server side, and is not a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check). Therefore, error handlers are not called.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
you can specify the default required permissions, but the server admin has final say over which roles/channels/members can bypass that requirement in the integrations tab
also not sure if that decorator alone precludes it from being usable in DMs, but you can apply @app_commands.guild_only() just in case
I hate that you can either choose between having properly established permissions, OR properly organized commands w/ sub-commands... I wish Discord would expand their system to include support for sub-command permissions.
I have a question, so you know how modals have the note at the top, can you make a custom note for certain arguments?
But not a note to replace that one, but a different note or something?
or is textinput the only thing allowed?
ya
apparently the api docs shows a value field that can be pre-filled, but im not sure if dpy supports it
oh, it corresponds to default= it seems
i guess it can substitute for a note...
arent there placeholders for that?
ye, those fit up to 100 characters
I see
that seems like an odd method
Thank you.. was wanting like a note but I have an idea on what I can do lol
How is that odd? The bot and website both have access to the db.
yeah but why not use discord.ext.ipc with Server and have it be like an api
That's how most bot owners would do it.
where you request the guilds and stuff
@Server.route()
async def guild_count(self, _):
return str(len(self.guilds))
Because I rather just use a db tbh.
The bot gets the guilds users n stuff from dpy, then it commits to a db, then the website can grab it from the db
Get a vps.
serving an API gateway on the bot and a separate webserver would be appropriate for real-time communication, but i guess most things don't need to be in real time
You can get a vps for around $3
free?
Bruh it's of no use
How to get the replit hosting link for hosting in uptime robot
Yes, but the issue with that, is if the bot goes down, or the api, then the website can't show any numbers, which will cause more errors, if the bot doesn't update the db, it will still have some type of numbers ya know?
thats just caching then
Replit is not a host.
Sorry i mistyped
Idk. I think of it as a better way for me personally, most will disagree but that's just my opinion
Your reason is more logical. But for me, mines just better for me.
Is there a seperate server for discord.py?
Yes
Dm me link then
Oh also @hushed galleon, since we are on this topic, for making a dashboard would the way I do it be reasonable or would you recommend doing an api way yall are talking abt, because we are making a dashboard soon and I kinda want good tips ig?
aight so what is the best way to learn fastapi? do i just watch tutorials or do what was suggested a little while ago which is to read the documentation and somehow understand it?
with my current knowledge id much rather prefer one database too, but i havent explored web development enough
You can do both.
They are gonna tell you the same thing btw, if not more toxic. Dpy is a very toxic place for new people or people who ask abt replit.
Oh bruh
i'd start with lots of simple apps and work up in complexity, that helps you reinforce your understanding of the fundamentals
So no way for me to get into py eh? π
I never said that now! You can always learn py, just don't use replit to host your py projects
I'm in mobile bruh
aight thanks, will give it a go
I have no clue then bro
Lol
ive written a few scripts in termux, but typing on a tiny touchscreen sucks
^^
Is it good?
I also have a tablet not an issue there...
over an actual keyboard and IDE heck no, but as for using python, termux (from FDroid) offers a decent linux environment
hosting a discord bot merely requires maintaining a client connection to discord
you don't need to serve it on a public IP address/domain
Oh (I'm new) so that means when I run the code it will work 24/7?
Your code will work 24/7 until a massive error happens that will end the process
Is pydroid good?
What's the error?
Never heard of pydroid. The ones I know are dpy, next cord and pycord
for as long as you still have an internet connection, it should, though ive had a few times where having my phone turn off would interrupt SFTP transfers... prob needed to whitelist termux from battery optimizations
It's a interpreter for android
It's an what if statement. Because if you have a big issue in your code, you could have a big error that will end the process if it's a bad error.
Oh
Oh mb.
So when I go offline can't I host it?
I forgot you were on phone!! That's my bad.
Np
Well do u have a pc?
Yes but no internet lol
In my city I am waiting for the big fibers to come then I will subscribe to plans for internet
Oh okayy
Speed here are very low 20-30mb/s
Yeah
I'm using mobile data now
Well, I could do something for you possibly
What?
But completely up to you, so i have a server where I can host discord bots, which I host like 8-9 already on there for others, if you want, I could do it for you too
For free, cuz I get the server for free myself lol
been living with that for a while π
Wth is this real
Nah I'm being serious π
Dm me bro π
It ends at the end of the year.. and I don't use it for anything else besides discord bots
Oh so your ok with hosting?
@vapid parcel dm maybe?
Yeah hold on
!d discord.Message.mentions docs
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
so load said extension
can anyone help me please
also please do not use int as a shortened version of interaction because you'll override the actual int() method
does it output any errors?
!tb
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
no errors...
show screenshots then
of the console?
all it does is print from the print statement at the end of the sell command
you need to await the function
await SellOrNo().wait()
?
no the load_extension
as its a coroutine
oh im not worried about that rn but thanks anyways
try printing out the type() of card_number
try printing the rest of the variables too
see if they have the data as u expect
alright but im confident they are correct
huh....
print(card_name.type(), card_number.type(), card_value.type(), user_id.type())
is this right?
im doing that but nothing is printing
I wonder why it still isn't raising an error, do u have an error handler?
can u send that?
wait
problem perhaps lies there
i dont have an error handler
oh
Consistency
no error handler in this command
do you have a general error handler?
Output: <class 'str'> <class 'str'> <class 'int'> <class 'int'>
just as it should be
other commands will throw errors
like if i miss a bracket its not like it wont tell me
I'm pretty sure the error is just being suppressed somewhere because u calling type() shouldve also raised an error
well yeah that's different, it's a syntax error
I'll try to look more if u wanna send the entire code to me in dms
something like, having an error handler -> handling a specific instance of an error but not raising the error if it's of another instance
626 files?
626 gb
what- π
jk 626 lines but the first half is just extra stuff
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
u can add different files here too
hmmm alright
upto you
just dont plagiarise my code
I won't π
as expected
what is it
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.channel.send(f"This command is on cooldown, retry in {error.retry_after:.2f}s")```
after this if statement, add
else:
raise error
what error did it raise?
here is the error:
Traceback (most recent call last):
File "C:\Users\iront\PycharmProjects\CBX\venv\lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\iront\PycharmProjects\CBX\main.py", line 603, in sell
await ctx.channel.send(embed=embed, view=SellOrNo(card_name, card_number, card_value, user_id))
File "C:\Users\iront\PycharmProjects\CBX\main.py", line 540, in init
print(user_cards[card_number])
TypeError: list indices must be integers or slices, not str
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\iront\PycharmProjects\CBX\venv\lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "C:\Users\iront\PycharmProjects\CBX\main.py", line 172, in on_command_error
raise error
File "C:\Users\iront\PycharmProjects\CBX\venv\lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\iront\PycharmProjects\CBX\venv\lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\iront\PycharmProjects\CBX\venv\lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: list indices must be integers or slices, not str
^ this is why i originally asked the question, but i guess i didnt explain why it mattered
yeah what confirmed it was an error handler was, the error not being rased when he called type() on an integer
sorry
card number is a str
as intended...
according to this
well u cant index a list with a string
well now you can enjoy debugging your code with error messages and tracebacks instead of guessing what's broken :)
at one point i thought it might have been this
but the thing is i dont know how to fix cuz
same, thats why i asked u to print the types
{"675798876858482731": {"cards": [{"number": "077", "amount": 1}, {"number": "021", "amount": 1}, {"number": "096", "amount": 1}, {"number": "066", "amount": 1}, {"number": "113", "amount": 1}, {"number": "112", "amount": 1}], "rings": 1000}```
can u print(card_number) and tell me what it is?
if its just a number inclosed in strings (always) then u can do int(card_number)
before indexing
card number is the 3 digit one
user_cards = user_data[str(user_id)]["cards"]
print(user_cards[card_number])
selling_card = user_cards[card_number]
user_rings = user_data[str(user_id)]["rings"]```
printing user_cards will give the list, but it wont know which like item in the string that the number its looking for is in
this hurts my head
remember that lists can only be indexed starting from 0, 1, 2, ... but dictionaries can be indexed by each key it has - if you want to be able to index by card number, the card numbers need to be keys in a dictionary rather than a list
ik what ur saying is to do like
user_cards[integer]["card_number"]
but idk how to get that integer unless it makes some loop to run through all the items in user_cards and see if number is equal to the given number and if it is then assign that value to the variable but idk how to do that
so will that allow it to directly get card_number from user_cards?
yes
user_id should have the children cards and rings
and for every card in cards, it should have children number and amount
right... so how can i rewrite the json so that i can change it
i guess you can write a little migration script to read the file, replace the lists with dictionaries, and write it back
afterwards make sure your bot is storing dictionaries instead of lists
ok first of all how do i change the dictionary to look better cuz rn it all in one line
use json.dump(..., indent=4)
headache
{"675798876858482731": {"cards": {{"number": "077", "amount": 1}, {"number": "021", "amount": 1}, {"number": "096", "amount": 1}, {"number": "066", "amount": 1}, {"number": "113", "amount": 1}, {"number": "112", "amount": 1}}, "rings": 1000}, "590190033495916595": {"cards": {{"number": "044", "amount": 1}, {"number": "071", "amount": 1}, {"number": "085", "amount": 1}, {"number": "014", "amount": 1}, {"number": "125", "amount": 1}, {"number": "092", "amount": 1}}, "rings": 1000}, "696309271524147251": {"cards": {{"number": "034", "amount": 1}, {"number": "057", "amount": 1}, {"number": "012", "amount": 1}, {"number": "123", "amount": 1}, {"number": "038", "amount": 1}, {"number": "106", "amount": 1}, {"number": "130", "amount": 1}}, "rings": 1000}}
i tried to change it myself by changing all the []s to {}s
but it didnt work
"675798876858482731": {
"cards": [
{
"number": "077",
"amount": 1
},
{
"number": "021",
"amount": 1
},
{
"number": "096",
"amount": 1
},
{
"number": "066",
"amount": 1
},
{
"number": "113",
"amount": 1
},
{
"number": "112",
"amount": 1
}
],
"rings": 1000
},
"590190033495916595": {
"cards": [
{
"number": "044",
"amount": 1
},
{
"number": "071",
"amount": 1
},
{
"number": "085",
"amount": 1
},
{
"number": "014",
"amount": 1
},
{
"number": "125",
"amount": 1
},
{
"number": "092",
"amount": 1
}
],
"rings": 1000
},
"696309271524147251": {
"cards": [
{
"number": "034",
"amount": 1
},
{
"number": "057",
"amount": 1
},
{
"number": "012",
"amount": 1
},
{
"number": "123",
"amount": 1
},
{
"number": "038",
"amount": 1
},
{
"number": "106",
"amount": 1
},
{
"number": "130",
"amount": 1
}
],
"rings": 1000
}
}```
this the original
side quest for your project which i highly recommend is to use an actual db instead of json. it'll be easier to navigate in the future, but for now, stick to the JSON doc
an actual database?
id rather make all the changes now rather than have to in the future for ease, how do you mean by actual database?
have you heard of sql?
uhhhh in cs class yeah but i dont really get it
https://sqlbolt.com for learning it
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
it's not really that difficult to get the basics and I have a gist on it (self promo β¨)
also i think you should manually search for X card while keeping that structure
@hushed galleon which of these is a good idea? py card = cards[cards.index({'number': '007', 'amount': 1}}] py card = [card for card in cards if card['number'] == '007'][0]
also look into SQLite since its a file-based sql database, and you can read syntax diagrams in their docs to learn SQL too
https://sqlite.org/lang_select.html
https://sqlite.org/lang_createtable.html
i have one more json file which hsa the information for all the cards, do you recommend to change that to sql too?
learn sql first before migrating
indeed
currently there are 150 cards and 1200 lines so im imagining its gonna get quite big quite fast since im producing cards fairly quickly
also an advantage of .sql files is that instead of your multiple JSON files, you can have 1 sql file with multiple what are called "tables"
the tables look like excel spreadsheets when you look at them
so you can have a table for cards, a table for inventory, etc
if you do end up using sqlite, download this β‘οΈ https://sqlitebrowser.org
the first assumes you have complete knowledge of the row, the latter lacks short-circuiting
i'd write a function for this and do it the simple way, e.g. py def find_card(user_cards, num): for card in user_cards: if card["number"] == num: return card
@glossy flame 
it can display the contents of your sql file in a more readable overview fashion
wow i wish i heard of this sooner
you might also be interested in sqlitestudio https://sqlitestudio.pl/
(ignore the capitalization inconsistencies in the table names)
sqlite browser far succeeds sqlite studio (it looks better imo)
this ruined my day, thank you 
is it gonna take long to finish the sqlbolt
i am stuck on lesson 2 (this is gonna take ages)
i think sqlbolt lacks exercises for the other side of SQL, which is knowing how to model data with tables
you need to practise it on something practical, like storing custom guild prefixes or tracking wins/losses in a minigame
damn it what i got wrong was that semicolon nonsense
so you always put the semicolon at the end of the qury
which ill have to do if i switch from json to sql anyways
i have idea
for now, ill use json and in the meantime ill learn sql, then practice on something like tracking wins/losses then when im ready ill switch
but i still want to get this sell function to work...
whats the issue rn?
Using the for loop, it sends the embed and it knows the card but after sending the embed it will say this:
Traceback (most recent call last):
File "C:\Users\iront\PycharmProjects\CBX\venv\lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "C:\Users\iront\PycharmProjects\CBX\main.py", line 172, in on_command_error
raise error
File "C:\Users\iront\PycharmProjects\CBX\venv\lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\iront\PycharmProjects\CBX\venv\lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\iront\PycharmProjects\CBX\venv\lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: SellOrNo.init() missing 4 required positional arguments: 'card_name', 'card_number', 'card_value', and 'user_id'
it says its missing the 4 arguments, but the arguments were given and it had to have been or else the embed wouldnt have sent containing information OF the given arguments
Error handling request
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/aiohttp/web_protocol.py", line 350, in data_received
messages, upgraded, tail = self._request_parser.feed_data(data)
File "aiohttp/_http_parser.pyx", line 557, in aiohttp._http_parser.HttpParser.feed_data
aiohttp.http_exceptions.BadStatusLine: 400, message:
Invalid method encountered:
b'\x03'
^
Error handling request
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/aiohttp/web_protocol.py", line 350, in data_received
messages, upgraded, tail = self._request_parser.feed_data(data)
File "aiohttp/_http_parser.pyx", line 557, in aiohttp._http_parser.HttpParser.feed_data
aiohttp.http_exceptions.BadStatusLine: 400, message:
Invalid method encountered:
b'\x16\x03\x01'
^
Error handling request
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/aiohttp/web_protocol.py", line 350, in data_received
messages, upgraded, tail = self._request_parser.feed_data(data)
File "aiohttp/_http_parser.pyx", line 557, in aiohttp._http_parser.HttpParser.feed_data
aiohttp.http_exceptions.BadStatusLine: 400, message:
Invalid method encountered:
b'\x16\x03\x01'```
what are these errors and how do i fix
Try updating dpy
pip install -U discord.py
im using disnake (latest ver)
who
wheres the section of code that raises this error?
so pip install disnake (although you should definitely use dpy instead, you get upfront updates like user apps)
i doubt nextcord, pycord, disnake, etc has user app support
might be wrong 
im on latest version already, also i switched to disnake back when dpy was abandoned and now im too lazy to switch back lol
i dont need it anyways so its fine
the API's in preview after all, it'd be annoying to release it only for discord to make a breaking API change and cause all libraries to bump a major version
Seems like a library issue then
how are you so sure its from disnake?
im not sure but it has to be in either here:
class SellOrNo(discord.ui.View):
def __init__(self, card_name, card_number, card_value, user_id):
super().__init__()
with open("user_data.json", 'r') as f:
user_data = json.load(f)
user_cards = user_data[str(user_id)]["cards"]
for card in user_cards:
if card["number"] == card_number:
selling_card = card
user_rings = user_data[str(user_id)]["rings"]
self.card_name = card_name
self.card_value = card_value
self.card_number = selling_card
self.user_rings = user_rings
self.user_cards = user_cards
self.user_data = user_data
@discord.ui.button(label="Yes", style=discord.ButtonStyle.green)
async def yes(self, interaction: discord.Interaction, value):
self.user_cards.remove(self.card_number)
self.user_rings += self.card_value
with open("user_data.json", 'w') as f:
json.dump(self.user_data, f)
await interaction.response.send_message(f"Sold {self.card_name} [{self.card_number}] for {self.card_value} Rings!")
self.stop()
@discord.ui.button(label="No", style=discord.ButtonStyle.red)
async def no(self, interaction: discord.Interaction, value):
await interaction.response.send_message("Cancelled.")
self.stop()```
or here:
@bot.command(
name="sell"
)
async def sell(ctx, given_card):
user_id = ctx.message.author.id
with open("user_data.json", 'r') as f:
user_data = json.load(f)
with open("cards.json", 'r') as c:
cards = json.load(c)
if str(user_id) not in user_data:
user_data[str(user_id)] = {"cards": [], "rings": 1000}
user_cards = user_data[str(user_id)]["cards"]
for user_card in user_cards:
card_number = user_card["number"]
card_amount = user_card["amount"]
for card in cards:
if card["number"] == card_number:
card_number = card["number"]
card_name = card["name"]
card_value = card["value"]
if card_number == given_card:
embed = discord.Embed(title=f"Are you sure you want to sell *{card_name}*?", description=f"Selling one copy of *{card_name}* will return with {card_value} Rings.", color=0xFFC0CB)
embed.add_field(name="", value=f"Selling cards will permanently remove them from your inventory.")
print(type(card_name), type(card_number), type(card_value), type(user_id))
await ctx.channel.send(embed=embed, view=SellOrNo(card_name, card_number, card_value, user_id))
await SellOrNo().wait()```
the lower half of that traceback comes from CommandInvokeError, it's not as important as the upper half that should have shown the exact line where the TypeError occurred
but regardless the last line there, await SellOrNo().wait(), is probably where it occurred
you're also using 2 instances of SellOrNo
thats your issue
the second instance is missing the arguments
it doesnt look like you need to wait on it, but either way, you need the same view instance that you created and passed to send(view=) in order to wait on it
no it should be 1 instance anyway
yeah
for example: py view = SellOrNo(...) await ctx.send(..., view=view) await view.wait()

right...
run this code if you want to know why ```py
class Example:
def init(self):
self.val = 5
a = Example()
a.val = 6
b = Example()
print(a.val)
print(b.val)```
(in a test file)
thank you, but i think there is a logic error as the card has been removed but my rings value in the json didnt increase by the same amount of the cards value
and there is no error
Cuz the traceback seems to point to that. You should really ask in the disnake server
pretty sure you copied the data instead of inheriting (idk if thats the word) from it
try replacing this py class Example: def __init__(self): user_rings = ... self.user_rings = user_rings
with this instead py class Example: def __init__(self): self.user_rings = ...
what you're doing is copying the value from the data and then changing the copy instead of making edits on the original
ohhh right i get it
hm... it didnt work
def __init__(self, card_name, card_number, card_value, user_id):
super().__init__()
with open("user_data.json", 'r') as f:
user_data = json.load(f)
user_cards = user_data[str(user_id)]["cards"]
for card in user_cards:
if card["number"] == card_number:
selling_card = card
self.card_name = card_name
self.card_value = card_value
self.card_number = selling_card
self.user_rings = user_data[str(user_id)]["rings"]
self.user_cards = user_cards
self.user_data = user_data```
Uh... Could you point out where? I might be blind but all I see is it originates from aiohttp
userid = interaction.user.id
email = self.inputemail.value
data = read_json("users")
for user in data['users']:
if user['id'] == userid:
user['email'] = email
self.email_set_event.set()
self.stop()
return
else:
await interaction.response.send_message("User not found", ephemeral=True)
return
async def on_cancel(self, interaction: discord.Interaction):
await interaction.response.send_message("Cancelled", ephemeral=True)
return```
how do i close out of the modal after self.stop()
what do you mean
after i submit it and it does self.stop() it doesnt close out of the modal
it keeps it open
yk how to do it?
on_submit() is only called when you close out of the modal
or submit it
afaik just close out of the modal yourself. it'll block your screen and prevent you from using the app so users will instinctively want to click out
alright thanks
@viscid hornet yo I got a question, where/ if you do/ do you host like discord bots
for free, cuz I am trying to figure out a way to host my bot on some server for free, I found 1 website but my bot doesnt work onit and so I am here asking you for rec
pay for a vps, borrow someone's computer or run it in the background on your own pc
is there no good server host bru
there are but they have drawbacks
what is that
@viscid hornet is it possible to keep editing messages?
how so?
like let me send u my code because im keep getting like discord.errors.InteractionResponded: This interaction has already been responded to before
inputemail = discord.ui.TextInput(style=discord.TextStyle.short, required=True, label="Email Address", placeholder='Enter your email address', min_length=1, max_length=100)
email_set_event = asyncio.Event()
async def on_submit(self, interaction: discord.Interaction):
userid = interaction.user.id
email = self.inputemail.value
data = read_json("users")
for user in data['users']:
if user['id'] == userid:
user['email'] = email
write_json(data, "users")
await interaction.response.defer()
embed = discord.Embed(title="Email Set", description="Email set successfully", color=discord.Color.green())
await interaction.edit_original_response(embed=embed, view=None)
self.email_set_event.set()
self.stop()
else:
await interaction.response.send_message("User not found", ephemeral=True)
return
async def on_cancel(self, interaction: discord.Interaction):
await interaction.response.send_message("Cancelled", ephemeral=True)
return
@app_commands.command(name="buy", description="Buy gifting credits")
async def buy(self, interaction: discord.Interaction):
class PaymentMethodSelect(discord.ui.Select):
def __init__(self):
super().__init__(
placeholder="Payment Method",
min_values=1,
max_values=1,
options=[
discord.SelectOption(label="Test"),
],)
async def callback(self, interaction: discord.Interaction):
selected_method = self.values[0]
if selected_method == "Test":
if not check_email(interaction.user.id):
await interaction.response.send_modal(SetEmail())
await SetEmail.email_set_event.wait()
embed = discord.Embed(title="Test", description="Click the button below to pay with Test", color=discord.Color.dark_theme())
await interaction.response.edit_message(embed=embed, view=None)
return
class PaymentMethodView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.add_item(PaymentMethodSelect())
embed = discord.Embed(title="Payment Method", description="Select a payment method", color=discord.Color.dark_theme())
await interaction.response.send_message(embed=embed, view=PaymentMethodView())```
@viscid hornet so like when i have a email in the json it shows embed = discord.Embed(title="Test", description="Click the button below to pay with Test", color=discord.Color.dark_theme()) which i want and when i dont have a email in, it shows the modal and when i put it in it returns embed = discord.Embed(title="Email Set", description="Email set successfully", color=discord.Color.green()) and i want it to edit the message also to show the Click the button below to pay with Test but i keep getting discord.errors.InteractionResponded: This interaction has already been responded to before
you want .followup. instead of .response.
on all of them?
everything after the first .response.
alright im try it and let you know who it goes.

how do u update a deferred message? i want to send file
you edit the original message (aka the deferred response), the way to do that depends on the library that you are using
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit) in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
@viscid hornet i keep getting this discord.errors.InteractionResponded: This interaction has already been responded to before
here im send the updated code
class SetEmail(discord.ui.Modal, title='Set Email'):
inputemail = discord.ui.TextInput(style=discord.TextStyle.short, required=True, label="Email Address", placeholder='Enter your email address', min_length=1, max_length=100)
email_set_event = asyncio.Event()
async def on_submit(self, interaction: discord.Interaction):
userid = interaction.user.id
email = self.inputemail.value
data = read_json("users")
for user in data['users']:
if user['id'] == userid:
user['email'] = email
write_json(data, "users")
await interaction.response.defer()
embed = discord.Embed(title="Email Set", description="Email set successfully", color=discord.Color.green())
await interaction.followup.send(embed=embed, ephemeral=True)
self.email_set_event.set()
self.stop()
else:
await interaction.response.send_message("User not found", ephemeral=True)
return
async def on_cancel(self, interaction: discord.Interaction):
await interaction.response.send_message("Cancelled", ephemeral=True)
return
@app_commands.command(name="buy", description="Buy gifting credits")
async def buy(self, interaction: discord.Interaction):
class PaymentMethodSelect(discord.ui.Select):
def __init__(self):
super().__init__(
placeholder="Payment Method",
min_values=1,
max_values=1,
options=[
discord.SelectOption(label="Test")
],)
async def callback(self, interaction: discord.Interaction):
selected_method = self.values[0]
if selected_method == "Test":
if not check_email(interaction.user.id):
await interaction.response.send_modal(SetEmail())
await SetEmail.email_set_event.wait()
embed = discord.Embed(title="Test Payment", description="Click the button below to pay with Test", color=discord.Color.dark_theme())
await interaction.response.defer()
await interaction.followup.send(embed=embed, ephemeral=True)
return
class PaymentMethodView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.add_item(PaymentMethodSelect())
embed = discord.Embed(title="Payment Method", description="Select a payment method", color=discord.Color.dark_theme())
await interaction.response.send_message(embed=embed, view=PaymentMethodView())
what line
in the callback where it says await interaction.response.defer() await interaction.followup.send(embed=embed, ephemeral=True)
also you most definitely should not make nested classes
remove the defer line and tell me what it says
okay
okay it worked when there is no email and i set he email it return the embed and it said email set and returned also another embed with Test Payment
but when i do the command again and it click it with it email set i get discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
@viscid hornet
hm thats weird
try just await inter.resp.send()
without deferring
where do i put it in the modal or the callback
just replace the 2 lines with that line i showed you
okay
okay when it set the email it sent that but it didnt send the test payment and i got a error
discord.errors.InteractionResponded: This interaction has already been responded to before
.followup.send() then
when there is a email set in the json i get discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
ok just use inter.channel.send()
foolproof
okay let me try it
He could solve that refactoring a bit the code
could you send the full traceback?
like how?
Can I use the wait_for() inside of a Cog?? Because this is giving me an error:
import discord
from discord.ext import commands
from discord import app_commands
class Avatar(commands.Cog):
def __int__(self, bot) -> None:
self.bot = bot
@commands.Cog.listener()
async def on_member_join(self, member: discord.Member) -> None:
await member.send(f"Welcome, write your name")
name = await self.bot.wait_for('message', check = lambda message: message.author == member and message.channel == member.dm_channel)
ERROR - discord.client : Ignoring exception in on_member_join
Traceback (most recent call last):
File "/home/codespace/.python/current/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/workspaces/AdeptusStudio-PyBot/cogs/comunity/avatar.py", line 13, in on_member_join
name = await self.bot.wait_for('message', check = lambda message: message.author == member and message.channel == member.dm_channel)
AttributeError: 'Avatar' object has no attribute 'bot'
anyone recommend any hosting sites
https://paste.pythondiscord.com/AYVQ no errors and no prints pls help
your computer
also pro tip, use ? for your placeholders instead of f-strings because they're susceptible to sql injection
your reason is also already a string so you don't have to do f"{...}"
also have you considered that it might have actually worked?
is there an update in the database?