#discord-bots
1 messages · Page 367 of 1
ok thats it
You colonizer 🗣️
yeah mate my computer can vote 😭🙏🏽

its alright lol no worries : )
you guys enjoy : ))
you too 👋🏽
hihi, im new here and i want to learn python but i dont know where to start. i taught myself LuaU (Roblox Studio) but i'm getting a bit bored of it and i wanna extend my knowledge. if anyone sees this message, how'd you learn python? maybe i could learn the way you did
!res
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
ooo let me see
i learnt mine in a shoddy way by learning it backwards
wdym?
well i wanted to get into coding by coding a discord bot since i used the platform quite frequently
but to learn a discord bot, you obviously have to know python
i didnt know python but i still carried on with the library
so the way you’re supposed to do it is:
learn python > learn the library > make a discord bot
i did:
make a discord bot > learn the library > learn python
@viscid hornet you are the best for help 
eh sorta
it was terribly inefficient and i would definitely do it another way
use the resources page — its very useful
gotcha, but yet, i don't know where to click on the resources page 😭 too many buttons
my stupid brain cant understand which button to click
focus on fundamentals first, then OOP, then concurrency, those are big concepts you need to learn and discord.py uses heavily
uhm
i don't understand😭
see this part https://gist.github.com/scragly/095b5278a354d46e86f02d643fc3d64b#essentials
Primitive data types until Argument definitions would be python fundamentals
these are also helpful to learn the basics to intermediate https://automatetheboringstuff.com/
what are python fundamentals though? i'm a complete beginner when it comes to python, sorry
Inshort learn everything of basic Python upto OOP concept
Any other language before?
Yeah, Lua on RobloxStudio, that's it
pretty much just the core of python, syntax, variables, control flow, etc
should be smooth sailing if you've already learnt other programming language
so it's like the basics?
yes
Check the before you begin part from this page
Pycord Guide is a complete guide for Pycord. Learn how to create Discord Bots today!
so those are the basics i should get to before learning discord.py?
okay i see
More better you understand language more easier for you to work with library (dpy)
Did I just read pycord
dpy is short for discord.py i suppose?
I didn't suggest library just gave them basic idea of what to learn before getting started
Yes
i see, i think i understand how to start now
so just learn the basics of python itself, then learn dpy
Yes
technically not just the basic, Object Oriented Programming (OOP) is a huge concept, i wouldn't call those basic
what is OOP?
OOP is something of intermediate level thing as per my opinion
Could be little overwhelming as a beginner but it's easy af once you understood everything properly

i see
i believe the tutorial i'm using will cover OOP, but if not, i'll just either search it up or ask here again
usually just ask in #1035199133436354600 for that
im tryna do this but with js and im already lost - you got anything i can use for it?
You learning JS?
Node?
probably?
Usually I just read https://learnxinyminutes.com/docs/javascript/ it has similar syntax anyways, only difference is a few quarks js have
idk i just booted up vscode, wrote a print(“hello world”) in js, cried when i found out about the syntax and then gave up
js syntax aint even bad
console.log("Hello world") you mean
yes, a print(“hello world”) in js
as in using the js language
ima have to stop you right there
life saver
wtf do you mean equality is ===
Ain't even that bad
😭😭
Teach me after you understand
I accept you as my Sensei
there's both == and === but this isnt the channel for it
mf if it aint that bad you learn it 😭
#ot0-psvm’s-eternal-disapproval - ima be there
similar to is and == in python
That doesn't type check
=== means if type and value both are similar
I see I guess I forgot about implicit cast js have
Js seems confusing 😭
Wtf you mean NaN or undefined just give me None
That's their equivalent
wb null
Ah, right
when i try to turn the bot on it says errno 2 and ill looked it up and i get it sorted
cant get it sorted*
need more details than that mate
well there you go
I have tried everything and cant get it working
!code
!traceback - this is the most important
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.
What do i type for that?
wdym?
What is that?
a traceback?
I just started learning, what is that?
it tells you more about your error
!traceback errno 2
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.
its an information embed
axo 
send us whats in your terminal
also are you doing this? py try: ... except Exception as e: print(e)
fuck you want now? 😭
you're trying to run a file that doesnt exist in that directory
are you in vscode?

yeah
use the play button at the top
you're in your user folder on the terminal
So that is what i need to put in?
intents = discord.Intents.default()
client = discord.Client(intents=intents)
are you using commands?
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
then you need to add the message content intent like so:
intents = discord.Intents.default()
intents.message_content = True
bot =commands.Bot(intents=intents)
discord.commands.Bot 😭
So do i remove where it says @client.command() with this?
wdym
you are a discord.commands.Bot
no, where you do client = commands.Bot
alright
no you are ray

ray skywalker
like that?
You still need to do bot.command() and bot.event accordingly.
and also pass the command_prefix like here ^
Intents just tells Discord what additional information that you want to receive.
@intents.command() is new - ive never seen that
?
client = commands.Bot(command_prefix="!", intents=intents) and remove the bot = ... line
|| (discord.commands.Bot also doesnt exist) ||
bot = ... line? where is that?
its because he has good intents 
no fucking way you have your own pastebin image service
he has good intent with his code
sorry this might sound dumb, but you are running your bot with bot.run right
but you have bad intents, you must be eliminated 
what if i do
piss off
frontend goes hard
it used to be just "Hello, World! (now in rust)" in plain text
fuck js man i forgot a semicolon
how does it work, it seems annoying to have to paste it there all the time, so im assuming it just takes ur clipboard and sends it there right?
what do yu mean? where my bot token is i am using client.run
okay cool

it's uploaded instantly when i take a screenshot
neat
at least with a specific program
gyat keeping?
its said this then i think tons of error
what are the errors?
send the errors
!traceback - show the terminal
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.
?
hes a little silly
my condolences
your token is in that
censors everything except token
please do reset it asap
done
yeah on top of it says that
that's fine
nvm
that's just info
enable your intents in the dev portal
also always send the full error, otherwise we cant help you
!code - and do it like this - very useful
noice 👍

how do i code my shi to do like, for every token tht it says doesn't have default pfp it puts in newtokens.txt
What do you mean by token
like my discord token but i have alot of alts, and i put tokens from all alts i got and it goes line by line in tokens.txt and it checks each token with discord public api and if avatar is default(i coded this part already) it should js continue to next token but if it's not default it pastes that token in newtokens.txt (didnt' code this idk how)
You should not be using user tokens in automation. That is very strictly against TOS
what's api for then 🤣
i am not using in bad purposes it's my tokens all
then js lemme format my question better
how do i code my shi to do like, for every apple tht it says has worm inside of it it puts in newtokens.txt if doesn't have worm then it continues to next apple in apples.txt
So you're just trying to obscure the fact you're violating TOS
nope
that's what i need to code
i am not aiming at tokens anymore i js wanna know how do i make code paste the value in .txt file in that directory
So in the last 2 minutes, you have decided you want to do the exact same thing but for an entirely different purpose
Disgustingly manipulative, we're not stupid
no mate i am telling you, i didn't ask because of the part which is against tos, i didn't know it and i am sorry i wont do it but i still have more projects that have same thing to do to fill the .txt file but idk how to code it to put in txt file
Automating your user account is completely forbidden by discord. Do not seek help for this project on this server again


Discord batman all over again
no way this is an emoji 😭
Great emoji isn't it
🤯
nuh uh
trendy with the kids i see, old man 👌
SHUTUTP im not that old
sorry grandpa

@viscid hornet ```py
import discord
from discord.ext import commands, tasks
from discord import app_commands
import os, mysql.connector, aiohttp, random, time, datetime
color_lace = discord.Color.from_rgb(60, 161, 224)
class Automeme(commands.Cog):
def init(self, bot):
self.bot = bot
self.database = mysql.connector.connect(host=os.getenv("MYSQL_HOST"), port=os.getenv("MYSQL_PORT"), user=os.getenv("MYSQL_USER"), password=os.getenv("MYSQL_PASSWORD"), database=os.getenv("MYSQL_DATABASE"))
time.sleep(1)
self.auto_meme.start()
@tasks.loop(minutes=1)
async def auto_meme(self):
try:
cursor = self.database.cursor()
cursor.execute("SELECT guild_id, channel_id FROM automeme")
results = cursor.fetchall()
for guild_id, channel_id in results:
guild = self.bot.get_guild(guild_id)
if guild:
channel = guild.get_channel(channel_id)
if channel:
webhooks = await channel.webhooks()
webhook = webhooks[0] if webhooks else await channel.create_webhook(name=self.bot.user.name)
async with aiohttp.ClientSession() as session:
async with session.get(f"https://reddit.apiwant.xyz/api/reddit/MemesESP") as response:
if response.status == 200:
data = await response.json()
post = data["data"]["post"]
meme_url = post["mediaURL"]
embed = discord.Embed(color=color_lace)
embed.set_image(url=meme_url)
embed.set_footer(text=f"{self.bot.user.name} | automeme | {datetime.datetime.now().strftime('%H:%M')}", icon_url=self.bot.user.avatar.url)
view = discord.ui.View()
view.add_item(discord.ui.Button(style=discord.ButtonStyle.secondary, label="Invítame", url=f"https://discord.com/api/oauth2/authorize?client_id={self.bot.user.id}&permissions=70368744177663&scope=bot+applications.commands"))
await webhook.send(embed=embed, view=view, username=self.bot.user.name, avatar_url=self.bot.user.avatar.url)
except Exception as e:
print(f"Error: {e}")``` recommendations?
nope
yes
alr
axo approves !?
im just sleep deprived i cba to read into it

medical malpractise
mods ban him
That's rule 11 @viscid hornet
Looks stealable
Medical malpractices prohibited
what?
!rule 11
:x: Invalid rule indices: 11
fanks for that
That's a secret rule

dont print your exceptions
never print your exceptions
What would he do?
Forward them on your mail?
let them be raised of course
Handling is better than raising?
either that or py import traceback msg = traceback.format_exc() await ctx.send(f"'''py\n{msg}\n'''")
theres a difference between handling and what hes doing
hes taking an exception and then doing nothing with it, other than stripping away literally everything to let him handle the exception manually

yeah thats valid because at least the traceback is outputted somewhere
piss
Dumb
🤫
Screenshoted
what
me sleep now
!e
value = "10"
try:
value = int(value)
except Exception as e:
print(e)
@latent pier :warning: Your 3.12 eval job has completed with return code 0.
[No output]
😂
!e
value = "ok"
try:
value = int(value)
except Exception as e:
print(e)
@latent pier :white_check_mark: Your 3.12 eval job has completed with return code 0.
invalid literal for int() with base 10: 'ok'

