#discord-bots
1 messages · Page 363 of 1
yeah sorry
my bot isn't responding on discord this is the code:
https://paste.pythondiscord.com/2QFA
I get this on my cmd:
[2024-05-08 14:50:00] [WARNING ] discord.ext.commands.bot: Privileged message content intent is missing, commands may not work as expected.
[2024-05-08 14:50:00] [INFO ] discord.client: logging in using static token
[2024-05-08 14:50:01] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: df02e9c7af814420779c9fd726debdf1).
roblox has connected to Discord!
I have enabled the settings on discord dev portal but yet no respond.
You're not requesting it in code
which code do i need to add that into the code? and where? ( i just started coding )
You need to enable the message_content flag on the Intents object you're passing into your bot
and how do i do that?
!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.
what you're looking for is in the codeblock
i added the stuff from the codeblock but it still not working
new error?
still getting this:
[2024-05-08 15 11 38] [WARNING ] discord.ext.commands.bot: Privileged message content intent is missing, commands may not work as expected.
[2024-05-08 15 11 38] [INFO ] discord.client: logging in using static token
[2024-05-08 15 11 39] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: 3530980cfef0825cd05cb4df16be243c).
roblox has connected to Discord!
so its not enabled in the dev portal
code?
you're overriding the intents silly
its like if i did this
!e py a = 5 a = 19 print(a)
@viscid hornet :white_check_mark: Your 3.12 eval job has completed with return code 0.
19
@viscid hornet :white_check_mark: Your 3.12 eval job has completed with return code 0.
19
oh bruh which ones do i need to remove?
just combine the two
intents = ...
intents.something = True
intents.something_else = False```
which two?
both sets of intents
you’re writing intents then overwriting it
better?
yes
it is not working still
I want to setup a command that uses dates. Is there a better setup than this:
/search day:XX Month:XX, Year:XXXX
have it as one string and use datetime.datetime.strftime
!d datetime.datetime.strftime
datetime.strftime(format)```
Return a string representing the date and time, controlled by an explicit format string. See also [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior) and [`datetime.isoformat()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.isoformat).
oh wait its strptime
But that's not for a python command param
!d datetime.datetime.strptime
classmethod datetime.strptime(date_string, format)```
Return a [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) corresponding to *date\_string*, parsed according to *format*.
If *format* does not contain microseconds or timezone information, this is equivalent to:
```py
datetime(*(time.strptime(date_string, format)[0:6]))
``` [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) is raised if the date\_string and format can’t be parsed by [`time.strptime()`](https://docs.python.org/3/library/time.html#time.strptime) or if it returns a value which isn’t a time tuple. See also [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior) and [`datetime.fromisoformat()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat).
Im dealing with idiots players on a video game not programmers lol
They won't understand how to put a datetime in properly.
just take a date like 23/07/2024 and then pass it as “%d/%M/%Y”
They're idiotsplayers
mfw MM/DD/YYYY
if they’re fucking stupid then go for the day, month, year approach
whats the new error
it works now but the answer part isn't working
answer part?
Ya. I was hoping for a better approach is all lol
do you not have syntax highlighting?
i got no idea what that is
your “command” is a message listener, not a command
when you send “!answer” it interprets that as a command
oh
If you want to use the command framework, you should make actual top level commands and get rid of your on_message
!code
(send the link)
thank u 😭
you get far more out of commands than a simple message event listener because commands are made to be commands and message event listeners are just plain text 🤷🏽♂️
@slate swan spit it out

grr whos my good wittle kitten

okayy thank you for explaining
@vale wingDo you know how to overwrite a text file with new data outside of the docker container?
I'm trying to update a text file based on data fetched from a URL, but it seems like the file changes are not persisting as expected locally
This is a discord bots channel
please use #1035199133436354600
!d str.join
str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes) objects. The separator between elements is the string providing this method.
This is a discord bots help channel 😭
Please use #bot-commands to use the bots
My bad
Is it mounted
If it is, file perms are read only, you can manually alter them and edit file
Someone knows how i can add the a specifc value as the default value to ui textinput in discord.py
`class add_keyword(ui.Modal):
keyword = ui.TextInput(
label="Keywords",
default=self.value
)
excluded = ui.TextInput(
label="Exclude",
required=False
)
def __init__(self, value):
self.value = value`
that wouldnt work
I'm running a task to update the text file. So there is no way to update the text file locally by the bot running in a docker container?
with open('blacklisted_domains.txt', 'r', encoding='utf-8') as f:
current_blacklist = f.read().splitlines()
if fetched_data.strip() != '\n'.join(current_blacklist).strip():
with open('blacklisted_domains.txt', 'w', encoding='utf-8') as f:
f.write(fetched_data)```
Sorry I don't really understand what you mean. The idea is that the bot should write to the text file with new data. I don't want to do it manually.
You pretty much can. Could you show how you mount it
Ah mb, thought you were trying to edit it manually from hard drive
modals dont have an __init__ btw
I think kwarg is placeholder
But why lower_snake_case classname 😭
Please
UpperCamelCase
#!/bin/bash
echo "Stopping existing Docker container..."
docker stop blitzcrank
wait
echo "Removing existing Docker container..."
docker rm blitzcrank
wait
echo "Removing existing Docker image..."
docker rmi blitzcrank
wait
echo "Building a new Docker image..."
docker build -t blitzcrank .
wait
echo "Starting a new container with the updated image..."
docker run -d --name blitzcrank --restart always -t blitzcrank```
Use compose 😛
It's headache to configure volumes via cli
how do i change the profile of a guild with a simple command?
!d discord.Guild.edit
await edit(*, reason=..., name=..., description=..., icon=..., banner=..., splash=..., discovery_splash=..., community=..., afk_channel=..., owner=..., afk_timeout=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the guild.
You must have [`manage_guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_guild) to edit the guild.
Changed in version 2.0: The newly updated guild is returned.
Changed in version 2.0: The `region` keyword parameter has been removed.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
i need an example
Spoonfeeding*
But fine
@command()
async def swap_icon(ctx):
with open("new_icon.png", "rb") as fp:
await ctx.guild.edit(icon=fp)
but it works
ok
if it works then 🤷
thx but it doesnt work
You asked for example, not working code 😛
ok
Figure it out and adapt for your needs
yk what i meant
ok
Yeah I know. This was just my temporary solution 😄
However, any idea how I can write to the text file locally?
Well you'd still need compose first
Configuring volumes via cli is possible
But your build line will be long af and unreadable
how do i make it work then?
Well what have you transformed the code to for now
You need to change the decorator and filename at the very least in order for it to work
If I wanted to use python (ro.py, discordpy) to make a roblox in-game verification system, is that possible
I’m aware it would need a webhook, I’m just not sure how to use them
Can you give me an example for a better understanding?
https://www.pythondiscord.com/pages/guides/python-guides/docker-hosting-guide/ there is a guide how to configure volume
This guide shows how to host a bot with Docker and GitHub Actions on Ubuntu VPS
So from my understanding is the blacklisted_domains.txt file currently saved in the memory or in temporary files?
And compose
Yeah as long as it's not mounted it lives as long as container does
Well you'd just need to use roblox API I guess
Can do that pretty much from any app as long as you have internet connection xd
!pypi aiohttp use this
As I said however, I’m pretty new to this. Can you go a bit into detail?
technically everything has __init__ 
Well web API is not something I can explain in one discord message, but I can give you some guides to understand that topic
Alright! Please do
https://realpython.com/api-integration-in-python/ think this one is good
Kk
Yeah that one even has examples
They're using requests library however, keep in mind that you will need to swap to aiohttp when you get to implementing your verification system
you have no right to talk
Is there a way to retrieve all members with a specific role without having to iterate through every member in the guild?
!d discord.Role.members
property members```
Returns all the members with this role.
@young dagger 
Hello y'all me again back with another issue lol, use have helped me solve many of my issues with my bot so far and it's currently working amazingly so Thank you,
Anyways I have added a new command which will remove said members from their current role and also update the embed message accordingly (by removing their @username from that category) however when I try to use the remove command I get the error message Unknown Integration within discord, how do I resolve this so the command works as it should.
Code and traceback?
async def remove_from_category(ctx, category_name: str, member: discord.Member):
try:
if not ctx.author.guild_permissions.administrator:
raise commands.MissingPermissions(["administrator"])
normalized_category_name = category_name.lower()
if normalized_category_name not in queue_categories:
raise commands.BadArgument("Invalid category name.")
role_name = queue_categories[normalized_category_name]
role = discord.utils.get(ctx.guild.roles, name=role_name)
if not role:
raise commands.BadArgument("Role not found for the specified category.")
await member.remove_roles(role)
channel = ctx.guild.get_channel(TARGET_CHANNEL_ID)
if not channel:
raise commands.BadArgument("Target channel not found.")
await update_embed(channel)
await ctx.send(f"Successfully removed {member.mention} from {category_name}.")
except commands.MissingPermissions as e:
await ctx.send(f"You don't have permission to run this command: {e}")
except commands.BadArgument as e:
await ctx.send(f"Invalid usage: {e}")
except Exception as e:
traceback.print_exc()
await ctx.send(f"An error occurred: {e}")```
Something like?
unverified_role = discord.Role.members(id=769451860884062228)```
members is a property, not a method
so it doesn't take any arguments
you would have to first get the role from the guild
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
and on that role use an members property
What is different between that method and unverified_role = discord.utils.get(guild.roles, id=769451860884062228)
What I think it will do is looping thru every role and comparing its id to the one provided to you
and get_role will take the role from the cache
(will return None if not found)
What is the best way to handle comparisons with member.joined?
# Check if member joined more than 5 minutes ago
if (datetime.datetime.utcnow().replace(tzinfo=None) - member.joined_at.replace(tzinfo=None)).total_seconds() > 300:
Thank you
This sounds more like a general question
Sure
I want to compare member.joined which is Discord related
Ofc anything is gonna be Python related too
More like datetime
You'd probably have more chance in #1035199133436354600 anyway
Sure. Right to my note 🤠
is there another way to do application / slash commands without all the tree stuff?
You'd have to use the forks, like disnake, instead in that case
async def on_message(message):
if 'happy birthday' in message.content.lower():
await message.channel.send('Happy Birthday! :balloon::tada:')```
what does lower mean?
or content.lower
Hi guys, gonna ask for a suggestion, if there is already a bot for this use case, if not then I'll just end up making a bot for this
Use case: Ban the user if they write anything in the honeypot channel
This is being done to ban people who use spam bots.
!d str.lower
str.lower()```
Return a copy of the string with all the cased characters [[4]](https://docs.python.org/3/library/stdtypes.html#id15) converted to lowercase.
The lowercasing algorithm used is [described in section 3.13 ‘Default Case Folding’ of the Unicode Standard](https://www.unicode.org/versions/Unicode15.0.0/ch03.pdf).
it makes the string all lowercase
- use an on_message listene
- compare the message’s channel id to the honeypot channel id
- ban them if it is
whats the issue with “tree stuff”?
Is there a way to host it somewhere for free ?
Repl.it maybe ?
Sorta need it 24/7, can't have the pc running 24/7
Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.
See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.
You may also use #965291480992321536 to discuss different discord bot hosting options.
there we go. check this out
Thanks mate !
what means channel "unbekannt" / "unknown" in the hosting factoid? that the resource changed?
channel unknown? what are you doing to get said channel
you used the trigger "!hosting" and the bot posted a factoid as reaction. it suggests to join the channel "unknown" and it confuses me
just means the channel doesnt exist
oh, ok
👍🏽
Do try and except blocks on discord errors work? I have tried a bunch of stuff but none of them seem to be catching the discord errors
assuming you mean with discord.py using the commands extension, it depends on what raised the error - if it was something inside your command body then you can try-except that just fine, but for errors outside of it like check failures, CommandNotFound, MissingPermissions, etc., you need to write a special error handler for it:
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#error-handling py @bot.event async def on_command_error(ctx, error): if isinstance(error, commands.MissingPermissions): await ctx.send(f"You are missing the following permissions: {error.missing_permissions}") else: raise error # print traceback to terminal
daaang so its a specific function that I call for permissions errors? You are too smart
my problem is with permissions so that is super helpful
its just too much
but i found another way
i think it was
@bot.hybrid_command(name="The_name", description ="The_Description")
and so on
with await bot.tree.sync in the async def on_ready event thing at the start
Hey I'm just starting out with discord user installed apps in Python and wondering if someone could link some example code, or maybe just some barebones code that uses /hello and will output a little greeting from the bot. Much appreciated.
I would recommend reading the documentation for on_ready before continuing to use it
I'd recommend you making a separate command instead of calling it in events everytime you update new command in bot you sync it using sync command
Documentation has those examples already
thats how i done it
Hey can anyone help me
if
message = message.content.startswith("hey"): message.channel.send("¡Hey!")
But no work
∆:
message.channel.send() is not awaited
And bad indentation
if message.content.startswith("hey"):
await message.channel.send("¡Hey!")
Have you learnt python?
on_ready might get called multiple times whenever your bot reconnects, starts, etc so triggering bot.tree.sync() so many times might lead you to timeout so it is better to use it only when necessary instead of calling it many times unnecessarily
??.
Where's the event decorator and function?
Writing these two lines won't make it work
Link?
Uh I copy what u send
That's not how it works
Uh so what I Ned do when someone say hey the bot respond?
You can make a command or use on_message event which listens to every message
Can u make. 😭 I was looking for that
@bot.Event
async def on_message(message):
if message.content.startswith("hey"):
await message.channel.send("¡Hey!")
But remember this channel isn't for spoon feeding you gotta learn things on your own and try to build it by yourself
Yes thanks but it give this error
Why is it om line 474 what's the rest code?
this is why you don't edit code inside pterodactyl
I got much codes all work
Use proper IDE
I was looking for that
I wouldn't recommend editing code directly on the panel
shouldnt it be a lowercase e?
that should be a lowercase e...
Well his code isn't working anyways so
So point in investing energy....
you shouldnt be auto-syncing in on_ready
whats wrong w it
@viscid hornet bro's trynna edit it directly on panel
I've no idea because never experienced this error before
how come? ```py
for main.py file
@bot.tree.command()
async def test(interaction):
await interaction.response.send_message("hello")
for cog
class MyCog(...):
...
@app_commands.command(name = 'test', description = '...')
async def test(self, interaction):
await interaction.response.send_message("hello")```
you have an unprintable character at the end of the line 🤷
(this is for slash commands only btw)
unprintable character?
Could be possible that there's a invisible character
my question is how the hell is bro 500 lines deep into the file thats supposed to be his main file
Same question but with one more condition
How bro wrote 500 lines when he can't even make simple event
@viscid hornet see this
guy just wrote an if statement 😭🙏🏽
mf works in mysterious ways
Uh what wrong?
My literal reaction to it .
More mysterious than aliens
E?
@bot.event
async def on_message(message):
if message.content.lower().startswith("hey"):
await message.channel.send("¡Hey!")
Try this
@plush field
lowercase e on Event
Ok I'm back I was eat
Thanks it work and also it gave a limit? Like how much I can put this in my main.py
There's no limit but it's a good practice to keep it short and simple and organize your commands in cogs
Okay and also if I put this the commands was I got don't work
Only the "hey"
And don't give error where should I put?
How you organize commands/whatever else into cogs is completely orthogonal to what files you put things in. Cogs are classes, and can go wherever. Your main file could have 50 cogs and that would work just fine
turns out I need on_error instead of on_command_error because I am doing it on a on_reaction_add function. quite a pain
. With both on_error and on_command_error I should be able to have the global error handler in main while the functions that might raise errors are in cogs right? The error handler should still catch it?
yes, the @bot.event / @bot.listen() decorators receive errors from listeners in your cogs
in the case of commands, the command's error handler runs first, then cog_command_error(), then your global handlers
Ahhh yeah makes sense
I appreciate it!
So you can edit ephemeral messages, can you delete them?
I am talking abt interactions.
!d discord.Interaction.delete_original_response can do that
await delete_original_response()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the original interaction response message.
This is a lower level interface to [`InteractionMessage.delete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.delete) in case you do not want to fetch the message and save an HTTP request.
alr ty 😁
Wait, I am calling a drop down, how can I do this? I wanna make the message go away after they select whatever they select ya know?
They press a button, which then calls a drop down.
I wanna delete the message the button sends, but after they click the cog they reload..? How can I do that..?
since the select is an interaction, you can call delete original response and it’ll delete that message
check the code
also for your exceptions, remove the “exception as e” and use this
!d traceback.format_exc
traceback.format_exc(limit=None, chain=True)```
This is like `print_exc(limit)` but returns a string instead of printing to a file.
i see too many beginners just printing the last line of the error and not including any traceback info as to what ent wrong
can you not just use delete OR?
let the select do it after it reloads
Thats for embed only 
in console it will show traceback
I am not going to show traceback inside of an embed.
it wont because you’re catching the error then printing it
Bro, inside of console, it shows the full error...
it doesnt when you do it like that
Does for me.
!e
x = "abc"
try:
x = int(x)
except Exception as e:
print(e)
@viscid hornet :white_check_mark: Your 3.12 eval job has completed with return code 0.
invalid literal for int() with base 10: 'abc'
prints the last line
what IDE are you using that prevents errors from being caught by try excepts 😭🙏🏽
pycharm is so not lightweight 😭
cant run it for shit
When did the word lightweight come into this..?
how the fuck am i supposed to rate an editor if it takes 2 minutes to load 😭🙏🏽
2 seconds*
thats why we use vscode babyyy 🗣
2 minutes*
Your pc just sucks then bro 
actually wait
im a fucking microwave 🤦🏽♂️
20 seconds
i was thinking about it wrong
eh shut up anyway
printing an error is still bad practice 🤷🏽♂️
IM NOT EVEN PRINTING ITTTT
why cant you use delete OR?
SHOW THE PRINT
mfw im paraphrasing
^^
in callback???
yeahh? callback has interaction
No I can't do that
await interaction.delete_original_response()
It will give an error
404 error.
fax
missing interaction? or what?
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
pass in the view the parent interaction and use that to delete the message
that should in theory work fine
yeah hes big brain
see

sometimes...
most of the time
i thought you were gonna say “finally you’re useful” 😭🙏🏽
real
this is the first time youve actually helped me
instead of me HELPING you
see, im useful
bro been counting
also just so you know, it works because the parent interaction is what sends the message with the view so that interaction holds the original response. you can think of the select interaction as a child interaction where it doesnt have an original response
hes been marking on his wall and going insane

when has this ever happened
real
Check first dm buddy
your first dm was you asking for help 
waiting for bro to delete the message 
🤫
|| (not in front of the hoes) ||


@viscid hornet
yeah?
Be more help, i was showing this man that only codes bots in js, my control panel, but he doesn't know what cogs are
so what would cogs be in js? I said extensions, he said no also 
Tf do they have in js 😭
just call em modules
they import stuff in the same way i believe
djs might have cogs idk
😭
research it
Research? whats that...?
cogs are just discordian modules that you import
!d InteractionResponse @crisp glacier
Lol
!d discord.InteractionResponse @crisp glacier
class discord.InteractionResponse```
Represents a Discord interaction response.
This type can be accessed through [`Interaction.response`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.response).
New in version 2.0.
call em modules and just move on w the convo
TO much work
its basically modules if you must know
?ah
from discord.ext import commands
Yes
import discord
from discord.ext import commands
Example
Ok thx
I made this control panel in my bot, was wondering if anyone had any more ideas for it!! if not then that is fine!
maybe further cog information, ability to enable disable commands in the cogs itself some handling of tasks as well i suppose?
cancel, start, restart tasks ig
import discord
import os
# Set bot token as environment variable
os.environ['BOT_TOKEN'] = 'token'
intents = discord.Intents.all()
intents.messages = True
intents.message_content = True
class DiscordBot(discord.Client):
def __init__(self, intents):
super().__init__(intents=intents)
async def on_ready(self):
print(f'Logged in as {self.user}')
async def on_message(self, message):
if message.embeds:
for embed in message.embeds:
self.print_embed(embed)
def print_embed(self, embed):
print("Embed Title:", embed.title)
print("Embed Description:", embed.description)
print("Embed Fields:")
for field in embed.fields:
print(f" {field.name}: {field.value}")
print("Embed Footer:", embed.footer.text)
print("Embed Image:", embed.image.url)
print("Embed Thumbnail:", embed.thumbnail.url)
print("Embed Author:", embed.author.name)
print("Embed URL:", embed.url)
def run(self):
try:
super().run('BOT_TOKEN')
except discord.errors.LoginFailure:
print("Invalid bot token")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == '__main__':
bot = DiscordBot(intents)
bot.run()
Why my bot not responding
Any additional information? What exactly doesn't work 
🤔
you don't have a command prefix?
also you shouldnt go through the bother of subclassing Client because Client is a literal nothingburger when it comes to doing literally anything
also STOP PRINTING EXCEPTIONS. PLEASE 😭
But it's a even when embed is sent
man this my first time coding a bot and i cant even get it to run
can you rephrase?
whats your issue? i gotchu my man 🤝
That code is gen from gpt idk coding 💀
weve all been there bro
Don't even know what that means
from typing import Final
import os
from dotenv import load_dotenv
from discord import Intents, Client, Message
from responses import get_response
TOKEN = 'token'
intents: Intents = Intents. default()
intents.message_content = True
client: Client = Client(intents=intents)
async def send_message(message: Message, user_message: str) -> None:
if not user_message:
print( '(Message was empty because intents were not enabled probably)')
return
if is_private := user_message[0] == '?':
user_message = user_message [1:]
try:
response: str = get_response(user_message)
await message.author.send(response) if is_private else message.channel.send(response)
except Exception as e:
print(e)
@client.event
async def on_ready() -> None:
print(f'{client.user} is now running!')
@client.event
async def on_message(message: Message) -> None:
if message.author == client.user:
return
username: str = str(message.author)
user_message : message.content
channel: str = str(message.channel)
print(f'[{channel}] {username}: "{user_message}"')
await send_message(message, user_message)
def main() -> None:
client.run(TOKEN)
if __name__ == '__main__':
main()```
🤦🏽♂️
time to learn how to code then
try writing code normally this time
i followed a tutorial on yt for this
2 things:
- syntax highlighting (do
!code) - should be using
commands.Botpreferably
Can you provide video/text of reading embed?
Ik basics
wdym "reading" an embed?
no like type the command lol
!code
# codeblocks
"with syntax highlighting"
When a bot sends a embed
My bots need to print and store those in var
"""
makes things easier to read
"""```
gambling go dms before i cut your balls
😭
So I can do things with that
just store the embed itself as a variable
My bot be like
🤓 No one sent embed
why is ur username google btw
I used carl bot to send embed
Umm 😳
(read the embed)
Ahh
!code
three backticks then py at the end
then three backticks under the code
that gives it syntax highlighting which makes it easier to read
AY THERE WE GO
i fixed xd
Can you check if this is a working code?
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages) to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot) does not have this problem.
two things:
- use
commands.Bot - you already enabled all the intents - you dont need to re-enable them
Should I make a normal command ?
Reather then using events?
few things:
- use
commands.Bot - you dont need a main loop - dpy already has its own
.run()function requestsis blocking so it freezes your bot while processing a HTTP request
you have to use events for this sort of thing
just how it goes yk ¯_(ツ)_/¯
ic
listen to gambling he big brain
when i asked chatgpt it said that "SSL certificate verification failed due to the inability to get the local issuer certificate"
!d discord.ext.commands.Bot for more info
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, ...)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin) to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
!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.
show me this ^^
Whats wrong in my code?
And what should I change so it can work
probably that its written by chatgpt
its really long should i send all of it?
Where can I learn about embeds reading
Idk that stuff
!code | yeah go ahead. if it's too long use this:
!d discord.Embed | read up on the attributes of this
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
It's for making embeds but how to read embeds through bot
read up on the attributes of this
hmm 🤔
!d discord.Message.embeds
A list of embeds the message has. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
i think its just getting the content from the embed for some reason
hm

hi ray
@slate swan thats a network issue i think. ask @fast osprey - she fixed this issue for someone
hi
i have no idea how to sort it ¯_(ツ)_/¯
|| ray do you have balls ||
alr
solstices hard
!d random.choices @crisp glacier
random.choices(population, weights=None, *, cum_weights=None, k=1)```
Return a *k* sized list of elements chosen from the *population* with replacement. If the *population* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError).
If a *weights* sequence is specified, selections are made according to the relative weights. Alternatively, if a *cum\_weights* sequence is given, the selections are made according to the cumulative weights (perhaps computed using [`itertools.accumulate()`](https://docs.python.org/3/library/itertools.html#itertools.accumulate)). For example, the relative weights `[10, 5, 30, 5]` are equivalent to the cumulative weights `[10, 15, 45, 50]`. Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.
notd
SSL issues very rarely have to do with network at all and typically are just a lack of certs on the local machine
does markdown not work in embed fields?
it works
Code
blackjack_hit.add_field(name="Dealer deck", value=f"# {hand_value_dealer} -" + ",".join([str(c) for c in self.casino.dealer_deck]),
inline=False)```
just put double **
wdym
i need it to be really big tho
not just bold
@scarlet tiger why isnt it working tho?
do you use discord.py?
yes
how do i do this, im kinda lost rn
try putting the value text between double **
i dont want that tho
its going to be bold, i need it to be big
like this
and not like this
get it ?
you said markdown not big text
Getting
[SSL: CERTIFICATE_VERIFY_FAILED]on Python 3 on OS X?
Navigate to yourApplications/Python 3.X/folder and double click theInstall Certificates.commandto fix this.
Happy coding!
oh this was easier than i thought xd, thanks
How is this bot doing it then
it looks like custom emojis
the numbers?
ye
np
I can't really disable n enable commands.. idk how to do that.
remove them from the tree then resync
they arent
Headers can be in embeds
Pretty sure you can use headings in embed descriptions too

but why didnt it work when i tried
.
It does perfectly for me
Are you putting it in a field name? Because it doesn't work there
double_down.add_field(name="Dealer deck", value=f"# {hand_value_dealer} -" + ",".join([str(c) for c in self.casino.dealer_deck]),
inline=False)```
nope im putting it in the value
Still does
Am i doing it right ?
|| (try it and see) ||
I can only try it every 12 hours.
also theres no point in printing a traceback so you dont need the “try except …” stuff
is this code generated by ai?
the string id 💀
since it's probably from an api that makes sense
oh. fair enough 🤷🏽♂️
All i wanted to know is whether if it's correctly implemented or not. Please help.
can apis not send back large/long numbers or smth
eg. a discord id is larger than a 32-bit integer
in python it doesn't matter but in js you'd have to use BigInt
ah ok 👍🏽
wait so how the fuck are the numbers so big
is it like milliseconds since the computing big bang
You can send test votes
how?
Guys how to get a story from this api
https://short-stories-api.onrender.com/
And display name as title and description of embed will be the story? I am new to APIs so pls help me
it should give you a JSON response so just interpret it like a dictionary
How can I do it then? Idk how to.
do you know what a dictionary is
it sends you a dictionary when you send it a get request
do you know how to get stuff from dictionaries
@viscid hornet I gave up typing when I read "not too much" 
😭🙏🏽
the rebirth of cancel 13
hes not even here
Bruh I'm here lol
@slate swan he got banned 💀
not you
who was that 
the one who asher said needed to take some duolingo lessons
most unhinged help channel ive ever seen
Anyways @spice seal, you wold need an aiohttp.ClientSession() and using that session you could make a GET request to the API which would return a Response object.
async with aiohttp.ClientSession() as session:
async with session.get("url") as response:
data = await response.json()
data in this meaning will be the JSON response from that API which is basically a python dictionary,
now having that data you could access elements / information that you need from it. Example:
some_json: dict[str, Any] = {
"some_stuff": [ "image.jpg", "new.gif" ],
"code": 200
}
print(some_json["code"]) # Will print value of the "code" key (200)
import discord
from discord.ext import commands
import requests
bot = commands.Bot(command_prefix='!',intents=discord.Intents.all(),case_insensitive=True)
@bot.command()
async def story(ctx):
# Make a request to the API
response = requests.get('https://short-stories-api.onrender.com/')
data = response.json()
# Assuming the API returns a list of stories and we're taking the first one
story = data[0]
# Create an embed with the title, description, and author's avatar as the thumbnail
embed = discord.Embed(title=story['title'], description=story['description'], color=0x00ff00)
embed.set_thumbnail(url=story['author_avatar'])
# Send the embed in the current channel
await ctx.send(embed=embed)
# Token and run goes here.```
This is still now working...
@slate swan
I assume you get KeyError, right?
I assume thats because you are accessing key that is against the rules? I don't really know since I would need to read scenarios in which JSONDecodeError happens. For sure the JSON key must be a string and you are accessing a key that is an int
u sure thats the right api endpoint ur hitting?
I a listening
dosent seem valid
This is the api
Wait a sec
I did it wrong
It's shortstories-api lol mb
@viscid hornet Could I give you a boost for the help you gave me with my bot?
@slate swan your right there is a key error.
Bro is a millionaire irl 💸💸
JSON keys are always strings
How can I fix it...
you would need to do something like data["film"] where "film" is a key name
boosts mean nothing ngl
nitro is where its at 🤑
{"_id":"5fce5054b9455b1cacf1ca59","title":"The Crow and The Pitcher","author":"Aesop's Fables","story":"In a spell of dry weather, when the Birds could find very little to drink, a thirsty Crow found a pitcher with a little water in it. But the pitcher was high and had a narrow neck, and no matter how he tried, the Crow could not reach the water. The poor thing felt as if he must die of thirst. Then an idea came to him. Picking up some small pebbles, he dropped them into the pitcher one by one. With each pebble the water rose a little higher until at last it was near enough so he could drink.","moral":"In a pinch a good use of our wits may help us out.","__v":0}
this is a sample data from the api
title story author moral here are the keys
import discord
from discord.ext import commands
import requests
intent=discord.Intents.all()
bot = commands.Bot(command_prefix='!',intents=intent,case_insensitive=True)
@bot.command()
async def story(ctx):
# Make a request to the API
response = requests.get('https://shortstories-api.onrender.com/')
if response.status_code == 200:
data = response.json()
# Check if the expected keys are in the data
if 'title' in data and 'description' in data and 'author_avatar' in data:
# Create an embed with the title, description, and author's avatar as the thumbnail
embed = discord.Embed(title=data['title'], description=data['description'], color=0x00ff00)
embed.set_thumbnail(url=data['author_avatar'])
# Send the embed in the current channel
await ctx.send(embed=embed)
else:
await ctx.send("The required data is missing from the API response.")
else:
await ctx.send("Failed to retrieve data from the API.")
This is the code,the code works but this is the correct error @slate swan
it should be data.keys() I think
nah dictionaries let you do key in dict
it implicitly is checking the key
log the response payload with pprint.pprint(data) and see if it matches your expectations
atleast take a look at the data ur receiving 💀
how to get this???
I guess just check len(guild.members)
th nd and so on 🥺
import discord
from discord.ext import commands
import requests
intents=discord.Intents.all()
bot = commands.Bot(command_prefix='!',intents=intents,case_insensitive=True)
@bot.command()
async def story(ctx):
# Make a request to the API
response = requests.get('https://shortstories-api.onrender.com/')
if response.status_code == 200:
stories = response.json()
# Check if the response is a list and not empty
if isinstance(stories, list) and stories:
# Access the first story in the list
story = stories[0]
# Check if the expected keys are in the story
if 'title' in story and 'description' in story and 'author_avatar' in story:
# Create an embed with the title, description, and author's avatar as the thumbnail
embed = discord.Embed(title=story['title'], description=story['description'], color=0x00ff00)
embed.set_thumbnail(url=story['author_avatar'])
# Send the embed in the current channel
await ctx.send(embed=embed)
else:
await ctx.send("The required data is missing from the story.")
else:
await ctx.send("The API response is not in the expected format or is empty.")
else:
await ctx.send("Failed to retrieve data from the API.")
Updated code @slate swan this is still not working...
If possible someone dm cuz I can't follow up with the chat
Dms are always open for help 🙂
I can't understand 😭
Can anyone update the code or help in detail
If possible pls dm
This gives you a dictionary (Whole JSON data from the response) , now you need to access the "story" key
I have done it in the embed tho right?
Right but this check is failing
since "stories" is an instance of dict (thats what I think atleast)
it is
also the dictionary dosent have any description or author_avatar
the code just looks ai generated at this point
also you should be using aiohttp instead of requests because requests is blocking
probably is ngl
what did i miss
secondth
thats what I said 

i aint see that
|| can i push it up so it swings back and forth like a grandfather clock ||
😂
ur weird

silence willy
I wonder if its a stupid idea to make a metaclass for creating Singletons
then subclassing the bot and passing it as a metaclass

just override __new__ ?
what the fuck is a singleton
it exists so there is only one instance of your class
or __call__ ig
only a single instance of a particular class is allowed
__call__ for class is when u call its instance again say a = A() now a() will invoke the __call__
so A()()?
yes
for some reasons it works tho 💀
u can instead override __new__ for this
!e
class Singleton:
__instance = None
def __new__(cls):
if not cls.__instance:
cls.__instance = super().__new__(cls)
return cls.__instance
s = Singleton()
print("Object created", s, id(s))
s1 = Singleton()
print("Object created", s1, id(s1))
@shrewd apex :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | Object created <__main__.Singleton object at 0x7f2075fdfcb0> 139777395260592
002 | Object created <__main__.Singleton object at 0x7f2075fdfcb0> 139777395260592
very discord bot related
well we used pydis bot to demonstrate sum stuff
!e
class SingleMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
class Test(metaclass=SingleMeta):
def __init__(self, a):
self.a = a
test1 = Test(2)
test2 = Test(5)
print(test1.a)
print(test2.a)
@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 2
002 | 2

yeah it would work if u define __call__ for the metaclass because this way the __call__ method is being invoked when ur doing Test()

!e
code
@marble rapids #bot-commands
ye?
this is a channel for bots support, use your commands there #bot-commands
i saw, i was just thinking this is like a bot for giving you python tests and you solving them with a solution
Sends docs on that?
!d discord.app_commands.CommandTree.remove_command
remove_command(command, /, *, guild=None, type=<AppCommandType.chat_input: 1>)```
Removes an application command from the tree.
This only removes the command locally – in order to sync the commands and remove them in the client, [`sync()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.sync) must be called.
Alr ty 😁

Real

Hello, newbie question here, is there a function in the discord API that allows a bot to ignore a message?
Wdym by ignore message?
I have it set up as "?" being the key for the bot to private message the user, then the bot deletes the users message in the channel. I'm stuck on that the bot deletes even messages with only a "?" and nothing else!
Do you know how to use if condition and startswith?
yes, a bit, I could send you the code if you'd like.
I did in the help channel and they sent me here so I thought I couldn't post code like that here!
if user_message.startswith('?'):
user_message = user_message[1:]
try:
response: str = get_response(user_message)
await message.author.send(response)
await message.delete()
except:
IndexError
Forbidden(print('Forbidden'))
NotFound(print('Not Found'))```
if user_message.startswith('?'):
user_message = user_message[1:]
try:
response: str = get_response(user_message)
await message.author.send(response)
if not message.startswith("?"):
await message.delete()
except:
IndexError
Forbidden(print('Forbidden'))
NotFound(print('Not Found'))
Thanks, I’ll give that a shot!
you know that this except block is not right
I do not, I’m not very experienced yet, especially not with try/except
!except
A key part of the Python philosophy is to ask for forgiveness, not permission. This means that it's okay to write code that may produce an error, as long as you specify how that error should be handled. Code written this way is readable and resilient.
try:
number = int(user_input)
except ValueError:
print("failed to convert user_input to a number. setting number to 0.")
number = 0
You should always specify the exception type if it is possible to do so, and your try block should be as short as possible. Attempting to handle broad categories of unexpected exceptions can silently hide serious problems.
try:
number = int(user_input)
item = some_list[number]
except:
print("An exception was raised, but we have no idea if it was a ValueError or an IndexError.")
For more information about exception handling, see the official Python docs, or watch Corey Schafer's video on exception handling.
this is how you catch errors
except:
IndexError
Forbidden(print('Forbidden'))
NotFound(print('Not Found'))
-> ```py
except IndexError:
# do something
except Forbidden:
print('Forbidden')
...
or if you want to do same thing for couple errors
```py
except (Forbidden, NotFound):
print("Error")
also if you want to know what error was actually caught you can save it in a variable like this ```py
except (Forbidden, NotFound) as e:
print(e)
Ooooh! That actually makes it very clear! Thanks a bunch!

Hi where can I create a bot?
At your home
Rude
Dumb question Developer portal
Ik that but what about the codes
Hey hey don’t be rude
Can you help me?
Language and library
Python and OOP concept
Here is a full guide https://fallendeity.github.io/discord.py-masterclass/
A hands-on guide to Discord.py
Thanks you 🙏
I just want to create a bot like ticket
But I have no idea about how I will do it
That'd be little complicated if you're starting now
Learning will take time
I mean em if I type !help the bot sends a msg do you know how to do that?
That’s the default help command
It’s built in
You can read this for better understanding
https://guide.pycord.dev/introduction
Pycord Guide is a complete guide for Pycord. Learn how to create Discord Bots today!
Overwrite discord.py's help command to implement custom functionality
This is a different library
But when I do !help and the message it send am I able to edit?
I said this page only it covers basic requirements of python knowledge
See Robin’s message for that
Okay
You can overwrite it with your own custom made help command
But as said I have no idea how py works so i'ma just copy some tutorials on YouTube.
That will only give you problems Learn Python before making a discord bot
Tutorials will help ....
Or no?
YouTube is a cesspit where people make things up and nobody checks them on it. You should not use it to learn
Then how can I learn basics?
If it helps, I learned Python on YouTube
🤨
We can disagree on this, but there is an insane amount of bad practice and misinformation with no accountability measures or peer review
Search on YouTube, but you must practice a lot to be able to learn this way. I learned like this
I personally recommend you get comfortable with reading articles, and use those from reputable sources that are reviewed to educational standards
If you only watch videos to satisfy your attention span, you are severely limiting yourself as most of the best content is written as that is the best medium for this information
I mean I don't want to be an expert I just want to know some basics like make commands and it sends a reply message
That's all I need
You won't be able to do that yourself unless you understand the concepts at play
For example
If youre just looking to copy paste something that someone else wrote without understanding it, that's a whole other thing
Ye
Question are there any codes on Google that I can copy paste to py?
Not all people learn the same. But if you are looking for a quick way go to YouTube.
Okay
And a lot of people who think they have learned are unaware of the depths of the bad practices they've ingrained in themselves by watching some rando making stuff up in his basement for YouTube clicks
If you only watch clips you will do poorly. Luckily in my community there are videos of more than 15 hours that teach everything. I speak Spanish 😅
could not get this to work, however this seems to work
if user_message.startswith('?'):
user_message = user_message[1:]
if len(user_message) <= 0:
return
try:
response: str = get_response(user_message)
await message.author.send(response)
await message.delete()
I'd like to see the full code
Sure, DM or here?
You won't be able to do it with just basics discordpy requires much more knowledge of language
Yt ..?
Especially this will need a good understanding of OOP concept
!code
Here
we have a pastebin for this 👍🏽
😭🙏🏽
I wouldn't recommend YT as it gets outdated in no time
K
!blocking | you should use aiohttp instead of requests and this explains why
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
- The standard async library -
asyncio - Asynchronous web requests -
aiohttp - Talking to PostgreSQL asynchronously -
asyncpg - MongoDB interactions asynchronously -
motor - Check out this list for even more!
Stop it Axo 🤣
also what is your code supposed to do?
are you reading input like a command but with a message listener
🤫
That's complicated tho why don't you use dpy library instead
You need it
need what
wdym?
It's supposed to delete commands that the user sends as private but not when they only send a "?"
Emoji on yourself
😭🤦🏽♂️
so if i wrote “?sandwich” that can stay but if i wrote “sandwich” then that gets deleted?
no, if you wrote "?sandwich" it gets deleted and you get a private message with either a command output or an error message, "sandwich" would stay and do nothing
wait i think i misunderstood. can you give me an example of what you want to happen?
ok hold on
so send a user the error if they run a command and something goes wrong. did i get that right?
ok wait im overcomplicating. basically just send the user command output
I'm assuming
@client.event
async def on_message(message):
if not message.startswith("?"):
await message.delete()
the "?" operator should make the bot send you a private message instead of output in the channel
Isn't it same?
but its supposed to do something before deleting, im guessing?
Something like?
but it should not delete "?" if thats all the user sends
yes, if its more then a single "?"
you should probably use commands for this. iirc nothing happens if its just the prefix
I had the code delete the "?" even tho the user should be allowed to send that. I have fixed that now!
nice 👍🏽. you should use commands for this and end each command with a delete unless theres a better way to do that for all commands
So i make the message deletion happen in the command?
yes, pretty much
have you used commands before?
I see where you are coming from, however I don't see how I can make it work since I want to have "!" as public commands
Wouldn't that make it 2x the code?
no not necessarily
could override ctx.send and check the prefix
wait this got more complicated
tell me more 
Imma head to bed, thanks for the input guys!
alr np 👌
i wouldve said just use a message listener and check if a message starts with a certain prefix and delete the message that way but i forgot commands have output 🤦🏽♂️
IMO on_command_completion would probably be more suitable
had no idea that existed
did you do work on dpy? you know a ton abt it
class MyContext(commands.Context)
async def send(self, *args: Any, **kwargs: Any) -> discord.Message:
if self.clean_prefix == "?":
return await self.author.send(*args, **kwargs)
else:
return await super().send(*args, **kwargs)
``` ?
If I'm understanding the desired functionality correctly
Although you'd lose typing info on the parameters, but could probably fix that
how would you use that in a command?
would you typehint to your new context class or make an instance of it already or what?
examples/custom_context.py lines 27 to 32
class MyBot(commands.Bot):
async def get_context(self, message, *, cls=MyContext):
# when you override this method, you pass your new Context
# subclass to the super() method, which tells the bot to
# use the new MyContext class
return await super().get_context(message, cls=cls)```
@viscid hornet
what
oh woah thanks willi
app command
but you need bot tree also
and dont forget to make a prefix command for syncing
nvm imma fix it somehow
@crisp glacier
import discord
from discord.ext import commands
class Slash(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name="ping", description="Prueba el comando ping")
async def ping(self, interaction: discord.Interaction):
await interaction.response.send_message("pong!")
@commands.command()
async def syncup(self, ctx):
await self.bot.sync()
await ctx.send("Listo")
async def setup(bot):
await bot.add_cog(Slash(bot))```
?
Define within if not type checking ez
in a cog you use app_cmds.cmd, but in your main file you use bot.tree.cmd
and how do I solve it?
solve what
#discord-bots message - for more reference
solve what
yeah im sure im not much help lmao
shut up then 🗣️🗣️ || only joking ||
what are you trying to solve tho

🥺
@viscid hornet
bot.py: py @bot.tree.command() async def test(interaction): await interaction.response.send_message("hello")
cog: ```py
import discord
from discord.ext import commands
from discord import app_commands
class Slash(commands.Cog):
def init(self, bot):
self.bot = bot
@app_commands.command(name = 'testt', description = '...')
async def test(self, interaction):
await interaction.response.send_message("hello")
@commands.command()
async def syncup(self, ctx):
await self.bot.sync()
await ctx.send("Listo")
async def setup(bot):
await bot.add_cog(Slash(bot))```
ok sorry
@bot.event
async def on_dbl_vote(data):
try:
print("User voted!")
user_id = data["user"]
bot_id = data["bot"]
print(f"User ID: {user_id}, Bot ID: {bot_id}")
if bot_id == '1182613510895697931': # Make sure to replace with your bot's actual ID
print("Bot ID matches!")
# Logic to add reward to the user's account/profile
#reward_user(user_id, reward)
# Optionally, send a message to the user (you would need the channel or user object to do this)
user = await bot.fetch_user(user_id)
print("Fetching user...")
await user.send("Thank you for voting for Sparkle Wonder! This is a test vote :c")
print("Sent DM to user!")
except Exception as e:
print("An error occurred:")
print(e)
traceback.print_exc()
raise
I've tested the code but it didnt work. None of the print statements were shown in console. I don't quite understand what i did wrong, please help me thxs.

did ai do this
btw it is a topgg vote tracker
yeah partially helped me fixed it up a bit

i really wanted to learn
yeah its all good
yo im back
hey
did you check out the test webhook feature the guy mentioned?
i dont have webook url/ auth token?
bro lives in the help channels
yeah. also its bot.tree.sync
no the thing that lets you test if a vote has been made
i said i tested the vote through actually voting
I put it as a prefix /
and it didnt work as intended
?
as in there is no print messages shown
ngl i think this comes as this not being a valid event
not advised
gay son or thot daughter
bro fuck off 😭
ive looked at the topgg docs and i dont see other valid ways to implement this?

yeah doesnt exist
check github and lmk what you find
😭
!pypi dblpy
A simple API wrapper for top.gg written in Python.
Released on <t:1599585545:D>.
oh
thats not correct either
what isnt?
well on dblpy i think i found what you’re looking for
is it topgg or topggpy or dbl or dblpy... which is it?
https://pypi.org/project/dblpy/ - check the “using webhook” section
topgg and dbl are both websites - their py alternates are wrappers for interacting with their respective APIs
then how do i get webhook url and pass/auth?
dont you just need an API key?
no?
the wrapper takes care of the rest for you, would it not?
ill have a look at it
You know topgg and dbl are the same site right?
wait what
i swear they were different 😭
Dbl aka discordbotlist was the old site name before it became topgg
You are probably thinking of discord.bots.gg or discordboats
how come its a separate site and they didnt depreciate it?
seo?
Wait NVM I'm the dumb one
wait so if they’re the same website then how come they need different modules for each
had my brain melting
Did someone else buy the old domain 🤔
https://topggpy.readthedocs.io/en/stable/index.html
this is the correct one?
yeah looks like it
if i install topggpy, and use this one. what do i import?
i tried import topggpy, import topgg and both didnt work
you just need a client instance or whatever, smth like that, and you should be good to go
and says module not found error
check the docs
should say what to import
there is none?
you just sent me a link
ive read the docs
ok so what does everything start with
should say X_name.Y_something
whats “X_name” in this case?
topgg?
^
so thats what you’re importing
what did you pip install?
A simple API wrapper for Top.gg written in Python.
Released on <t:1636189849:D>.
whats in it
@viscid hornet The slash does not work nor does it respond to the syncs command
whats wrong w it
!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.
always start with this
getting a 404 error 10015 on interaction for pressing a button 
need more info than an error code 
!traceback for more reference
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 a decently long chain of u.i embeds and components put together, on the 3rd component press i get the error code on:
File "C:\Users\*****\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\*****\Desktop\melee-python\cogs\locations.py", line 216, in handle_dungeon_inputs
await interaction.followup.edit_message(interaction.message.id, embed=difficulty_embed, components=components)
File "C:\Users\*****\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 1467, in edit_message
data = await adapter.edit_webhook_message(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\*****\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 191, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook




