#discord-bots
1 messages · Page 353 of 1
did you add the cog with the bot attr?
async def setup(bot):
await bot.add_cog(YourCog(bot))```
command really doesnt work, did you find any problems?
im looking for hours, and didnt find anything
check the db
use this to open your .sql file
and screenshot the contents
no
pretty much all free vps sites have drawbacks that will force you to perform tradeoffs
they do want money after all
how else is their business gonna stay afloat
i have a laptop
Yep! I did but the error continues
@viscid hornet any chance you can help me to achive what im trying to do and not do channel.send?
can anyone help me im getting this error
raise InteractionResponded(self._parent) discord.errors.InteractionResponded: This interaction has already been responded to before
class SetEmail(discord.ui.Modal, title='Set Email'):
inputemail = discord.ui.TextInput(style=discord.TextStyle.short, required=True, label="Email Address", placeholder='Enter your email address', min_length=1, max_length=100)
email_set_event = asyncio.Event()
async def on_submit(self, interaction: discord.Interaction):
userid = interaction.user.id
email = self.inputemail.value
data = read_json("users")
for user in data['users']:
if user['id'] == userid:
user['email'] = email
write_json(data, "users")
await interaction.response.edit_message(content="Email set", view=None)
self.email_set_event.set()
return
else:
await interaction.response.edit_message(content="Error setting email", view=None)
return
@app_commands.command(name="buy", description="Buy gifting credits")
async def buy(self, interaction: discord.Interaction):
class PaymentMethodSelect(discord.ui.Select):
def __init__(self):
super().__init__(
placeholder="Payment Method",
min_values=1,
max_values=1,
options=[
discord.SelectOption(label="Test")
],)
async def callback(self, interaction: discord.Interaction):
selected_method = self.values[0]
if selected_method == "Test":
if not check_email(interaction.user.id):
await interaction.response.send_modal(SetEmail())
await SetEmail.email_set_event.wait()
embed = discord.Embed(title="Test Payment", description="Click the button below to pay with Test", color=discord.Color.dark_theme())
await interaction.response.edit_message(embed=embed, view=None)
return
class PaymentMethodView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.add_item(PaymentMethodSelect())
embed = discord.Embed(title="Payment Method", description="Select a payment method", color=discord.Color.dark_theme())
await interaction.response.send_message(embed=embed, view=PaymentMethodView())```
You're responding to the interaction twice. First you're sending a modal, and then you're editing a message
hm can you help me on fixing it?
You can use a followup if you need to edit the message after the modal has been responded to
How do I let the bot wait until someone replies to the original message the bot sent. I’m currently using context.bot.wait_for(‘message’, check = check) but it is only doing it for every message sent. So if people actively talk the bot will think a response has been sent
I also have a timeout of 25.0
I'm trying to make a discord Automod that deletes curse words. The code I have linked below accesses a file called "bad_words.txt" which contains each word on a separate line. The bot can see these words and sends list of them all in the console but it just deletes any messages the person sends? How can I get it so it deletes just the words from the file?
( I suck at coding so I use tutorials to help )
from discord.ext import commands
intents = discord.Intents.default()
intents.messages = True
intents.guilds = True
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
def load_bad_words():
with open('bad_words.txt', 'r') as file:
return [word.strip().lower() for word in file.readlines()]
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
@bot.event
async def on_message(message):
if message.author.bot:
return
bad_words = load_bad_words()
for word in bad_words:
if word in message.content.lower():
await message.delete()
await message.author.send("Your message containing a bad word has been deleted.")
break
await bot.process_commands(message)
bot.run('YOUR_BOT_TOKEN') ```
I ofc won't put my actual token. It doesn't give me a specific error but just deletes any message sent rather than just messages containing the bad words
What does your check look like?
return message.author == context.author and message.channel == context.channel
I want to make it so the bot only responds if the user replies to the original message the bot sent
You might have an empty line or something like that in your file which is causing it to trigger on every message
!d discord.Message.reference check this too
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.
Oh wow thank you, that was nice and straight forward :)
Hmm message.reference.message_id NoneTyoe object has no attribute message_id
Fixed that issue but now I have this issue which I have no clue how that is working
The second embed replies to the first one
May if found this issue
@fading marlin I keep getting the error
and now when there is a email im getting Unknown Webhook
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
idk why it wouldnt let me copy the error
@bot.tree.command(name="register", description="Register your account")
async def register(interaction: discord.Interaction):
user = interaction.user
cn = getNextEmptyRow(wks2)
wks2.update_cell(cn, 1, user.name)
wks2.update_cell(cn, 2, 0)
embed = discord.Embed(title='Account Created', color=e_color, timestamp=datetime.now(), description="""
You have successfully registered your account.
Thank you for registering.
""")
await interaction.response.send_message(embed=embed, ephemeral=True)```
idk if im tweakin like ive made thousands of commands before
https://paste.pythondiscord.com/UWFA
ive been trying to figure out why the send level up message function isnt working for hours, can some1 pls help me before i lose my sanity
im literally dying rn
@potent helm i remember your smart maybe you can help?
that's literally what you're waiting for. on_message is called every time a new message is sent that the bot can see
Its not giving me any errors
anything visual that can be called an error?
like anything on the discord side?
the lack of a message ;-;
also something i see now which is still sorta important but not your issue
use sanitisation for your inputs
thats the data tables for example
? is for sqlite which i'm guessing is your db language
postgresql
ah alright
get an async version of postgres
the normal version is blocking
all the other async functions work
just the one 2 send the level up message doesnt
would the db deploy logs be helpful?
yeah i'd say so
wait delete it nvm i dont need it
i found your error
what is it?
.get_channel() returns either a Channel or None
so if it can't find the channel, it basically just returns the command and cuts it off there
!d discord.Guild.get_channel
get_channel(channel_id, /)```
Returns a channel with the given ID.
Note
This does *not* search for threads.
Changed in version 2.0: `channel_id` parameter is now positional-only.
so how do i fix it?
firstly, add an else statement to print that it can't find the channel
then rerun the code to make sure that's the error
it already has that
that's if you don't have a guild
i said add it if there's no channel
oh
!d discord.Guild.fetch_channel
k, the bot is launching with the changes ill let you know what happens in a minute

bro is single handedly resolving every issue 😭
I am not a fan of the new tag
its not even printing
dies
wait, could it be because its defining guild as ctx.guild, its recieving guild when called, but its not set to take guild when run?
wdym
shouldnt do
k...
i have no other ideas 💀
self and ctx parameters are self-fulfilling iirc....
oof
stupid suggestion:
maybe try to comment out the db code for now and call the func just to make sure whats causing the issues
i did that already 🙂
ah okay, and the bot did what you were expecting it to?
ye
neat, im also gonna assume you "wrapped" the db statements with prints to see where it messes up
uhm no...
the prints dont... well.. print
very interesting
yes
okok hmmm
1 message = 1 xp, 10xp = 1 level, the leveling system works (ik cause when i call view_level its right)
since im not all too familiar with sql or the like i wont be of much help
im mid with postgresql
something feels fishy
im mid with sqlite LMAO (i just use json or just ignore a db)
lol
i suck with json
ah i see, well can you send me your code so i can look @ it on pc
||use a db. json is hot shit
||
it has some documentation
|| yes it indeed is but i dont plan on deploying my bot in prod or anything so its good for apps i use personally ||
||still good to use a db but to each their own
||
if its helpful im hosting on railway.app from github
this is the level_module in cogs right?
si
yeah i really dont know either, its a skill issue from me dude
lol
this is one of the times i wish there where errors so at least i could fix them
rightt
actually imma go left cause something with this code aint right 
i cloned ur bot so i can meditate on the code
kk

(also if it works let us know 🦾 )
how do i update it? dm me any further responses cause imma be afk and i dont wanna miss em
pip install -U discord i believe is the command
C:\users\user> pip install -U discord```
that doesnt work, theres a requirements file instead
also, i remember that the code worked 4 hours ago, but between then and now there was a discord update
@viscid hornet sorry for ping but ur in here actively
i forgot to ping on reply 💀
do any of your functions use interaction?
wdym?
whats the new version of discord
so update the version
lemme check
should be 2.4
2.4.0?
Unknown interaction only happens when you do interaction.followup.whatever()
or am i tweaking

i definitely dont have that in my code
what da hail
i can send u the whole file in dms
im getting mixed signals lol
the version you have is 1.7.3, uninstall it and reinstall the latest one
but which one is the latest one lmao
this one
ah ok
pastebins exist for a reason
oh yeah
removing all the other row stuff worked completely fine
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
2024-04-18 03:52:06 INFO discord.client logging in using static token
2024-04-18 03:52:12 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 010b5def581cd10add8b4bc0947b3be1).
Successfully logged in as Echo#4570
main.py:29: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(messageModule(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
main.py:30: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(memberModule(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
main.py:31: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(weatherModule(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
main.py:32: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(channelModule(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
main.py:33: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(HelpModule(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
main.py:34: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(ModerationModule(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
main.py:35: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(reminderModule(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
main.py:36: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(levelModule(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
...
use patebin for that
not an issue
1 sec lemme get the github up again
well at least im getting something now 🙂
did you make your setup function async?
It is
alright
i think it is
@bot.event
async def on_ready():
create_database()
print('Successfully logged in as {0.user}'.format(bot))
await bot.add_cog(messageModule(bot))
await bot.add_cog(memberModule(bot))
await bot.add_cog(weatherModule(bot))
await bot.add_cog(channelModule(bot))
await bot.add_cog(HelpModule(bot))
await bot.add_cog(ModerationModule(bot))
await bot.add_cog(reminderModule(bot))
await bot.add_cog(levelModule(bot))
await bot.change_presence(status=discord.Status.online, activity=discord.Game('Starting...'))
await asyncio.sleep(5)
status_cycle = cycle(variables)
while True:
current_status = next(status_cycle)
await bot.change_presence(status=discord.Status.online, activity=current_status)
random_delay = random.uniform(30, 600)
await asyncio.sleep(random_delay)
bot_token = os.environ.get('TOKEN')
bot.run(bot_token)
no in each cog
the launch file is smol
async def setup(bot):
await bot.add_cog(...(bot))
no i didnt... is that important?
No, but that's how people usually make cogs; in an extension file
yeah
🍞 im dumb
build 2.001
2 because i updated the discord requirements file so its pretty much a different system
unforunately the message sendy thingy still aint workin
Idk what the message sends thingy is
someone please help error is in the register command
You didn't respond to the interaction in time (3 seconds), so it expires
its not even a long command what
Interaction not found. Can you explain a bit more? From what I see it seems like you’re trying to respond to an interaction outside of the period it allows
i ran it through an ai to see if its all up to date and erm....
You may want to defer the interaction
Things you're doing is probably taking a long time 🤷
i just want the command to work and send the embed
to make it work you defer
You'd want to call the interaction.response.defer method to defer the interaction at the top and respond instead with interaction.followup
how can i do so
i remember saying that about my help command
Look up defer in the docs
On my phone so I cbf writing code
ok ty
touch grass
🐦 burb 🙂
If I recall its interaction.response.defer()
And then it’s interaction.followup.send()
https://paste.pythondiscord.com/UWFA
thats the code for the message sendy thing
Interactions have 3 seconds to complete normally and defer extends to 10 minutes
3 seconds... sounds like my attention span
2nd function?
ye
Is it meant to be inside the other function?
Paste error or you didn’t see the indent?
istg if thats been the problem the entire time....
The 2nd function is inside the first
in my code it isnt...
are there any errors raised?
See how the 2nd highlight is more right?
That tells python it’s inside the first function
its probably a paste error
I hope so
just incase it is a paste error thats the source
yep paste error
The spaces in front of the first line is removed by the message storage in most cases
Discord also does that
:P
https://paste.pythondiscord.com/B3HA
thats the entire cog
you didn't answer
I’m gonna ignore indent errors
no errors
add print statements in different places to see where it stops
i did 🙂
and what'd u infer
Remove the try. It won’t catch every error in that code block
Ya
Try catch doesn’t output every error
You want to ideally use it for as little a codeblock as possible
And only in instances where there’s a possibility it could fail
Not as an entire wrapper for a block of code
Alright time to go stumble back to my car . Back in 15 . If I don’t return in 30 assume the best
still no errors
me fr
its not printing any of the check statements...
its not printing first check passed?
nope
that means
if new_level > current_level:```
this isnt being met
try printing out both the variables
before the if statement of course
k
when i use Echo_view_level the levels are updating properly.... so am i just dumb or...
we shall see
i think i got your error
507
508
still ill wait to see what this resulted in
well
https://paste.pythondiscord.com/NBIA
thats the full log
<class 'int'>
<class 'int'>
507 is current level or?
You may need to do some test variables to ensure it works lol
Write two new variables before the check overwriting the original and set them to something that will trigger the check
?
if 507 is current level, 508 is new level, and both are integers. theres absolutely no way the print("first check") isnt outputting...
hmmmmm
Which is why you need to put fake levels in for now so it forces to run
what they mean is
new_level = 1000
current_level = 10
if new_level > current_level:
...```
Yes
OH
This forces it to run
wait a sec.... when i do view_level it returns level_row = self.ldb_cursor.fetchone()
prev_level = level_row[0] if level_row else 0
return int(prev_level)
not the new level
should be fine
but thats the command ive been using to check if the leveling system is working
and this is fine iirc
@frigid estuary basically to properly debug you first need to see where your code stops. So put print statements everywhere and anywhere. If you reach a point where it doesn’t work as intended you can easily trace back the last time it did work
↓↑↨→←
oh...
There is probably better ways to do it
But I like this way
It forces me to read my code
nah print statements is the best way
Also don’t be afraid to read your code out loud
Saying what it does as you go.
And what you expect to see etc
This helps you process what is actually happening
Like you will read it out loud and go “wait. wtf. No that’s not right”
Or realise you’re saying the same thing 5 times
Also invest in a rubber duck
ok... lol
i feel like im about to fall asleep ngl... but i wanna get this working
need
Sometimes I use my private discord servers to rubber duck
Like I don’t even need help I just need to process my thoughts
why is total_xp defined twice hmmmmmmmm
oh ye
as gnome said, this is like
total_xp = xporwhatever
total_xp = total_xp + increment```
Could shorten to one line if needed
yes but readability 🫡
Fuck readability!
i keep looking at these and feel like im missing smthn
Yes
the only thing python devs have going for them is readability 😭
but whyyy isnt the first print statement being called
Unless ctx is used in the send level up message then you need to define it
If you don’t properly assign the params when you call the function python will just assign the values in order
So ctx is actually user id in this case
so if ctx isnt assigned then erm ugh
You aren’t assigning ctx at all
just have another arg for guild_id
Normally discordpy does it but since this isn’t a command you need to pass it through
how do i define it, i cant have the level_update define it
when u r calling the function from the message listener u can pass ctx and get everything
Oh to be young and inexperienced
sorry im still looking at ur code, i was setting up a postgresql db to try and recreate ur issue but i forgot the password i used to set it up 😭
I remember when I was as inexperienced as @frigid estuary
Now my issues are more advanced lol and often so unique and niche that not even chatgpt can help lol
i was suffering from a skill issue while trying to help them so thanks 🦾
It is currently 3pm and I haven’t heard a car honk in 10 minutes
Almost forgot I was sat in a car park in the middle of the city
uhm how
trust me im great at front end but back end..... meh
Same here but in reverse lol
lol\
^^ me too
Ooo I hear a siren!
mb
Who wants to take the over and under on when the next car toot will be?
I say 2 minutes
Timer starting now
Not even
if new_level > current_level:
print("first check passed")
# Send level-up message if the user leveled up
await self.send_level_up_message(guild, user_id, level=new_level)
i need to define guild 😮
1 minute 40!
also why do i feel like the inequality arrow is whats messing it up
It’s not
same
Can someone who understand what I am saying show him an example?
He is calling the function correct but he is assigning “user id” to the “guild” parameter and the “user id” param remains empty. The user id doesn’t have get channel
Your function takes 3 params and you only send two
why isnt it giving me an error saying that then 😮
Or to change it up. You need three keys to open this door and you have only used two
take the hinges off the door
@potent helm
bro was online last time i pinged him and went idle without even looking 😭
if new_level > current_level:
guild = ctx.guild
print("first check passed")
# Send level-up message if the user leveled up
await self.send_level_up_message(guild, user_id, level=new_level)
tronk
I should hear another honk within 3 minutes
async def update_user_xp(self, user_id, xp_increment):
# Update user's XP in the leveling database
self.ldb_cursor.execute('''
INSERT INTO user_xp (user_id, xp)
VALUES (%s, %s)
ON CONFLICT (user_id)
DO UPDATE SET xp = user_xp.xp + EXCLUDED.xp
''', (user_id, xp_increment))
self.ldb_connection.commit()
await self.update_level(user_id, xp_increment)
this seems right
i think i have an idea
lol
so... the event on_message can pass ctx... and i can use ctx to get the guild... so why not pass ctx from on message to the function
Idk give it a shot
i am tring to send an image but i am getting a no response for this line (py-cord)
await ctx.respond(file=discord.File(fp=f"test.png"))
any error?
and is test.png in the same folder you're running the bot in
yes.
try catching the error
okk
Can you show the full code of the command?
you're probably trying to respond to a dead interaction
MY IDEA WORKED
i can die in peace...
i mean sleep.... i can sleep in peace
that isn't the full command
tysm for helping
tysm for helping
np, even though i didnt do much glad to see it work out in the end
happy coding 🦾
thnx 🙂
the test image is being saved each time i run the command
what are you trying to do?
put a filter on avatar
what type of filter
i can finally uninstall postgresql 😭
an API probably exists already for what you want to do
that's a different image...
but that's not the problem here
this works and the image is being saved
i can't use API in everything... i wanna do it myself
Lmao
Hello i want make my bot 24h i use python
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.
As the bot said. Use a hosting service
It costs money but that’s the price to pay
Alternatively you can host it yourself on a computer and never turn it off
like you can use a spare android phone and install termux and a few other things on it clone the bot and boom ur good
?
Its Client
guys how can we mention a slash command in a message in disnake?
Me when case sensitivity 😔
tbh why is he replacing the bot after defining commands above it
some bots have commands here, what is this called?
Context menu
you got a guide for this? are they added through the api wrapper or through the dev portal?
Can't find it if i search for "context" in disnake docs (maybe they don't have it?)
@discord.app_commands.context_menu(*, name=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command context menu from a regular function.
This function must have a signature of [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) as its first parameter and taking either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member), [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User), or [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message), or a [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union) of `Member` and `User` as its second parameter.
Examples...
Average discord.py W
disnake doesn't have it?
I don't know other libraries besides discord.py :P
unfortunate :(
Maybe try searching something like message command?
class disnake.APIMessageCommand```
A message context menu command returned by the API.
New in version 2.4.
thank you
🐈
iirc the format is </cmd name:id>, where ID is the slash command's ID
with dpy its relatively easy to get these IDs yourself with a custom tree (see my gist), but for disnake i couldn't find any obvious way to access it, and their feature request for properly supporting slash command mentions is still pending DisnakeDev/disnake#631
im so confused with the music cog, are there any tips, i just want it to be basic nothing too complicated, something i can use for my own self
or my gist which is better
actually tho what did you change from soheab's? I hate gists don't keep commit history so I can't diff it :c
"commit history" as in like being able to fork and compare gists, rather than just the revisions tab? either way i think it was mainly just refactoring and simplifying the API (and disregarding 3.8/3.9 compatibility)
That makes sense
And yeah that's what I mean. When forking a gist it doesn't keep the revisions
currently on disnake the only way is by fetching the list of global commands / fetching the global command using
disnake.ext.commands.Bot.fetch_global_commands
or
disnake.ext.commands.Bot.fetch_global_command
they either return a list of objects or an object from which you can access the .id attribute
obviusly the most easy way to do this currently would be by manually retrievieng all the ids instead of fetching them every time
ah ok, can it be retrieved during their auto sync? since the bulk overwrite commands endpoint returns the same list of commands
mh this is a bit difficult to do for normal users who are not familiar with the internal codebase, the price for auto sync (so abstraction) is that the user lose a little bit of help to sync commands manually, but ig it should be possible by fucking a little bit with internals (mainly using HTTPClient methods and other things)
auto-sync can be disabled by passing the appropriate flags when creating a Bot instance, so you need to create from scratch your own logic so it is possible but it's a very advanced thing
probably learn to use pillow
it was correct code, my internet connection was the problem.
i am learning that's why i asked for help here but was told to use API instead
But if you process your images through pillow directly, Your bot might die.
#media-processing would be appropriate for questions specific to pillow, but as for integrating them into dpy, you'll want to make sure you're doing your image manipulation in a separate thread to avoid blocking your bot's event loop, and saving to an in-memory file to avoid concurrently writing to the same file on disk, e.g. ```py
import asyncio, io
def make_praise_image(image_data: bytes) -> io.BytesIO:
... # do some pillow magic
f = io.BytesIO()
image.save(f, format="png")
f.seek(0)
return f
@bot.command()
async def praise(ctx, user: discord.Member = commands.Author):
image_data = await user.display_avatar.read()
image_file = await asyncio.to_thread(make_praise_image, image_data)
file = discord.File(image_file, filename="praised.png")
await ctx.send(file=file)``` api reference: BytesIO, Image.save(), asyncio.to_thread()
hi i need help with command in discord bot sending on chanel "There was a problem processing your request. Please try again later."
@bot.command()
async def ltcc(ctx, transaction_id: str):
token = "95b43bad72c14cde9b9eb521d0b8a14e"
api_url = f"https://api.blockcypher.com/v1/ltc/main/txs/{transaction_id}?token={token}"
currency_api_url = "https://api.coingecko.com/api/v3/simple/price?ids=litecoin&vs_currencies=eur"
try:
response = requests.get(api_url)
data = response.json()
if response.status_code != 200:
error_message = f"Error communicating with LTC server (status: {response.status_code})"
print(error_message)
return
total_value_ltc = sum([output['value'] for output in data['outputs']]) / 100000000
currency_response = requests.get(currency_api_url)
currency_data = currency_response.json()
if currency_response.status_code != 200:
error_message = f"Error getting currency rates (status: {response.status_code})"
print(error_message)
return
ltc_to_eur = currency_data['litecoin']['eur']
total_value_eur = total_value_ltc * ltc_to_eur
transaction_date = datetime.fromisoformat(data['received']).strftime('%Y-%m-%d %H:%M:%S')
embed = discord.Embed(title=f"LTC Transaction Details (ID: {transaction_id})", color=discord.Color.blue())
embed.set_thumbnail(url="https://cryptologos.cc/logos/litecoin-ltc-logo.png")
embed.add_field(name=":link: Hash", value=data['hash'], inline=False)
embed.add_field(name=":white_check_mark: Confirmations", value=data['confirmations'], inline=True)
embed.add_field(name=":calendar: Transaction Date", value=transaction_date, inline=True)
embed.add_field(name=":inbox_tray: Inputs", value=len(data['inputs']), inline=True)
embed.add_field(name=":outbox_tray: Outputs", value=len(data['outputs']), inline=True)
embed.add_field(name=":moneybag: Total Value (LTC)", value=f"{total_value_ltc:.8f} LTC", inline=False)
embed.add_field(name=":euro: Total Value (EUR)", value=f"{total_value_eur:.2f} EUR", inline=False)
await ctx.send(embed=embed)
except Exception as e:
print(f"An unexpected error occurred: {e}")
pass
You shouldn't use requests, it is blocking
What exactly is outputted to your channel btw?
how should I make it work
this
"There was a problem processing your request. Please try again later."
ok. in your try except, you're going to have to make it output the full error:
import traceback
```then```py
except Exception as e:
traceback.print_exception(e)
right now what you're asking is pretty inactionable, as you're not being very specific.
I can't express myself in detail, I don't know much about it, but I just want the bot not to send this error and it still does it after this change, even though what the command is supposed to do works, but it sends this fucking error
||.format_exception(e) with py formatting
||
thanks i will do that
im starting to reach a breaking point, i need someone willing to review my project x3 i think i'm doing bad practices on some stuffs yet i dont know where
class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.
This object must be inherited to create a modal popup window within discord.
New in version 2.0.
Examples...
reminds me how weird it is to have {self.name} in that doc example
for a while i thought dpy did some magic to replace text inputs with strings, until i realized it was just returning .value from its __str__ method
thats the one, thanks
insane strat
Hi i have a problem when i have my discord bot and my flask website running at the same time im getting this error Timeout context manager should be used inside a task when i go on one of my apis and i want it to send a dm to a user when i go onto the api but I get that error
heres the code
@app.route('/api', methods=['GET', 'POST'])
def api():
data = request.json
asyncio.run(start_api(data))
return 'Our server has received your api.', 200
async def start_api(data):
try:
if data['status'] == "COMPLETED":
pass
else:
return
discordid = data['discordid']
discordid = int(discordid)
try:
user = await bot.fetch_user(discordid)
if not user:
return
else:
user.send("You have been given credits")
return
except Exception as e:
print(f"Error in start_api: {e}")
except Exception as e:
print(f"Error in start_sellapp: {e}")```
How can I get a discord.Guild object of a server with just the server ID to be able to create channels, categories, etc?
The thing is that the command that orders the creation of the channel/category can be used in all the servers the bot is in and make effect in one of the selected servers even if the command was not called from that server. Is that possible?
put your code on github and send the link here
if the Bot have the permissions in that guild yes
!d discord.ext.commands.Bot.fetch_guild
await fetch_guild(guild_id, /, *, with_counts=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild) from an ID.
Note
Using this, you will **not** receive [`Guild.channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.channels), [`Guild.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.members), [`Member.activity`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.activity) and [`Member.voice`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.voice) per [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member).
Note
This method is an API call. For general usage, consider [`get_guild()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_guild) instead...
its raising that error because you're using the bot with a different event loop, use asyncio.run_coroutine_threadsafe to use coros in a different thread and event loop
!d asyncio.run_coroutine_threadsafe
asyncio.run_coroutine_threadsafe(coro, loop)```
Submit a coroutine to the given event loop. Thread-safe.
Return a [`concurrent.futures.Future`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Future) to wait for the result from another OS thread.
This function is meant to be called from a different OS thread than the one where the event loop is running. Example...
^
Okay thanks
Is there a direct method to create a private thread that the admin cannot access.
theres channel.create_thread() if thats what you're looking for
I mean a thread that even the admin cannot access
that's not I'm looking for
I'm using that right now
but admin can still enter the thread through the #threads
I know maybe dm is a way, but is there a method that can work in a server?
i dont think thats possible
use DMs i say
there's a really strange method
it's a lot cleaner
whats the method
the bot needs to detect the users and remove it....
too much work
Indeed
just use DMs
but I need groups..
it's not personal
or is there a method to change a server's admin to a bot
wdym?
do you understand my meaning?
make a bot a server owner
so it's impossible to actually create a private space for certain user groups without dm
yeah pretty much
there will always be higher roles that can see it
Line can let the bot be the group owner
no it cant
owners are users because a user has to make it in the first place
yeah but then the bot can have the highest authority if the author don't access the bot
wdym by "author" in this context
the person who ran the command?
the bot creator
thats the bot owner, not the author
either way just use DMs
is it possible to create a dm group by the bot?
no
I know ....... now the problem is that I need space for multiple users
can anyone give me an example for required parameters in a slash command?
so then my problem isn't solved
async def your_cmd(self, ..., your_param: your_param_type):
...```
I need a requried option
just showed you how to make a required option
wdym by autofill?
I want the parameter to auto-fill with an answer
wait let me see if I can give you an example ;-;
so an autocomplete?
it is possible
this is not, gdm use oauth
!d discord.Client.create_guild
await create_guild(*, name, icon=..., code=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).
Bot accounts in more than 10 guilds are not allowed to create guilds.
Changed in version 2.0: `name` and `icon` parameters are now keyword-only. The `region` parameter has been removed.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
it's not
it is...
you cant transfer server ownership to a bot?
how?
just create the guild with the bot
Yeah. But it has a limit of 10 iirc
yeah "Bot accounts in more than 10 guilds are not allowed to create guilds."
guild = server
Bro remembers the whole docs 😭
I just copy pasted
crazy...
I read it 30 seconds ago lmao
And you actually believed 😭
Yes though
Quick question :
How would I check if a member has a specific roles in a slash command? Discord.py
if role in interaction.user.roles ?
!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...
is it possible to not create the server everytime?
cuz I might restart the bot
Very frequently lol
What is your use case idk maybe Alex can help
Or if you're willing to explain everything again 💀
I can
so I was trying to create a private thread for a certain group of users
it's a group, so DM doesn't work
but I want it to be purely private
even the admin cannot enter it
Well then your bot can create create a server and then you can use that server to create private channels for your users
!d discord.Client.create_guild
await create_guild(*, name, icon=..., code=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).
Bot accounts in more than 10 guilds are not allowed to create guilds.
Changed in version 2.0: `name` and `icon` parameters are now keyword-only. The `region` parameter has been removed.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
yeah but will it create the server everytime a start it?
Nah you can just create it once and then delete that line of code if you want it to remain unchanged
Yeah
No
In a command preferably
Then run that command and store the server id
Then use that id for further processing
I see
so is it possible for me to transfer the ownership
cuz... there are so many members in my server
guys how can i get all slash commands from a ext by its name in disnake?
holy shit he's right
disnake is a rewrite of dpy so i'm guessing use bot.walk_commands() to create an iterable of all the commands and then check if each "command" is a cog and then get all the commands from said cog
!d disnake.ext.commands.InteractionBot.get_cog nvm i fixed my issue lol
i used
get_cog(name)```
Gets the cog instance requested.
If the cog is not found, `None` is returned instead.
im stupid regardless 
the repo is private cause im embarrassed by my (non)skills x,x
guys should i make text based commands or slash commands, like which are preffered and easy to use?
i’d say slash commands when you get to know them but either works fine. they both have their quirks and prefix commands make more sense upfront
what are you exactly trying to do?
literally just what I said
get the user id by username
kk, thanks
are you looking for a username inside of a guild where the message was sent?
nope
a random input string
so you’re querying the whole of discord for a username?
whats the scope of your username search?
one server? multiple servers? the whole of discord?
in the server
the server
I used guild.members
@viscid hornet here's my code
are you inputting a username or a display name?
honestly, just use Guild.get_member_named
!d discord.Guild.get_member_named
get_member_named(name, /)```
Returns the first member found that matches the name provided.
The name is looked up in the following order...
username
okay
How can i do a while loop with integers?
wdym while loop with integers?
age = str(int(input("How old are you?: ")))
while len(str(age)) == 0:
age = int(input("How old are you?: "))
To make it loop until the user types a full answe
i tried
age = int(input("How old are you?: "))
while len(age) == 0:
age = int(input("How old are you?: "))
But then i just get the error
Traceback (most recent call last):
File "D:\First\First\HelloBubba.py", line 10, in <module>
while len(age) == 0:
^^^^^^^^
TypeError: object of type 'int' has no len()
- you made it in integer and integers dont have any length because it's a number, not a list or string
- this isnt something to be in discord bots
go to #python-discussion isntead
Is there a good way to check if a token is a bot token or user token?
paste it into discord. it will tell you if its a bot token or not
Will warn me for every token and I need it in python
you can always try to run the tokens and then if any errors show up, its not a bot token
But I have to check if it's a bot then bot or user token then user.. because in the headers in the auth I have to set it to bot {token} when it's a bot token
yeah?
theres not really any way around that
whats your use case?
A token tool... You find a token and then you can for example show all guilds the user/bot is on
But I guess I will just add a u/b input to select if it is a user or bot token
nono worky like that
lemme try in a sec
well I've solved that problem
okay
I enabled the members intent in the developers portal
well, ofc
its called a joke
? so why ask
Okay
the display of humour was lacking but alright
read that message wrong
how do i configure telegram bot to listen message from my channel and respond to it
I already have the channel id
currently bot is listening to itself and responds
what the hell is that
so check if the author is the bot and if it then just “return” out the function
a joke apparently
the fact that it doesnt even work 😭🙏🏽
it does
if youre gonna decide to be a smartass, do it correctly
and i am clearly in pycharm, so it would highlight incorrect shit
test it here: https://programiz.pro/ide/python/1X887IDK4D?utm_source=python_playground-shared-project-link
Python Playground: An online IDE to practice Python programming. Write, edit & run code online. Suitable for all skill levels. Try now.
almost like everything you wrote has yellow squiggly lines underneath
😭🙏🏽
not red lines tho
🗿
then why are you asking for a code review
Understanding where you could do better is part of the improvement
Im using discord.py and was wondering how i could check if i have the ability to ban a member from a server?
hm can you help me out on how to add it?
i have a gist on it covering how to register persistent views, plus stateful views, if that helps
https://gist.github.com/thegamecracks/0f9ab7ad3982e65ff4aa429acb39cc4e
its written with dpy in mind, but nextcord should be mostly similar
@hushed galleon may you help me out with a problem I’m having
asyncio.run_coroutine_threadsafe(start_api(data), bot.loop)
fairly straightforward
tbh i would recommend just not combine flask and discord.py in the same process/project
thank you it worked for me
is it possible to add multiple users to a thread at a time?
(I want to prevent users added to thread notification messages from being too long)
Any idea why this is not giving me the role when I react to the message?
@bot.event
async def on_reaction_add(reaction: discord.Reaction, user: discord.User):
if user.bot:
return
try:
with open('projects/project_data.json', 'r') as infile:
project_data = json.load(infile)
except (json.JSONDecodeError, FileNotFoundError):
project_data = []
if isinstance(project_data, list):
for project_info in project_data:
if project_info['message_id'] == reaction.message.id:
if reaction.emoji == '✅':
project_details = project_info['project_data']
server_guild = await bot.fetch_guild(project_details['server_guild'])
role = await server_guild.get_role(project_details['role_id'])
await reaction.user.add_roles(role)
Looking for a better way for my discord bot to call another file and take an output image generated by it, feedback would be appreciated
I need to call src/image_gen.py and then an image output is generated by it
My bot needs to display the image
If the message was sent after bot startup, you need to listen to on_raw_reaction_add
!d discord.on_raw_reaction_add
discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_reaction_add), this is called regardless of the state of the internal message cache.
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions) to be enabled.
Generally, in async applications heavy blocking processes (such as image generation) need to be threaded
I think I have some open source repo with image generating bot
Lemme see
Even if I'm passing the message ID to check if a reaction was added? owo
Yeah, you don't receive simple on_reaction_add events if message is not in cache
And it will never be in cache after bot restart
oooh
Yeah found the repo, take a look https://github.com/DevotedExuDevelopersTeam/EventMaster/blob/master/utils/image_generation.py
gotcha
Specifically at async functions that wrap sync image generation functions
asyncio.get_event_loop().run_in_executor(None, ...) is equivalent to asyncio.to_thread(...), better of using that function, most people actually just make a deco for it so its not a bloat
is it possible to add multiple users to a thread at a time?
(I want to prevent users added to thread notification messages from being too long)
Yeah I have a deco in my newer repos but they're private
It still looks pretty unholy
I'm not sure if there's atomic operation for that but you can always for loop ig?
I'm using for loop now
but the problem is
users added to thread notification messages will be sooooo long
the endpoint for adding members to thread doesnt seems to provide a way to add multiple users per call
You could theoretically asyncio.gather everything but uh you do risk getting ratelimited
ummm
what would happen if you get ratelimited
Discord doesn't let you send requests for some time
oops
I think I've got this from clearing messages
How many users get added to thread at one time
Many
I need to add 12 users
I'm adding it by a for loop
which will cause the thread having 12 messages like
{user1} has been added to this thread
{user2} has been added to this thread
{user3} has been added to this thread
...
{user12} has been added to this thread
so I was finding for a method
that can add them once
{user1, user2, user3, ... user12} have been added to this thread
is this clear enough?
Are you manually sending this message? like with .send()? If so then you don't need to send the message again and again
huh for a sec i thought they just want a single api call to add multi users into thread, guess it was just logic issue
Thank you will go through it
Actually could u explain what I need to do in simpler terms? If possible
My smooth brain can't process this
Discord API doesn't support adding multiple users at once, so it's impossible to merge all these messages into one
If you mean the system message
Did you get scared cause of lots of constants at the top xd
Scroll down till you see async functions
haha yes
users are added 1 at a time normally so its reasonable to suspect the API would work in a similar way
okay
okay, then I'll wait for this feature to be done one day.
wdym by “help menu with select menu”
a help command with a select menu?
:v
ask @vapid parcel because im yet to make a proper help command of my own :v
my guess is that you would get all the cogs, load them into a select menu, then get a list of commands and their details like usage, description, etc into a list from those cogs and display them in a paginator
but thats like surface level, idk the intricacies 🤷🏽♂️
@vapid parcel
Hello, it does not detect the prefix of my bot.
What is It
There is
Print os.environ
I don't understand
in your code add print(os.environ)
Before the erroring line so it actually prints
There is
what there is?
client = commands.Bot(command_prefix=os.environment['PREFİX'])
^ 🙏
He says so now
!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.
u missed this part
Anyone free to help me out lil bit?
Just ask
That's the simplest python error 💀
Maybe stop sending ss
Hey guys how do i reset bot on discord. My commands wont show up
i have this weird problem where unless i kick a bot from my server the new commands dont show up
have u tried restarting discord after u update the code?
does someones knows if is possible to create a discord bot that execs a specific cell on a jupyter notebook in github codespaces? I have a minecraft server located in github codespaces, and i want to create a bot to start the server directly on discord without entering on github
probably need to sync your commands
are these slash commands?
yes
need to sync them then
from discord import app_commands
from discord.ext import commands
import os
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@bot.event
async def on_ready():
print(f"{bot.user.name}")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print(e)
how do i make a discord bot that takes recording from your mic and plays it in a voice channel
no point in printing the exception btw
ok
are any errors printing btw
why not
there are errors in syncing
like duplicate commands
max commands reached
and more so its better to print errors if you dont have error handling
but it will be with traceback and all the jams is hard to navigate lol
print will print the exact same thing
nope
print only prints the exception
not the traceback
recommendation: use setup_hook for syncing
better recommendation: make command for syncing
If there are things that can cause the same exception, you'd have no idea where it came from
i have a whole control panel foor syncing reloading cogs unloading cogs restarting all cogs unsyncing commands and shit
The default one is already good enough
well its personal choice tbh
It just adds more unnecessary code for no benefit or use
anyways i was wondering how i can make a bot that can use my mic in my computer and tranmit the voice to a discord voice channel
i made one before but it made recordings of 1 min in my computer then played then and then deleted them but i am trying to figure out how to do it without cause its a pain to wait 1 min
but most of the time it didnt even play it properly even tho the recording had audio it didnt played them
got any idea how i can make one of those?
I don't think bots can receive sound in voice channels
do you mean just playing a voice recording file in a voice channel?
oh what
because you’ll only get the bottom line with no traceback
It was long ago
ah
Idk if it's still a thing
no not in voice channel i wil speak from my computer and it wiill play in in the voice channel
well I guess if you want to use pycord you could refer to this @fiery girder
i will not be in a voice channel
Oh, you want this to happen realtime?
like, itll play as you speak?
yes
not sure if thats possible...
well if the bot is run locally, you can do that
yea i am running it locally
no clue then
get an audio stream from your mic and pipe it to the bot
how
I haven't done exactly that so idk what libs you would need, but it's definitely possible
i got the audio from the mic but it isnt piping it in yor bot
i have one right now that makes 1min audio file and plays that
@vivid holly this makes 1 min audio and plays it
but i want it live
you can get it live, but it'll sound like crap according to this stack overflow answer
ok lemme try this
what is the base format the discord..py uses
its not working it just keep playing nonsense noices
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OSError: [Errno -9998] Invalid number of channels
it litreely says int he discord.AudioSource that it should be stereo still its dooing this
it sounds like someones farting it dont replay my audio
but it'll sound like crap
accurate 🤷
like not even a remote resemblence?
not
that is certainly weird, but then again, I have not done this so maybe it is just unusable
it doesnt even match the pitch
how do i fix this while still using discord.ext commands
im trying to make a speechbubble command but i dont know how to turn the speech bubble invisible so you can see the discord background instead of black.. i even asked chat gpt to make it invisible but that ofc just ruined the code so that didnt help at all and i also tried searching through google with no luck at all
I'm using cv2
@bot.slash_command(name="bubble", description="Add a speechbubble to a gif or an image.")
async def bubble(ctx: nextcord.Interaction, file: nextcord.Attachment):
try:
file_data = await file.read()
img_user = cv2.imdecode(np.frombuffer(file_data, np.uint8), cv2.IMREAD_COLOR)
img_bubble = cv2.imread('bubble2.png', cv2.IMREAD_UNCHANGED)
img_bubble_resized = cv2.resize(img_bubble, (img_user.shape[1], img_user.shape[0]))
_, _, _, alpha = cv2.split(img_bubble_resized)
alpha_inv = cv2.bitwise_not(alpha)
bubble_alpha_mask = cv2.merge([alpha_inv, alpha_inv, alpha_inv])
img_content_cut = cv2.bitwise_and(img_user, bubble_alpha_mask)
img_bytes = cv2.imencode('.png', img_content_cut)[1].tobytes()
await ctx.response.send_message(file=nextcord.File(io.BytesIO(img_bytes), filename="adminhelper_speechbubble.png"))
except Exception as e:
print(f"Error: {e}")
shouldnt raise any errors
yet it does
import discord
from discord.ext import commands
import sqlite3
#Database
bot = commands.Bot()
active=False
@bot.event
async def on_ready():
print(f"{bot.user.name}")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print(e)
also i told you not to bother printing the exception
just put py synced = ... print(f"Synced {len(synced)} commands")
you wont get any traceback
do that and tell me the error that comes back
anything to do with the bot can raise errors
still gives an error next to tree
tell me what the terminal says
'Bot' object has no attribute 'tree'
also btw don't bother printing the error because you'll only get the last line like ```py
discord.ext.commands.errors.CooldownOnCommand(...): ...
thats weird because it definitely exists
maybe there are forks in the libs?
since i imported them i have problems
shouldnt have anything to do with the databases
no???
Explains alot
what are you using then
for what
thats probably your error
your discord bot?
are you using discord.py or another library
OHHHHH

ik now sorry im dumb
wait are there any args inside of commands.Bot()
should look like this (as example) py bot = commands.Bot(command_prefix = '!', intents = Intents.all())
thats your issue

this will fix the issue (change according to your preferences)
nope doesnt work
what did you put
the things you told me to
show the whole thing again
import random
import discord
from discord.ext import commands
import sqlite3
database = sqlite3.connect('data.db')
cursor = database.cursor()
database.execute("CREATE TABLE IF NOT EXISTS cars(car_name STRING, car_id INT)")
bot = commands.Bot(command_prefix = '!', intents = discord.Intents.all())
active=False
@bot.event
async def on_ready():
print(f"{bot.user.name}")
synced = bot.tree.sync()
print(f"Synced {len(synced)} commands")
his IDE might be tweaking ngl
i m using pycharm lol
missed await on the tree sync
changes absoulutely nothing
lemme test it out
whats the command you were trying to run?
there was a slash command, @bot.tree.command()
yes
whats that? show it here
@bot.tree.command(name="claim")
async def ping(ctx):
#script
show the script
also thats supposed to take interaction, not ctx
@bot.command() for a prefix command
this seems cursed
@bot.tree.command(name="claim")
async def ping(ctx):
global active
if active==True:
car_name = "Porsche 911"
await ctx.response.send_message(f"@{ctx.user.name} has claimed the car! The car is in your garage now!")
query = "INSERT INTO cars VALUES (?, ?)"
cursor.execute(query, car_name)
database.commit()
active=False
else:
await ctx.response.send_message("There is no car to claim!")
how about you try bot.__tree.sync() or smth 
this is weird though since tree property should exist
doesnt work
and what is the error?
'Bot' object has no attribute 'tree'
try __tree, not tree
doesnt work
even though this seems so wrong
commands.Bot inheritates from discord.Client and BotBase class which has a tree property
that should return your app_commands.CommandTree
@pale zenith 
i cant use app_commands cuz i get an error
thgat i cant import it
have you installed the latest discord.py? can you do pip show discord.py
yes
watch it be a prehistoric version 
are there for sure 0 forks?
we shall know soon hopefully
its 2.3 i think