Half sleeping
Come to off topic
!e
value = "10"
try:
value = int(value)
except Exception as e:
print(e)
@slim bloom :warning: Your 3.12 eval job has completed with return code 0.
[No output]
!e
value = "x"
try:
value = int(value)
except Exception as e:
print(e)
@slim bloom :white_check_mark: Your 3.12 eval job has completed with return code 0.
invalid literal for int() with base 10: 'x'
Add print to it
!e
value = "10"
try:
value = int(value)
print(value, type(value))
except Exception as e:
print(e)
```
@latent pier :white_check_mark: Your 3.12 eval job has completed with return code 0.
10 <class 'int'>
What request can I do with OAuth2, to see what guilds my bot are in? This is for dashboard reasons.
You can see what guilds your bot is in without it
I am not using dpy
I am making a dashboard, aka not in python, which I would need to do OAuth2 to do it.
you can check users guilds if you have the guild scope but if you want to see the bots guild you would need to use your bot token and hit the normal api endpoints
few other ways are probably running a webserver along with your discord bot with endpoints to do what you want
well, I am trying to see if the bot is in the same guild as the guilds the user has on the dashboard, but if I use a database, it will make the dashboard slow. Which I tested. So I am trying to find a better way of doing it.
dont use a db, make a similar end point on your bot side which gives the list of guilds etc and then fetch it using a get request
How could I do that?
spawn a webserver on your bot side
Not really trying to do that tho.
you would need a common data point
- one is a database (and db access shared between bot and dashboard)
- webserver on bot side or seperately using the bot token to get crucial bot info
- using the bot token in your website side to get the data
Well, I will just do flask I guess..
is it possible to have a discord option autocomplete based of on another
Yes, you can check the Interaction.namespace
aight cool ty
I want a converter which takes discord.Member or ctx.message.reference.author or both as a argument if both are present there
.author is gonna be a discord.Member automatically. whats the converter for?
to take it as a argument in a command 🗣️
!d discord.Message.reference
The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.
New in version 1.5.
Should be easy
What do you need help with?
How so?
Ooh wait
It should take either one of them or both if both are given and it should be a required argument not optional
That's not really possible since converters aren't called for optional args
Yeah you'll have to do it in the command
Maybe write a helper function for it
@bot.command()
async def wave(ctx, to: discord.User = commands.parameter(default=lambda ctx: ctx.author)):
await ctx.send(f'Hello {to.mention} 👋')
I found this example somewhere close to what i want
I can do
ctx.message.reference.author if ctx.message.reference else ...
I was thinking default=lambda ctx: ctx.message.reference and ctx.message.reference.resolved and ctx.message.reference.resolved.author
What's resolved for?
MessageReference doesn't have an author attr
You need to get it from the message
.resolved returns the message if in cache
Edit: Correction, the api optionally returns it
MessageReference.cached_message is from dpy
Wait a minute
Yeah understood
How about we change it and remove default?
Like for example
.user id @lament depot
It should respond with yours and @lament depot's id
Get the replied message from ctx.message.reference... in the command
I tried 🤣
But the only problem is if i don't pass user with command it'll throw missing argument callback
Make it optional then
And if i put it to optional and there's no message reference, there's no way i can raise missing argument
member: discord.Member | None = None
Correct
You can send a message from the command instead
Yeah i guess that's the last option
Any reason you don't want the default thing?
It'll redirect to default when argument is not passed, right?
Yes
Yeah I think i should use this
There's these too btw
@bot.command()
async def bar(ctx, cool_value: SomeType = commands.parameter(converter=MyVeryCoolConverter)):
cool_value.foo # no error (hurray)
class SomeType:
foo: int
class MyVeryCoolConverter(commands.Converter[SomeType]):
... # implementation left as an exercise for the reader
@bot.command()
async def bar(ctx, cool_value: MyVeryCoolConverter):
cool_value.foo # type checker warns MyVeryCoolConverter has no value foo (uh-oh)
You can use typing.Annotated there
arg: Annotated[SomeType, MyConverter]
But using param for it is completely fine too
!code
!code @kick.error async def kick_error(ctx.error): if isintance(error, command.MissingPermissions): await ctx.send("You do not have permission to kick this person")
why is there a red line under the bracket? iv closed the bracket on the other side
Is there a way to log every time a command is used without having to do it manually for each command?
what type of commands afaik there are stuff like before_invoke for message commands and a global interaction_check for slash commands
how do i give the bot perm to kick?
i have given the bot administer but it still isnt working
https://discordpy.readthedocs.io/en/latest/api.html#interactions
on_interaction too
its kick_members not kick_member
yes
Slash commands.
then either of the ones i sent above
Ty
What is wrong with this code? cos there is a error and i cant find it
What's the error then?
nothing called avatar_url
mhm they should state the traceback 💀
whats a traceback
!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.
!traceback@client.command() async def embed(ctx): embed = discord.Embed(title="dog", url="https://www.google.co.uk", description="We love dogs!", color=0xE9BD19) embed.set_author(name=ctx.author.display_name, url="https://www.youtube.com/@ArmyforLyfe", icon_url=ctx.author.avatar_url) await ctx.send(embed=embed)
i just removed url and its working
its ctx.author.display_avatar
both works
avatar_url?
that i doubt
isnt that depreceated now?
yeah .avatar works but u would have None if there is no avatar
display_avatar would give u the default avatar in this case
Right
.avatar
.display_avatar
.default_avatar
.display_avatar = guild_avatar or .avatar or .default_avatar
may want to google the meaning of "deprecated" in software
how can i fix this? the brackets are red
it thinks the brackets werent closed but they are
check the code above
also hover over it, it will (sometimes) tell you exactly what's wrong
that is what it says
np
!d discord.User.banner
property banner```
Returns the user’s banner asset, if available.
New in version 2.0.
Note
This information is only available via [`Client.fetch_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.fetch_user).
make sure to read the note
Hello !
I get this error all the time, reinstalled py-cord, no other libraries
from discord.ui import TextInput
ImportError: cannot import name 'TextInput' from 'discord.ui'
!code
not sure but I think most people here use/help with discord.py.. you could try asking at https://discord.gg/pycord
how do i install os?
don`t work
Error: 'NoneType' object has no attribute 'url'```
banner user
embed.set_image(url=user.banner.url)```
^
the messge you replied had nothing to do with you
user = await self.bot.fetch_user(user.id)``` ?
also, you shouldn't assume that everyone has a banner set
???
fetch_user takes an user id
import discord
from discord.ext import commands
from discord import app_commands
color_lace = discord.Color.from_rgb(60, 161, 224)
class Banner(commands.Cog):
def __init__(self, bot):
self.bot = bot
@app_commands.command(name="banner", description="Muestra el banner de una persona")
@app_commands.describe(user="el usuario a mostrar")
async def banner(self, interaction: discord.Interaction, user: discord.Member = None):
try:
user = user or interaction.user
user = await self.bot.fetch_user(user.id)
embed = discord.Embed(color=color_lace)
embed.set_image(url=user.banner.url)
await interaction.response.send_message(embed=embed)
except Exception as e:
await interaction.response.send_message(f"Error: {e}", ephemeral=True)
async def setup(bot):
await bot.add_cog(Banner(bot))```
user have a banner
you should check whether user.banner isn't None
show
I think I already saw the error that was causing it to fail.
It's inbuilt

!d discord.User.avatar
property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset) for the avatar the user has.
If the user has not uploaded a global avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar).
good
How is this possible to display this on a users profile in a server?
This is done thorough oauth with a web server, but yeah
You can't say this stuff with a bot
who wants tohelp code a discord bot
Would it be possible to run flask in a cog..?
Don't know much abt flask, kinda why I am asking.
social credit > +1000 
you should add an execute command that doesn't let you execute more commands and adds your family to an unfinishable debt
for your punishment you shall be forced to write your next discord bot in rust
mods cook him
a little of javascript and thats it
So that cmd is not even connected to a db?
pls no
the hell are you talking about!
persistent storage so ur bot rmrs the social credit
Nope
!resources here ya go, im not sure if you've seen it
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
He did not.
🦾
Possible tho?
thread it i guess
i didnt have space
like how you used to run flask + bot on replit
I have it threaded, but would I be able to put it in a cog or nah?
i removed the last part
Uses json
tf is that
no clu
Bro...
brother..
I give up 😭🙏
sorry im new
its okay, we're all here to learn
indeed
!rule 10
oh uh
if you're really new to python and programming in general i think you should check out the resources link python sent
okay i guess
I truly recommend like
good luck!
everything looks to complicated!
is this site good too?
https://devdocs.io/python~3.12/
Python is literally the easiest language...
Never used it.
indeed however classes and objects are hard
I just recommend the 2 I sent. Because I am a visual learner and an interactive learner. So it's easier for me to learn from those 2 websites. But if you are better verbal, then do reading ig.
nahh, visual better for me
You think it's possible?
i say yes
But going off this, you don't.
cog hmmm, cog, cognitive old gland
i know, i was testing you
smh no rust
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
OFC
however my proposal was purely out of a hypothetical situation
you become the bank
hmm i wonder who 🤫
yeah here where i live you get like 40 to 60 k euro
!rule 10
per year
You are 1 and 0s
Bros way behind
bro uses internet explorer
yeah
Bros def on the first computer
what is rule 11?
i did just nw
i have important question about coding, what is the easiest and fastest language i can learn? programming wise
Nuh uh
Py
really?
Yes
its not like a ancient programming language made back in the 80s or something?
It's the easiest language out there...
@vapid parcel
i heard assembly is easy
Hi
I have a question: how would I organize the cogs of my bot well?
Hm, how are u loading them?
async def load_cogs():
for filename in os.listdir("src/cogs"):
if filename.endswith(".py"):
try:
await bot.load_extension(f"src.cogs.{filename[:-3]}")
print(Fore.LIGHTWHITE_EX + f"Cog valido: {filename[:-3]}")
except Exception as e:
print(Fore.LIGHTBLACK_EX + f"Cog error: {filename[:-3]}: {e}")```
Also, cogs should have more than just 1 commands, recommend making cogs a category, not a section
ok thx
bacon bacon bacon bacon
💀
Also that's good. But, you could just make more folders to organize if you want and go a little deeper inside if you want.
But seems good. I have 24 cogs. Which seems a lot imo but some are handlers for other cogs because I don't wanna make my other cogs messy
Friendly reminder that ide regions and control F exist

this is inappropriate, please don't post stuff like this
That trick is from Discord itself
doesnt matter
Ok, sorry 
How is the @discord.ext.tasks used in a Cog for a timer for example?
Got it ty
Hey, is Interaction required for this function?
async def autocomplete(self, interaction: discord.Interaction, current: str) -> List[Choice[str]]:
#Checks if the players list is populated. If not, populate it!
if not self.players:
self.players = await self.db.get_all_users_list()
#Populates the choices the user will be able to select from.
if current:
choicelist = []
for player in self.players:
if current.lower() in player.lower():
choicelist.append(player)
if len(choicelist) > 20:
break
return [Choice(name=c, value=c) for c in choicelist]
else: #Tells the users to start typing!
default = ["Start typing a players name (preferably their in game name)"]
return [Choice(name=d, value=d) for d in default]
I'm using discord choices, and this function will update the options based on what you type.
and I am unsure if I even need Interaction at all
🤔 maybe I do.
hhmm..
oh well. I'll leave this here and maybe a smart person can give me a solution or explain
or something :D
its a required parameter if you don't need it you can leave it unused
Unused it shall be.
I recommend index slicing the list to show max 25 items instead of breaking. Now it will still trigger the function but just not show anything, when slicing it, it won't go over the 25 limit and still show suggestions. Should still work been coding too much in js lol
I like it the way it is tbh
It also works.
and unless your way is faster, it's fine how it is
Don't fuck with shit that already works, ya know?
Yes indeed
Hey guys I am trying to make a gambling bot ( won't use irl money dw ) for my friends but I dont know how to import the code do I just run the python script and how do i get a discord bot token? Here is the code:
import discord
import random
client = discord.Client()
@client.event
async def on_ready():
print('Bot is ready')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!gamble'):
result = spin_slot_machine()
await message.channel.send(result)
def spin_slot_machine():
symbols = ['diamond', 'dirt']
spin_result = [random.choice(symbols) for _ in range(3)]
payout = calculate_payout(spin_result)
return f'Spin result: {" - ".join(spin_result)}\nPayout: {payout}'
def calculate_payout(spin_result):
if spin_result == ['diamond', 'diamond', 'diamond']:
# Adjust the odds as per your requirement (1/100)
if random.randint(1, 100) == 1:
return 'Jackpot! 2x payout'
if spin_result.count('diamond') == 2 and spin_result.count('dirt') == 1:
return 'No win'
return 'No win'
client.run('YOUR_TOKEN_HERE')
You get the bot's token from the discord developers portal (https://discord.com/developers/applications)
And yes you just run the python script
where can I ask for help with a problem with a telegram bot?
I'm trying to create a telegram bot for a game with some of my friends, not being an expert in Python I tried to do everything with chat and some tutorials but I'm still having problems
this is the code, the error it gives me now is
Traceback (most recent call last):
File "/home/ArgentAA/caccabot.py", line 2, in <module>
from telegram.ext import Updater, CommandHandler, Dispatcher
ImportError: cannot import name 'Dispatcher' from 'telegram.ext' (/home/ArgentAA/.local/lib/python3.10/site-packages/telegram/ext/init.py)
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
You can read this for a better understanding
https://fallendeity.github.io/discord.py-masterclass/
A hands-on guide to Discord.py
Thx and the code is good right?
@shrewd apex Are you planning to release a video series for this guide?
yeah
Ty
- the fact that videos are hard to keep up to date
They're also just a superior format for information that isn't visual. You can't control f a video
And anything made by a single individual, no matter how good they are, is subject to their own biases or gaps of knowledge
Yep, if you just want the code link a repo with a good readme for setup.
What could I improve or add?
It shows unloaded cogs if there is any but none were unloaded.
you could put the buttons in some better order

Embed has a limit?
no one can win roast battle against me 😎
:incoming_envelope: :ok_hand: applied timeout to @pastel isle until <t:1715874444:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
What commands should I make for a discord bot?
Find something you cannot do today on discord that you'd want to do, automate it
I really want to learn cogs so bad but I just don't understand discord py's documentation 😦
It's quite simple actually, what don't you understand
Yeahh you're probably right, I'm completely new though to be honest. Just looking for a place to start haha
I see, well good luck
where do I ask for help for apis?
if you're not using it, you can simply use async def autocomplete(self, _, current: str) -> List[Choice[str]]
wow, i was scrolled way up
Hello, I have a problem. I wrote this function and it works well, but the problem is:
Reactions are obtained, meaning 4 reactions, after which the function stops for a few seconds and then continues, which extends the duration of the function. Do you have any solution or another way to reach the same goal?
This function is intended to obtain the number of messages that a specific person interacted with via ID
async def get_unique_reacted_users_count(self, reports_channel: discord.TextChannel, start_date: datetime, end_date: datetime, player_id: str):
reacted_users_count = {}
async for message in reports_channel.history(limit=None, after=start_date, before=end_date, oldest_first=True):
if len(message.reactions) == 0:
continue
async for user in message.reactions[0].users():
print(f"User: {user.name} - ID: {user.id} - reaction: {message.reactions[0].emoji}")
user_id = str(user.id)
if user_id == player_id:
if user_id not in reacted_users_count:
reacted_users_count[user_id] = 0
reacted_users_count[user_id] += 1
break
return reacted_users_count
User: raouftazi - ID: 1141478482325536859
Execution time: 0.3402230739593506 seconds
User: tazidz - ID: 330475407675752460
Execution time: 0.34035468101501465 seconds
User: raouftazi - ID: 1141478482325536859
Execution time: 0.4886913299560547 seconds
User: tazidz - ID: 330475407675752460
Execution time: 0.4888267517089844 seconds
User: raouftazi - ID: 1141478482325536859
Execution time: 0.62017822265625 seconds
User: tazidz - ID: 330475407675752460
Execution time: 0.6202952861785889 seconds
User: raouftazi - ID: 1141478482325536859
Execution time: 0.7492554187774658 seconds
User: tazidz - ID: 330475407675752460
Execution time: 0.7493700981140137 seconds
User: tazidz - ID: 330475407675752460
Execution time: 5.335648775100708 seconds
User: tazidz - ID: 330475407675752460
Execution time: 5.48604416847229 seconds
User: tazidz - ID: 330475407675752460
Execution time: 5.641549348831177 seconds
User: tazidz - ID: 330475407675752460
Execution time: 5.795395374298096 seconds
User: tazidz - ID: 330475407675752460
Execution time: 5.955857753753662 seconds
User: tazidz - ID: 330475407675752460
Execution time: 10.467280387878418 seconds
User: tazidz - ID: 330475407675752460
Execution time: 10.6337890625 seconds
User: tazidz - ID: 330475407675752460
Execution time: 10.767956733703613 seconds
User: tazidz - ID: 330475407675752460
Execution time: 10.917591333389282 seconds
User: tazidz - ID: 330475407675752460
Execution time: 11.071693658828735 seconds
User: tazidz - ID: 330475407675752460
Execution time: 15.617467164993286 seconds
User: tazidz - ID: 330475407675752460
Execution time: 15.776914596557617 seconds
User: tazidz - ID: 330475407675752460
Execution time: 15.920830726623535 seconds
User: tazidz - ID: 330475407675752460
Execution time: 16.078328371047974 seconds
..?
Just classes. I could help u maybe
doing some testing, the ratelimit for getting users of a reaction seems to be 5/5s per channel, so there's not much you can do about it
a more efficient option would be tracking reaction events for each user, but there's the risk of having inconsistent results if your bot goes down for a while
Can i export message data and make a loop out side?
er, i dont think discord has any endpoint for that
Thx for your time
you can certainly try to export a count of the reactions using the same endpoints (assuming it complies with developer policy and local laws), but ratelimits will still slow you down
This is pycord, when I submit the modal it comes up "Something went wrong"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.add_item(discord.ui.TextInput(label="How old are you?", placeholder="Enter your age"))
self.add_item(discord.ui.TextInput(label="Describe yourself", style=discord.TextStyle.long, placeholder="Tell us about yourself"))
async def callback(self, interaction: discord.Interaction):
age = self.children[0].value
description = self.children[1].value
user_avatar_url = str(interaction.user.avatar_url)
embed2 = discord.Embed(title="User Information", color=discord.Color.blue())
embed2.add_field(name="Age: ", value=age, inline=False)
embed2.add_field(name="About you", value=description, inline=False)
embed2.set_thumbnail(url=user_avatar_url)
introductions = 1240752107846504549
target_channel = bot.get_channel(introductions)
await target_channel.send(embed=embed2)
await interaction.response.send_message("Thank you for introducing yourself!", ephemeral=True)```
any errors?
is .avatar_url a thing in pycord?
other than that the channel might be None
u can override on_error for the modal and print out any exceptions to prevent it being surpressed
how can i add a chat filter into my discord bot
yeah
This is what I get, but visual studio gives no errors 😦
add a on_error handler for ur modal
make sure get_channel returns a value
or use instead Client|Bot.get_partial_messageable
so you don't rely on the cache if you only send a message to that channel
got a vs code question... looking for a theme that will show each syntax in a different color like this. any suggestions? https://imgur.com/tYjVq9c
#editors-ides is probably a good place to poke
Anybody bored and wanna give this a crack? :D
https://discord.com/channels/267624335836053506/1240862972125905048
stupid bot
?
¿
'Member' object has no attribute 'timeout_until'
Can I resolved?
What i do?
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
You can read this for a better understanding
https://fallendeity.github.io/discord.py-masterclass/
A hands-on guide to Discord.py
Make sure to only enable the intents you need.
immediate next example uses Intents.all()
"do as i say, not as i do" moment
@shrewd apex
hmm yeah iirc i was doing a bunch of examples which needed message content and members intents so i just reused some bits of code
hmm yeah that can be changed to just enable message_content
if you are free for a while sometime could I request a proofread and suggestions on the guide better practices, stuff that can be improved etc. I would be glad to have new insights so i can improve on it
ty 🙏
Happy to offer thoughts. To be honest, us support folks in dpy have been burned time and time again by people making guides in isolation, then we have to pick up the pieces. We have a comprehensive user guide in the works but it's been delayed severely. This is the tradeoff between quality and getting many eyes on content vs velocity in getting it out
aight cool feel free to dm me or ping me here regarding this 😄
code: ```py
banners = []
for guild in self.bot.guilds:
members = [member for member in guild.members if not member.bot]
banners.extend(members)
random_banner = random.choice(banners)
banner = await self.bot.fetch_user(random_banner.id)
banner_url = banner.banner.url```
that's code
error: py Error: 'NoneType' object has no attribute 'url'
?
are you sure the user has a banner?
How could I make it only collect users with banners?
check if they have a banner before adding them to the list
how
Or you'd probably have to check when you fetch, nvm
check if its None, if its none dont add it
ah shit
When someone talk about when should you use a json file as a database vs. using a database?
is someone awake
how do i make my bot usable everywhere
i already did the connection i think i have to add some code tho
elaborate
like for .fmbot you can add app and then select the try it everywhere button
hold on lemme show u
look
😭
In a forum or a regular text channel?
Look into https://discord.com/developers/docs/tutorials/developing-a-user-installable-app
I haven't been keeping up with discord.py's development, so I'm not sure if it's got support yet
thank you
regular text channel
another question
why do my prefix commands get cancelled out if theres an on_message bot event?
Registering the on_message event with @bot.event will override the default behavior of the event. This may cause prefix commands to stop working, because they rely on the default on_message event handler.
Instead, use @bot.listen to add a listener. Listeners get added alongside the default on_message handler which allows you to have multiple handlers for the same event. This means prefix commands can still be invoked as usual. Here's an example:
@bot.listen()
async def on_message(message):
... # do stuff here
# Or...
@bot.listen('on_message')
async def message_listener(message):
... # do stuff here
You can also tell discord.py to process the message for commands as usual at the end of the on_message handler with bot.process_commands(). However, this method isn't recommended as it does not allow you to add multiple on_message handlers.
If your prefix commands are still not working, it may be because you haven't enabled the message_content intent. See /tag message_content for more info.
thank you!
looks like Rapptz/discord.py#9760 got merged to the main branch a couple weeks ago so you dont need to install the PR anymore
!d discord.app_commands.user_install
@discord.app_commands.user_install(func=None)```
A decorator that indicates this command should be installed for users.
This is **not** implemented as a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check), and is instead verified by Discord server side.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
Examples...
As a warning, things on the master branch and not on a stable release are NOT supported, and not considered stable. You will not get library support on them, and they are not guaranteed to not change before release
so i need the master branch discord
and not the stable build
oh wait you mean threads right?
not sure of its exact usage because ive never bothered to try it, but afaik you would first enable user installs in the dashboard, mark commands with one of those decorators, sync them, and then users can authorize the app so only they can see those commands
nah threads are stable, user installs are not
already did
how do i get the version that support user installs 🥺
so i can just do this?
https://github.com/Rapptz/discord.py
To install the development version, do the following:
$ git clone https://github.com/Rapptz/discord.py $ cd discord.py $ python3 -m pip install -U .[voice]
or the oneliner, pip install git+https://github.com/Rapptz/discord.py
pip already treats it as a different version of discord.py, so thats automatic
alright thanks
im ngl user installs dont work
am i doing it right 😭
its a bit awkward that the docs shows func=None in the signature...
theres an example under it
oh
whoopsies
does this make the command only work in user installs or do they work in guilds too
oh wait this is cool lol
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
im guessing this would work? @hushed galleon
do i have to wait on discord to do some things so that its properly synced
cuz i dont see it in dms or private channels 😔
oh wait
yes
its super buggy and super weird
if i do this:
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
it'll only work in guilds, it ignores dms and private_channels
@app_commands.user_install()
if i do this
it'll obviously only work for people who tried it themself, aka the weird feature
if i try doing this
@app_commands.guild_install()
@app_commands.user_install()
only guild install would work
idk how to do both of them
i want it to work in dms, group chats and guilds
im gonna try @app_commands.allowed_installs(guilds=True, users=True)
ok update:
it works in every guild however not private channels or whatever
the current decorators that i have rn is
@app_commands.allowed_installs(guilds=True, users=True)
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
its insanely buggy for no reason 😔
if I send an embed though a slash command, why would an imgur thumbnail not load? is that a permissions thing?
no there shouldnt be an issue
Try putting "?raw=true" at the end of the link, but there shouldn't be an issue, so this raw is not really necessary
didn't fix it. could it be the format of the image? https://i.imgur.com/5BimDGn.png is one of the examples I'm testing. e.set_thumbnail(url="https://i.imgur.com/5BimDGn.png")
likie my other imgur embeds work, but this doesnt?
i have my images in a db, but i even tried hardcoding it to see if it's the method of the url or something
im guessing its the png format or something
I am setting up my first discord bot and I want to keep my token secret. I checked the pinned messages and the link is broken, but I understand that I can save it to a .env file. Can someone link me further help on this issue?
Nevermind, I was able to reference this page on StackOverflow after lots of searching. https://stackoverflow.com/questions/63530888/how-would-i-go-about-creating-an-env-file-for-my-discord-bot-token. I would still like to point out the pinned link in this channel for this information is still broken.
which pinned link?
Can anyone check and help if the code I wrote below is appropriate for the Discord.py library? I'm pretty new to this. I'm trying to understand how checks work so I can restrict a command to users with the staff role only.
def has_specific_role(role_id):
async def predicate(ctx):
member = ctx.guild.get_member(ctx.author.id)
if member is not None:
role = discord.utils.get(member.roles, id=role_id)
return role is not None
return False
return commands.check(predicate)
@bot.tree.command(name="Hello", description="Say hello to the bot.")
@has_specific_role(role id here lmao)
async def slash_command(interaction: discord.Interaction):
await interaction.response.send_message("Hi there! I'm SERENA, nice to meet you!")
Please ping me!
!d discord.app_commands.checks.has_role
@discord.app_commands.checks.has_role(item, /)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check) that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingRole) if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.NoPrivateMessage) if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure).
New in version 2.0...
I read the docs and did my best to understand 
u can use that check directly in ur case
ohhh okay thank you sm I will work on it rn!
is it advised to use @command.has_permission(), or to check for their permissions in the code itself?
this is for slash command check examples in docs
I JUST SAW THIS THANK YOU SO MUCH!!!!!
upto you u can use the decorator and then define an error handler
it helps a TON!
for check failures
that way if u have multiple commands behind a particular perm u dont need to check it in command code again and again
idk if my code would be more confusing if I had to do an error for each command
not each command a global error handler
@client.command(name="purge")
async def purge(ctx, amount: int):
role_id = 1240776442229424168 # Replace with your role ID
if role_id not in [role.id for role in ctx.author.roles]:
embed = discord.Embed(description="You do not have the required role to use this command.", color=discord.Color.red())
await ctx.send(embed=embed, delete_after=5)
return
if amount <= 0:
embed = discord.Embed(description="Please specify a positive number of messages to delete.", color=discord.Color.red())
await ctx.send(embed=embed, delete_after=5)
return
def not_pinned(message):
return not message.pinned
try:
deleted_messages = await ctx.channel.purge(limit=amount, check=not_pinned)
embed = discord.Embed(
title="Messages Purged",
description=f"Successfully deleted {len(deleted_messages)} messages.",
color=discord.Color.green()
)
await ctx.send(embed=embed, delete_after=10)
except discord.Forbidden:
embed = discord.Embed(description="I do not have permission to delete messages.", color=discord.Color.red())
await ctx.send(embed=embed, delete_after=5)
except discord.HTTPException as e:
embed = discord.Embed(description=f"An error occurred: {e}", color=discord.Color.red())
await ctx.send(embed=embed, delete_after=5)
Anyone know why this wont work
How does it not work
Just does nothing
Add some prints inside
ive tried.
Where'd you put the prints and did they get printed?
hello
why does this not work?
@Bot.event
async def on_message(message):
if 'hi' in message.content:
await message.send("sup")
it says:
AttributeError: 'Message' object has no attribute 'send'
and idk what else i should do
message.channel is the channel where the message was sent, you can send to channel not messages
nvm
ik i just realised thx
png shouldn't be a problem, Discord is equiped to handle the format, why don't you try to access the image locally? It's not a good practice but you can try downloading the image and trying to access it from your files to see if the issue is with the link or the image, which I think is the link
Anyone has ideas for features/functions to make? I've done a lot but idk what next
is it okay to use json file for things like economy for public and private discord bots?
You shouldn't be using a flat json file as a database of any sort
does anyone know how to make a bot user installable and able to be used in guilds (guild install) private channels (dms and group chats)?
Discord bots can't tell if two users are friended
then how do i check if someone is friend with someone?
i mean
in friend list
sorry the confusion
I just told you, you can't
i see, not even if it's in friend list
Discord bots don't get that info (not even discord users get that info)
i see
guess copying someone's macro code would be unviable
aka unpractical
due to this and also the security breach
i like ur website it's nice
thank you!
uhmm, don't it was suppose to be a property of Embed?
do you have the image = "your image"?
yes, the image is from the image input from my method
This isn't how you set an image in the embed.
in another file?
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
import discord
async def exe_image(image):
embed = discord.Embed()
embed.set_image(url=image)
return embed
@severe sonnet
this is an example how to do it
yeah, oio made that once you sent me this
ok
add this:
image_url = "https://example.com/image.jpg"
embed = await exe_image(image_url)
and tell me if thisa works
yeah, and it worked, gotta test with macro
okay !
error:
Cog error: general: Extension 'src.cogs.general' raised an error: NameError: name 'ui' is not defined```
code: ```py
import discord
from discord import ui
class Questionnaire(ui.Modal, title='Questionnaire Response'):
name = ui.TextInput(label='Name')
answer = ui.TextInput(label='Answer', style=discord.TextStyle.paragraph)
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message(f'Thanks for your response, {self.name}!', ephemeral=True)```
@slim bloom What package is this?
@timber dragon
code: ```py
banners = []
for guild in self.bot.guilds:
for member in guild.members:
if not member.bot:
user = await self.bot.fetch_user(member.id)
if user.banner:
banners.append(user.banner.url)
random_banner = random.choice(banners)
banner_url = random_banner
print(f"Banner: {banner_url}")```
Because it does not work?
ui is not defined
Make sure its imported before you use it or discord.ui... works too
Also you don't need to ping me or anyone for help
but I wanted help from banner_url
@timber dragon
and sorry
does the api have hybrid commands
for a prefix/slash command
so i dont have to do them seperately
in discord.py they are known as hybrid commands and in pycord they are known as bridge commands. I don't know if other libraries support this type of commands.
are there any examples of this in d.py
25
is it possible to make the dropdown menu persistent?
Yes
then where am I supposed to put the custom id?
In the options part?
!d discord.ui.Select
class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu with a list of custom options. This is represented to the user as a dropdown menu.
New in version 2.0.
Where you define it
Do anyone know how to build a chat bot ?? [like ai]
by... ||coding||
a simple one, or smth like ChatGPT?
if you wanna make an LLM from scratch it's gonna be very hard
Hey, I'm trying to make a Discord bot but in devloper portal discord I don't have anything to add a bot to my server
The portal lets you generate an invite link with the permissions you want to request (assuming you have Bot enabled on your application)
A server manager has to go to that link to invite the bot. You can't add it directly from the portal
If it's set to private, that has to be you
How would I create a command that sends embedded message through a webhook? like .publish <content>
not asking to be spoonfeed just cant figure this out
Which part are you having trouble with?
Making a command?
That does that yes
No, do you know how to make a command?
Yes
Then that wouldn't be "all of it"
hmmm
Do you know how to make a webhook on discord?
Mhm
Do you know how to send a message to that webhook in code?
Which library are you using?
at less not yet
!d discord.Webhook.from_url
classmethod from_url(url, *, session=..., client=..., bot_token=None)```
Creates a partial [`Webhook`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook) from a webhook URL.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
You can use this to create a Webhook object from the url discord gives you. You can then call .send on that Webhook
How could I add a modal to a button?
In the button's callback, you can respond to the interaction by sending a modal
docs?
Just await interaction.response.send_modal(MyModal())
How can I send a user a form when they invoke a command?
What library do you use?
Lovely, thank you!
class Report(discord.ui.Modal, title="Reporte"):
description = discord.ui.TextInput(label="Describe tu reporte", style=discord.TextStyle.long, placeholder="Explica qué ha sucedido...", required=True, max_length=150)
def __init__(self, message: discord.Message):
super().__init__(title="Reporte")
self.message = message
async def on_submit(self, interaction: discord.Interaction):
try:
await interaction.response.send_message("Reporte recibido.", ephemeral=True)
await self.message.delete()
except Exception as e:
await interaction.response.send_message(f"Error: {e}", ephemeral=True)```
Why doesn't it delete the reported message, in this case embed?
should work fine
try using instead delete_original_response
ok
don`t work
do you get any error message? or is "Reporte recibido" not sent at all?
I receive the message report received but it does not delete the message
embed*
and does any error message show up in your console?
odd, if message.delete() failed then i would have expected the "Error: {e}" to fail and then result in a double traceback being logged, given that the interaction was already responded to
yeah ;c
async def on_submit(self, interaction: discord.Interaction):
try:
await interaction.response.send_message("Reporte recibido.", ephemeral=True)
await interaction.response.delete_original_response()
except Exception as e:
await interaction.response.send_message(f"Error: {e}", ephemeral=True)```
assuming something is wrong with your console not showing errors, can you try deleting the message first and then sending any traceback to discord? e.g. py try: await self.message.delete() except: import traceback message = discord.utils.escape_markdown(traceback.format_exc()) await interaction.response.send_message(message, ephemeral=True) else: await interaction.response.send_message("Reporte recibido.", ephemeral=True)
although for dpy, it could also mean you haven't configured logging...
what code do you have to start your bot? minus the token
views and modals don't report errors by default right? unless u have on_error setup
i checked earlier, they call the logger by default instead of print_exc() that dpy used to use for er, on_error events iirc
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/ui/modal.py#L166
discord/ui/modal.py line 166
_log.error('Ignoring exception in modal %r:', self, exc_info=error)```
ic
i usually have that on_error overriden for this makes debugging way easier
class Report(discord.ui.Modal, title="Reporte"):
description = discord.ui.TextInput(label="Describe tu reporte", style=discord.TextStyle.long, placeholder="Explica qué ha sucedido...", required=True, min_length=10, max_length=150)
def __init__(self, message: discord.Message):
super().__init__()
self.message = message
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message("Reporte recibido.", ephemeral=True)
await interaction.response.delete_original_response()
async def on_error(self, interaction: discord.Interaction, e: Exception = None):
await interaction.response.send_message(f"Error: {e}", ephemeral=True)```
@shrewd apex
^ can you use this for on_submit instead?
as in no message appears?
no
also, do you use await bot.start(...) instead of bot.run()? if so, you might not have logging configured
Who can teach me to create discord bot plz?
yeah, bot start
can you call discord.utils.setup_logging() just before bot.start() then? and then write your modal without any error handling, e.g. py async def on_submit(self, interaction: discord.Interaction): await self.message.delete() await interaction.response.send_message("Reporte recibido.", ephemeral=True)
configuring logging should make the modal log error tracebacks to your console as normal
delete_original_response is an interaction method, not a response









