#discord-bots
1 messages · Page 389 of 1
oh
class Moderation(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.moderator_roles = (727152007009271822, 710242627089596459, 710241598348329080, 949779453909823488,
711210963231178803, 1076838318555267073)
# Mute command
@commands.command(name="mute", description="Mutes the user.")
@commands.guild_only()
@commands.cooldown(1, 5.0, commands.BucketType.user)
@commands.has_any_role(self.moderator_roles)
Why can't I use the decorator check for my commands? Unresolved reference 'self'
Change the check_moderator Instead of a staticmethod, make check_moderator
Sorry I mean by using the commands.has_any_role
Do you have any idea?
If this is hardcoded just put it in the decorator
what event should I do it in?
I would rather use a variable so I don't need to go through all the commands one by one later
Also very generally, people really don't care about how many servers your bot is in. It's just a humblebrag that steals space from something that could actually be useful
i just like to look at it
You could look at things that aren't a publicly broadcast status 
`class Moderation(commands.Cog):
def init(self, bot):
self.bot = bot
self.moderator_roles = (727152007009271822, 710242627089596459, 710241598348329080, 949779453909823488,
711210963231178803, 1076838318555267073)
def is_moderator(self, ctx):
return any(role.id in self.moderator_roles for role in ctx.author.roles)
def check_moderator(self):
return commands.check(self.is_moderator)
@commands.command(name="mute", description="Mutes the user.")
@commands.guild_only()
@commands.cooldown(1, 5.0, commands.BucketType.user)
@check_moderator()
async def mute(self, ctx, member: commands.MemberConverter, *, reason=None):
await ctx.send(f"{member} has been muted for reason: {reason}"
bot.add_cog(Moderation(bot))`
try it like this
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.moderation' raised an error: TypeError: Moderation.check_moderator() missing 1 required positional argument: 'self'
bot=commands.AutoShardedBot(command_prefix='!', intents=intents, max_messages=150, chunk_guilds_at_startup=False, shard_count=2) this is the constructor?
i dont see them
Any idea?
What do you mean by "see"
Just use a constant. Again this doesn't need to be an instance attribute if it's not changing per instance
What do you mean by a constant?
Oh you mean outside the class
Exactly
Than I should use @commands.has_any_role(*moderator_roles) to unpack the tuple into individual arguments?
Yeah that should work
Is there any built in decorator like @commands.has_any_role specifically for channels?
Not that I'm aware of
You may really want to consider moving to app commands instead
You mean slash commands?
The formal name is app commands as that also includes context menus, but yes
Hi. I used to code a lot of discord bots using python in the past, but it has been so so long since I last coded one, and I wanna get back at it. Is there some manual that really teaches everything from the beginning, including all of these new features such as slash commands, menus, etc...
Do you know what library you are planning on using?
Is there anything else other than discord.py?
It's also a bit of a mixed bag. The libraries tend to only officially support api docs which tell you how the individual components work. These deep dive "tutorials" are made by individuals and vary a ton on quality or recency
There are a bunch now, py-cord, nextcord, disnake, etc
There were loads of forks made while discord.py was on hiatus
Which one would you suggest I use?
Very subjective question tbh
Pretty much all of the popular ones are up to date on the discord api
Becomes a question of library design choices and support
I normally recommend looking at the style of the docs and basic examples for each and see what you like best
So the top 4 would be discord.py, py-cord, nextcord and disnake? Or are there more worth checking out
To answer your original question.
A 3rd part tutorial for discord.py is here : https://fallendeity.github.io/discord.py-masterclass/
And a official guide (different than docs) for Pycord is here: https://guide.pycord.dev/
And I am not familiar with others.
Iirc hikari was the only one with novel design and not just a dpy fork
If you scroll to python you can see all the major options
https://libs.advaith.io/#python
Alright. I'll make sure to check them. Just interested, which one do you both use?
I use py-cord
I am community support for discord.py so take that with a grain of salt lol
Alright. Thank you both for the help, much appreciated!
@fast osprey Sorry for the ping. Is this how you use the persistent view?
https://paste.pythondiscord.com/AJYQ
If you do that, you are persisting a single view object across all of the messages that view type might be on
How do I solve this?
Either use dynamic items, or make as many views as you need
I only need one for this type of verification
Btw why am I getting Parameter 'button' value is not used on the line
@discord.ui.button(label='Start Verification', style=discord.ButtonStyle.primary, custom_id='verification:start')
async def start_verification(self, interaction: discord.Interaction, button: discord.ui.Button):
Pycharm?
That is something you can ignore. Generally you do not make a function that does not use an argument but in this case you have to so that the lib can provide the argument without erroring
Yes
Is there any other way I could/should rewrite this code?
Not that I know of, it is just a weak warning that you have to ignore
Is there any way to supress these warnings in Pycharm by adding a comment?
Yeah just add a _ before the parameter
Hi, not sure if this is the right channel to ask this in but I was having some trouble so I figured I'd try, https://github.com/vn-ki/film-raffle-bot I'm attempting to recreate a discord bot that uses python, I think I've got the main elements in the config file down but I'm having trouble with setting up a database for it since I have no experience with that. Any suggestions or recommendations for what to use?
tried in #databases but figured id try here too
Why is it not removing the attachment (image) from the embed when calling create_answer_callback
It removes the buttons but not the image
@staticmethod
def create_answer_callback(user, correct_answer):
async def answer_callback(interaction: discord.Interaction):
if interaction.user != user:
return
selected_answer = interaction.data["custom_id"].split(":")[1]
if selected_answer == correct_answer:
response = "You have been successfully verified."
else:
response = "Verification failed. Please try again."
# Create a new embed or modify the existing one to remove the image
new_embed = discord.Embed(title="", description=response, color=discord.Color.blue())
new_embed.set_image(url=None) # Explicitly clear the image
# Edit the message to update the content and remove the buttons
await interaction.response.edit_message(embed=new_embed, view=None)
return answer_callback
Try this ⬆️
Captcha image is still there
1 moment
@staticmethod
def create_answer_callback(user, correct_answer):
async def answer_callback(interaction: discord.Interaction):
if interaction.user != user:
return
selected_answer = interaction.data["custom_id"].split(":")[1]
if selected_answer == correct_answer:
response = "You have been successfully verified."
else:
response = "Verification failed. Please try again."
# Create a new embed or modify the existing one to remove the image
new_embed = discord.Embed(title="", description=response, color=discord.Color.blue())
# Edit the message to update the content, remove the buttons, and the image (embed and file)
await interaction.response.edit_message(content=response, embed=new_embed, attachments=[], view=None)
return answer_callback
You need to make sure that the one you're editing is the actual message, and i am unsure but i didn't know we can edit ephemeral messages.
And i don't think we can edit them, i never tried and never looked into that.
All I can do to is add attachments=[]
Thanks spooky
i keep getting the same error.. who can help?
Exception has occurred: Forbidden
403 Forbidden (error code: 50007): Cannot send messages to this user
File "C:\Users\jeqqy\OneDrive\Desktop\Frostware\frostware.py", line 653, in sendkey
await user.send(f"Your key is: {key.strip()}")
File "C:\Users\jeqqy\OneDrive\Desktop\Frostware\frostware.py", line 683, in <module>
botclient.run(bottoken)
discord.errors.Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user```
```py
for user in users_to_message:
try:
await user.send(f"Your key is: {key.strip()}")
print(f">> Sent key to {user.name}")
users_to_message.remove(user)
break
except discord.Forbidden:
print(f">> Cannot send message to {user.name}, DMs are closed.")
await ctx.send(f"Cannot send message to {user.name}, DMs are closed.")
except Exception as e:
print(f">> An unexpected error occurred with {user.name}: {e}")
await ctx.send(f"An unexpected error occurred with {user.name}: {e}")```
That basically means that the user dms are closed.
ik it does, but even with the error handling it still errors and stops the code
Could be beause you're trying to send the dm, but fails, so it will automatically raise that.
I can't see the full code, But i belive that's why this happens.
yes i am trying to send to the dm
theres nothing else to but variables
@botclient.command()
async def sendkey(ctx):
if ctx.author.id != 849652633261834241:
await ctx.send("You don't have permission to use this command.")
return
if not os.path.exists(KEY_FILE):
await ctx.send("Key file does not exist.")
return
with open(KEY_FILE, 'r') as file:
keys = file.read().strip().split(',')
guild = botclient.get_guild(GUILD_ID)
if guild is None:
await ctx.send("Guild not found.")
return
role = guild.get_role(ROLE_ID)
if role is None:
await ctx.send("Role not found.")
return
users_to_message = [member for member in guild.members if role in member.roles]
if not users_to_message:
await ctx.send("No users with the specified role found.")
return
for key in keys:
if not users_to_message:
break
for user in users_to_message:
try:
await user.send(f"Your key is: {key.strip()}")
print(f">> Sent key to {user.name}")
users_to_message.remove(user)
break
except discord.Forbidden:
print(f">> Cannot send message to {user.name}, DMs are closed.")
await ctx.send(f"Cannot send message to {user.name}, DMs are closed.")
except Exception as e:
print(f">> An unexpected error occurred with {user.name}: {e}")
await ctx.send(f"An unexpected error occurred with {user.name}: {e}")
keys.remove(key)
with open(KEY_FILE, 'w') as file:
file.write(','.join(keys))
await ctx.send("Keys sent and updated.")```
see
Ah
1 moment
@botclient.command()
async def sendkey(ctx: commands.Context) -> None:
bot_owner_id = 849652633261834241 # Replace with actual bot owner's ID
if ctx.author.id != bot_owner_id:
await ctx.send("You don't have permission to use this command.")
return
if not os.path.exists(KEY_FILE):
await ctx.send("Key file does not exist.")
return
with open(KEY_FILE, 'r') as file:
keys = [key.strip() for key in file.read().split(',')]
guild = botclient.get_guild(GUILD_ID)
if guild is None:
await ctx.send("Guild not found.")
return
role = guild.get_role(ROLE_ID)
if role is None:
await ctx.send("Role not found.")
return
users_to_message = [member for member in guild.members if role in member.roles]
if not users_to_message:
await ctx.send("No users with the specified role found.")
return
for key in keys[:]:
if not users_to_message:
break
user = users_to_message.pop(0) # Get and remove the first user in the list
try:
await user.send(f"Your key is: {key}")
print(f">> Sent key to {user.name}")
except discord.Forbidden:
print(f">> Cannot send message to {user.name}, DMs are closed.")
await ctx.send(f"Cannot send message to {user.name}, DMs are closed.")
except Exception as e:
print(f">> An unexpected error occurred with {user.name}: {e}")
await ctx.send(f"An unexpected error occurred with {user.name}: {e}")
else:
keys.remove(key) # Remove the key after successful delivery
# Update the key file
with open(KEY_FILE, 'w') as file:
file.write(','.join(keys))
await ctx.send("Keys sent and updated.")
@ivory remnant
same error
Is it better to use os or pathlib?
@botclient.command()
async def sendkey(ctx: commands.Context) -> None:
bot_owner_id = 849652633261834241 # Replace with the actual bot owner's ID
if ctx.author.id != bot_owner_id:
await ctx.send("You don't have permission to use this command.")
return
if not os.path.exists(KEY_FILE):
await ctx.send("Key file does not exist.")
return
with open(KEY_FILE, 'r') as file:
keys = [key.strip() for key in file.read().split(',') if key.strip()]
if not keys:
await ctx.send("No keys available in the file.")
return
guild = botclient.get_guild(GUILD_ID)
if guild is None:
await ctx.send("Guild not found.")
return
role = guild.get_role(ROLE_ID)
if role is None:
await ctx.send("Role not found.")
return
users_to_message = [member for member in guild.members if role in member.roles]
if not users_to_message:
await ctx.send("No users with the specified role found.")
return
keys_sent = 0
for user, key in zip(users_to_message, keys):
try:
await user.send(f"Your key is: {key}")
print(f">> Sent key to {user.name}")
keys_sent += 1
except discord.Forbidden:
print(f">> Cannot send message to {user.name}, DMs are closed.")
await ctx.send(f"Cannot send message to {user.name}, DMs are closed.")
except Exception as e:
print(f">> An unexpected error occurred with {user.name}: {e}")
await ctx.send(f"An unexpected error occurred with {user.name}: {e}")
if keys_sent > 0:
remaining_keys = keys[keys_sent:] # Slice the keys that haven't been sent
with open(KEY_FILE, 'w') as file:
file.write(','.join(remaining_keys))
await ctx.send(f"Sent {keys_sent} keys and updated the key file.")
else:
await ctx.send("No keys were sent.")
pathlib is preferred over os.
Why is that if I may ask?
- Enhanced Functionality
- Cleaner Syntax
- Object-Oriented Interface
Examples:
import os
if os.path.exists('file.txt'):
print('File exists')
from pathlib import Path
if Path('file.txt').exists():
print('File exists')
Joining paths example:
import os
full_path = os.path.join('dir', 'subdir', 'file.txt')
from pathlib import Path
full_path = Path('dir') / 'subdir' / 'file.txt'
Which one is faster in performance?
Eh.... i believe os is faster
i believe it's the same except pathlib is prefered in newer codebase after python 3.6
Yeah, i've mentioned pathlib is prefered, But still, i feel like os could be slighty faster in performance.
im getting the same error wth
send it again
403 Forbidden (error code: 50007): Cannot send messages to this user
File "C:\Users\jeqqy\OneDrive\Desktop\Frostware\frostware.py", line 656, in sendkey
await user.send(f"Your key is: {key}")
File "C:\Users\jeqqy\OneDrive\Desktop\Frostware\frostware.py", line 687, in <module>
botclient.run(bottoken)
discord.errors.Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user```
@dry kelp
error seems pretty clear?
@slate swan i didnt "blindly" paste someone elses code.. i looke dthru it and ensured anything needed to be changed
well duh? the problem is i have a error handler which it js doesnt seem to care abt and instead js stops
thats my issues thats what im trying to fix
if the dms is closed, it js skips them
thats what i implemented but it doesnt seem to want to skip
the error seems different, though. Could you copy the whole file and paste it?
!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.
whats your problem?
shouldn't matter. measure first before optimizing
a lot of os/pathlib functions will be bottlenecked by system IO anyway
too much code and confidential information
the rest is unrelated stuff
did you save your file and restart your bot? like this should work
KEY_FILE = "keys.txt"
GUILD_ID = 1223160887871934484
ROLE_ID = 1226546057077456966
@botclient.command()
async def sendkey(ctx: commands.Context) -> None:
bot_owner_id = 849652633261834241 # Replace with the actual bot owner's ID
if ctx.author.id != bot_owner_id:
await ctx.send("You don't have permission to use this command.")
return
if not os.path.exists(KEY_FILE):
await ctx.send("Key file does not exist.")
return
with open(KEY_FILE, 'r') as file:
keys = [key.strip() for key in file.read().split(',') if key.strip()]
if not keys:
await ctx.send("No keys available in the file.")
return
guild = botclient.get_guild(GUILD_ID)
if guild is None:
await ctx.send("Guild not found.")
return
role = guild.get_role(ROLE_ID)
if role is None:
await ctx.send("Role not found.")
return
users_to_message = [member for member in guild.members if role in member.roles]
if not users_to_message:
await ctx.send("No users with the specified role found.")
return
keys_sent = 0
for user, key in zip(users_to_message, keys):
try:
await user.send(f"Your key is: {key}")
print(f">> Sent key to {user.name}")
keys_sent += 1
except discord.Forbidden:
print(f">> Cannot send message to {user.name}, DMs are closed.")
await ctx.send(f"Cannot send message to {user.name}, DMs are closed.")
except Exception as e:
print(f">> An unexpected error occurred with {user.name}: {e}")
await ctx.send(f"An unexpected error occurred with {user.name}: {e}")
if keys_sent > 0:
remaining_keys = keys[keys_sent:] # Slice the keys that haven't been sent
with open(KEY_FILE, 'w') as file:
file.write(','.join(remaining_keys))
await ctx.send(f"Sent {keys_sent} keys and updated the key file.")
else:
await ctx.send("No keys were sent.")```
debugging thru vsc
since this error is referencing bot.run(), this doesn't seem quite related with
-oh are you using like the actual debugger? don't
its what i use
b4 anything else
cuz if i try to run a python file and theres a error it js closes
could you try without it? just open a console (even the vscode console) and just python YOUR_FILE_NAME.py or python3 or whatever you use
ya you don't just rawdog a python file like that, run it via a terminal instead of just double-clicking it
Not with that attitude

this somehow fixed it..
anyway, if running the code in a more conventional way does not fix the issue, send the most recent error here and we'll see
i did it in vsc terminal and it works just fine now
yea figures. I don't trust them debuggers- if I had to guess it just "forgot" to notice the file was saved, or something like that
yep the vscode terminal works fine like any other! for future reference, avoid using the debugger for discord.py-related code as it usually leads to such errors :)
I would go as far as to say not to use it for any code (but I'm just not a fan of it, usually gives me more headaches than it's worth)
glad it was fixed tho
Usually in vscode there are gonna be more terminals listed to the right of your current one. Close em
Which python version is recommend to use right now?
the last one ???
always download the last one
It's between 3.12 vs 3.13
if only it said somewhere
then 12
im using 12
Do I always have to fetch the user to see if they are a member of the guild?
no?
Can I run fastapi and my bot in same script? I want to implement pubsub model
You can, you shouldn't
Then how should I make it 😅 can u give me idea
I am checking api continuosly for changes and wanted to implement pubsub model
What is the webserver doing?
Actually my friend have given me his api endpoint and I keep checking it for updates every 5 minutes ,so I wanted to eliminate the continuous api checking
And just fire it up when there it updates instantly
# task.py
import discord
from discord.ext import commands
import asyncio
guild_access_lock = asyncio.Lock()```
# events.py
import discord
from discord.ext import commands
from task import guild_access_lock
class EventsCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def another_command(self, ctx):
async with guild_access_lock:
Why isn't this working?
Are the files in the same forlder?
Yes but what do you do with it on your end
Yes
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.events' raised an error: ModuleNotFoundError: No module named 'tasks'
I want server to just trigger the notification function of bot script that's why I thought of using within bot script
What does this notification function do?
Ping the role and sends embed+link of yt
You don't need a bot to do that at all, you can just post to a webhook
Hmm but for webhook what should I use I mean for yt updates
I have to track around 30-40 channel
webhooks are how you post from some arbitrary program into a discord message
That's weird
I mean what should I use for yt updates when new video arrive so I can send webhook with bot
For some reason from .tasks import guild_access_lock worked
with (dot) in the beginning
Yeah, I was testing it with a dot
Why is the dot necessary?
It's relative to your cwd
The dot makes a reference to the current package
You can use more than one dot to refer to the parent(s)
PS C:\Users\luffy\Downloads\pycord why> python bot.py
Bot is online as invade#9123
C:\Users\luffy\Downloads\pycord why\.venv\Lib\site-packages\discord\cog.py:796: RuntimeWarning: coroutine 'setup' was never awaited
setup(self)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Failed to load cog help.py: object list can't be used in 'await' exp```
@young dagger
test ignore
Code?
C:\Users\luffy\Downloads\pycord why\.venv\Lib\site-packages\discord\cog.py:796: RuntimeWarning: coroutine 'setup' was never awaited
setup(self)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
File "C:\Users\luffy\Downloads\pycord why\bot.py", line 19, in <module>
bot.loop.run_until_complete(load_cogs())
File "C:\Users\luffy\AppData\Local\Programs\Python\Python312\Lib\asyncio\base_events.py", line 687, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\luffy\Downloads\pycord why\bot.py", line 10, in load_cogs
await bot.load_extension('cogs.help') # Ensure the path is correct
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: object list can't be used in 'await' expression
PS C:\Users\luffy\Downloads\pycord why> ```
@fast osprey
Code?
!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.
That’s interesting
What library and version are you using?
My guess is that you have both py-cord and discord.py installed
If you are planning on using py-cord you should run
python -m pip uninstall discord.py discord py-cord
then python -m pip install py-cord
And then do not await load_extension
it work but i have another problem
PS C:\Users\luffy\Downloads\pycord why> python bot.py
Traceback (most recent call last):
File "C:\Users\luffy\Downloads\pycord why\bot.py", line 70, in <module>
@bot.command()
^^^^^^^^^^^^^
File "C:\Users\luffy\Downloads\pycord why\.venv\Lib\site-packages\discord\ext\commands\core.py", line 1430, in decorator
self.add_command(result)
File "C:\Users\luffy\Downloads\pycord why\.venv\Lib\site-packages\discord\ext\commands\core.py", line 1283, in add_command
raise CommandRegistrationError(command.name)
discord.ext.commands.errors.CommandRegistrationError: The command help is already an existing command or alias.
PS C:\Users\luffy\Downloads\pycord why> ```
@stark ingot
you (can, but) should not be writing a help command this way. override the default help command by subclassing commands.HelpCommand and passing it into your Bot constructor. https://docs.pycord.dev/en/stable/ext/commands/api.html#ext-commands-help-command
The following section outlines the API of Pycord’s prefixed command extension module. Bots: Bot: Attributes activity, allowed_mentions, application_flags, application_id, cached_messages, case_inse...
excuse me sir i get certificate verification error when i run python file on windows server using library nextcord
and I have installed certifi using pip install certifi
how do i solve this problem?
the error like this
how can i bypass certificate error on windows server?
try this
pip install --upgrade certifi
also make sure your system clock is correct
I've tried it, but it doesn't work, sir.
you're running it inside a VM right?
yes i run using remote desktop, i use windows server
have you tried running it locally to see if it works? might be an issue with where it's hosted
it works on real device, but it doesn't work on windows server
do you use ssl in your project?
I don't really know sir, but I use several libraries python for discord bot
I found a solution but I don't know what it means
try adding this to your code
import certifi
import os
from discord.ext import commands
os.environ["SSL_CERT_FILE"] = certifi.where()
okey wait i try
what do you mean by this sir?
do i have to use a code?
in your python file
okey sir i try
thank you sir, thank you very much, finally I can, thank you very much sir, always be healthy for good people
no worries! glad you got it sorted 😊
hah??
Not sure how sending irrelevant memes is related to this channel
can send your unfunny memes in off topic channels like #ot1-perplexing-regexing
still need help ?
!charinfo
@dim pond please don't post giant blocks of characters like that, thanks
anyone here familiar w discord api please dm me
We're not going to DM you
If you have a question you can ask it here
okkk
so basically ive only been coding for about 2 months and i tried making a discord username changer, you enter your token and the desired name and it changes the username to it, but for some reason i cant get this to work
That is against TOS
Writing any automation that asks for or uses user tokens
Is there any better way to do this?
def contains_repeated_content(message_content):
normalized_content = re.sub(r'\s+', ' ', message_content).strip()
pattern = re.compile(r'(.+?)\s+\1{1,}', re.IGNORECASE)
return bool(pattern.search(normalized_content))
well yeah do u know how to keep ur bot on 24/7 without running it on ur pc?
!hosting
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.
You can buy a VPS for hosting it
or get one for free
dm me
🤨
I would never use a VPS provided by someone I don't know
there are known ones
im using a known one
called pylexnodes
100% free
And how are they making money to maintain their servers?
No such thing as a free lunch
From what i can see on their website, shitton of ads
To...whom? The one person who goes on the site once to register and run their shit?
Yeah apparently on the "free panel" they have
Yeeeeah that doesn't remotely add up lol
Uhuh also probably not enough to sustain the servers they're using
I wonder why people start free hosting sites and if it's actually profitable in any ethical way
does anyone know how a discord bot can read a previous message?
Depends, how are you picking which message you want?
It would just be the message before a command
Wait can you choose a person’s last message sent?
There's not a short way to do that. You can search over a channel's history, and then filter based on that
For the former or latter?
Both
I mean you can't say "what was the last message this person sent ever", because your bot can't see every message a person sends
fair enough, is the former doable?
yeah
is it somewhere on the docs, I can't seem to find anything related
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) to do this.
Examples
Usage...
ah must've missed it ty!
Hello, I am here for Pycord API
Do you have a problem or question?
I might, I am just gauging the server 😊
If you have any questions you can ask, although most people here use discord.py, but I also use Pycord
oh, I thought discord.py was not developed anymore
Its creator is back
It's been under active development again for years
is it possible to get the context inside a FlagConverter's subclass?
show code maybe you can pass it in
What do you need it for?
Can anyone tell me why is the embed not coming
@bot.command(aliases = ["CF"])
@commands.cooldown(rate=1, per=10, type=commands.BucketType.user)
async def cf(ctx, amt: int):
await open_account(ctx.author)
users = await get_bank_data()
possibility = ["head", "tail"]
user_choice = random.choice(possibility)
bot_choice = random.choice(possibility)
if amt == None:
await ctx.send("Enter a amount to bet")
elif amt <= 0:
await ctx.send("Must be at least one")
elif amt > users[str(ctx.author.id)]["Wallet"]:
await ctx.send("You don't have enough money in your Wallet")
else:
users[str(ctx.author.id)]["Wallet"] -= amt
if user_choice == bot_choice:
amt = amt*2
users[str(ctx.author.id)]["Wallet"] += amt
em = discord.Embed(
title=f"Coin Flip",
description=f"Your choice **{user_choice}**, after filling the coin **{bot_choice}**. You won {amt}",
color=discord.Color.blue
)
await ctx.send(embed = em)
await save_data_bank(users)
else:
em = discord.Embed(
title=f"Coin Flip",
description=f"Your choice **{user_choice}**, after filling the coin **{bot_choice}**. You lost {amt}.",
color=discord.Color.blue
)
await ctx.send(embed = em)
await save_data_bank(users)
@cf.error
async def cf_error(ctx, error):
if isinstance(error, commands.errors.BadArgument):
await ctx.send("Please choose a number")
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(f"Command is on cooldown! Try again in {error.retry_after:.0f} seconds.")
What does happen?
And what happens in your error handler if you hit an error that isn't those two specific types?
I get error
Nope
😐
If you pass through those two if clauses, you do nothing
(error handlers should be exhaustive and always have a fallback where you do something)
IMO, completely independently of any user feedback you should always be logging the errors somewhere you can see them
any time
i have been seeing this for a while now and i dont see much going around explaining how it works? allowing bots to join servers for you, can someone provide a example on how its done?
It is an oauth scope your bot can request from users
ik it is, but how is it done and how do you use it real time?
its just an empty class i didnt override anything
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.FlagConverter.convert
its convert() method receives the context and argument just like a normal converter
I'm not sure how to do it but I know that none of the major bit libs support OAUTH scopes. So you will have to implement it yourself or find a lesser known library
i think hikari can handle the oauth2 flow if you combine their methods with a webserver, citation needed
ah, they do have an example using aiohttp as the webserver:
https://github.com/hikari-py/hikari/blob/master/examples/oauth.py
ohh i see
Is there any benefit to using match-case instead of elif statements when it comes to performance?
Hey guys, would someone be able to tell me exactly what i need to change to get my welcome image feature to work? For context I'm a beginner coder following this video: https://www.youtube.com/watch?v=Eu7X2SUOpaI&t=1030s&ab_channel=Paradoxial , the code doesnt give me any errors but when people join the server no welcome message is sent. Ive spent wayyy too many hours trying to fix. The developer intents are checked, the system message is on the correct one. And I have other cogs that run just fine so I doubt its the file structure or it not loading properly from the main.py. the code in question: https://paste.pythondiscord.com/HYWA the first section is the main.py the 2nd section is the actual welcome message cog. If someone would be able to tell me exactly what i need to change or maybe hop in a discord call for 2 minutes to get it fixed i would much appreciate 🙏
Hey guys, today we use a specific version of Pillow in Python to create ourselves some unique and professional looking welcome image cards for new members who join the server! Subscribe! :)
MY DISCORD: https://discord.gg/UqdbGp426a
MY GITHUB: https://github.com/Paradoxial8172
MY WEBSITE: http://houseofcode.xyz/index.html
DONATE: https://payp...
Some debugging would be a good first step
even as simple as just prints to see if the code you think is problematic is running at all
how would i go about doin that?
Writing print statements?
setting up the debugging
I can also tell you from watching about 15 seconds of this video that it recommends some pretty horrid practices
in general these video "tutorials" are very poor quality
Just writing print statements is sufficient
@commands.Cog.listener()
async def some_event(...):
logic1()
logic2()
logic3()
...
With this code, it is completely indistinguishable between this event never running at all, vs any of these individually silently failing. You're going in blind.
@commands.Cog.listener()
async def some_event(...):
print("the event fired")
logic1()
print("i did logic 1")
logic2()
print('i did logic 2")
...
This actually gives you some insight into what is happening. It's rudimentary, but you don't necessarily need something fancy for your own purposes that isn't meant for end users
thank you i appreciate it 👍
import cogs.ext.utils.utils as utils
def isEmbedEph(embed: discord.Embed, eph: str) -> bool:
return embed is not None and utils.configManager.isActivePlaceholder(eph) and eph in embed.title
error
name 'utils' is not defined
like what?
I did just as you suggested and sure enough the first 2 print but the next 2 do not. https://paste.pythondiscord.com/4L7Q , if udont mind, what do u think i should change with the ones that arent printing to get them to function properly?
the button doesn't work after bot restart,
My code:
@app_commands.command(name="ticketmenu", description="Sends ticket menu")
@app_commands.checks.has_permissions(administrator=True)
async def ticketmenu(self, interaction, channel: discord.TextChannel):
ticketbutton = ui.Button(label="Open Ticket",
style=discord.ButtonStyle.primary,
custom_id="ticketbutton",
emoji="📩")
embed = discord.Embed(title="Tickets",
description="**Open a ticket only if you need support!**\n**Opening tickets without a reason can get you __punished__!**\n**Make sure your issue is only related to CoffeeNetwork**\n**Please use correct category for your ticket**",
color=discord.Color.green())
embed.set_thumbnail(url=interaction.guild.icon.url)
class Pview(ui.View):
def __init__(self):
super().__init__(timeout=None)
@ui.button(label="Open Ticket", style=discord.ButtonStyle.primary, custom_id='pticketbutton')
async def TicketsButton(self, interaction: discord.Interaction, button: ui.Button):
await interaction.response.send_message('test')
view = Pview()
self.bot.add_view(view)
view.add_item(ticketbutton)
# ticketbutton.callback = self.ticket_callback
await channel.send(embed=embed, view=view)
await interaction.response.send_message(f"**✅ Ticket panel has been sent to {channel.mention}**")```
Code does not randomly stop executing. Are you seeing an error anywhere?
nope not seein any errors
A few things about this code:
- You don't need to declare the view class every time this function runs. You can declare it outside at the top level of your module just once.
- You should probably be using
@app_commands.default_permissionsrather than a local@app_commands.check - If you want things to continue working after restart, check the
persistent.pyexample in the repo (assuming you're using discord.py). It gives you two approaches for doing this
What is the code you use to start your bot? Do you get any logs from the library? Do you have any other error handlers you've declared?
yeah, i saw persistent.py, but had a little bit difficulty understanding it, and I tried adding it to the bot using the add_view func but still it didn't work (sorry my english is bad :c)
You need to call add_view when the bot restarts
not when someone runs the command again
Notice in the example how they use it
it would be the main.py which is is that first paste i sent earlier, and the only log i see is a discord log thats just letting me know the client is logging in using my token. And I havent declared any other error handlers.
hmm, so outside the command declaration right
I would recommend you remove asyncio.run, use bot.run instead, and migrate any setup into your bot's setup_hook
okay ill give that a shot, thanks again
Alternatively you could setup logging manually. But a lot of these tutorials go through this asyncio.run setup pointlessly without really realizing why
tysm solstice
This is horrible practice.
For one off debugging where attaching debuggers fries your bot, it's fine
i want to send new video publish link when some register streamer release video
how can i do that
def create_board_embed(
message: disnake.Message, board_name: str, color: disnake.Color, _: int
) -> tuple[disnake.Embed, list[disnake.ui.Button]]:
"""Create an embed dynamically for the board message based on the message content."""
embed = disnake.Embed(title=f"{board_name.capitalize()} Message", color=color)
embed.set_author(name=message.author.display_name, icon_url=message.author.display_avatar.url)
description = message.content or ""
if (
message.reference
and message.reference.resolved
and not isinstance(message.reference.resolved, disnake.DeletedReferencedMessage)
):
reply_message = message.reference.resolved
description = (
f"**Replying to [{reply_message.author.display_name}]"
f"({reply_message.jump_url})**\n\n{description}"
)
embed.description = description
if message.attachments:
attachment = message.attachments[0]
if attachment.url.endswith((".png", ".jpg", ".jpeg", ".gif")):
embed.set_image(url=attachment.url)
buttons = [url_button(label="Jump to Message", url=message.jump_url)]
return embed, buttons
Why does the attachment issue, not uploading it as embed image
nvm found a fix.
Can anyone tell me when I can find some non outdated tutorials im new to discord bot development and need some guidance to get started
Have you decided on what library you are going to use yet?
Discord and discord.ext are the only ones I know
So discord.py?
Discord and discord.ext are what you import not the library that you pip install
I have not used it but I have seen this recommended for getting started with discord.py
https://fallendeity.github.io/discord.py-masterclass/
Ye thats what I use
Do you need more resources aside from that?
A hands-on guide to Discord.py
Not unless there's anything you can think of that I might need
This is great
Oh lmao
I would recommend just generally reading the documentation
I understand if that's too much for you, though
It can be very overwhelming at times
There are also some examples in the discord.py github
I will read through the documentation tomorrow when I can get on my pc
Hi!
I have just made a Discord bot with python, and got it hosted on my raspberry pi. How do I publish it?
hello I come to you I need help or an explanation I have a bot in py that uses the discord buttons but when the bot restarts the old button no longer works which is a problem for me since it works with the gateway session id the id changes with each restart do you have a solution to save all the buttons automatically in a json or other if possible I would like to know how to do it because I am lost
Can you explain what yu mean by publish?
Put it in Discords find bots page.
What library are you using? You will need to add buttons to the bot with the same custom_ids as the buttons on discord
Am I able to do that?
go to discord.dev
requests + discord.py
did you see what i told you in #python-discussion
no sorry
async def profile(self, interaction: discord.Interaction, button: discord.ui.Button):
?
because I had read that it was possible to save the button ids in a json but I didn't understand
proof that yes I use 🙂
i didnt even
It depends on your usecase
okee
well in fact there is an embed we fill it after it sends the information in a room with a button on it in order to react if the bot restarts the button no longer works which blocks my project
in the big lines
When you press the button what needs to be done?
even better can you show your button callback
well once you press the button the bot sends a message in dm if the bot restarts the getwey changes so the button does not follow
I think all you have to do is verify your bot, then turn it on. I think you can verify your bot at any server count now too
Is the message always the same or does it have information related to that specific button?
I want to publish it for others to find.
Can someone tell me wheres the main chat?
for python, help, or off topic discussion?
About Programing chat?
the basic message remains the same only after sending the form the information changes but the base of the embed does not change nor the button an embed = a button
If i understand what you mean you should just be able to add custom_id = "The_Custom_ID_For_This_Button" to your button decorator
I don't need to make a json that keeps everything? because it currently works but if the bot restarts then the getwey also changes since a connection an id that's the problem
You only need to keep track of the custom_ids whenyou are storing information in the view object that cannot be retrieved from the interaction
I have to go for a while and will be unable to help until I am back
mhh okay
@stark ingot
from discord.ext import commands
import json
import os
bot = commands.Bot(command_prefix="!")
# Fichier de stockage pour les boutons
BUTTON_DATA_FILE = "button_data.json"
# Fonction pour charger les données des boutons
def load_button_data():
if os.path.exists(BUTTON_DATA_FILE):
with open(BUTTON_DATA_FILE, "r") as f:
return json.load(f)
return {}
# Fonction pour sauvegarder les données des boutons
def save_button_data(data):
with open(BUTTON_DATA_FILE, "w") as f:
json.dump(data, f)
# Classe pour créer les boutons
class PersistentView(discord.ui.View):
def __init__(self, message_id):
super().__init__(timeout=None)
self.message_id = message_id
@discord.ui.button(label="Bouton 1", custom_id="static_button_1")
async def button_1(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message("Tu as cliqué sur le Bouton 1")
@discord.ui.button(label="Bouton 2", custom_id="static_button_2")
async def button_2(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message("Tu as cliqué sur le Bouton 2")
# Commande pour créer des boutons et sauvegarder l'ID du message
@bot.command()
async def create_buttons(ctx):
view = PersistentView(None)
message = await ctx.send("Clique sur un bouton :", view=view)
# Sauvegarde l'ID du message et les boutons
button_data = load_button_data()
button_data[str(message.id)] = {"message_id": message.id}
save_button_data(button_data)
# Lorsque le bot démarre, recharge les boutons pour les messages existants
@bot.event
async def on_ready():
print(f"Bot connecté en tant que {bot.user}")
# Récupère les données des boutons sauvegardés
button_data = load_button_data()
# Recrée les boutons pour chaque message sauvegardé
for message_id, data in button_data.items():
channel = bot.get_channel(123456789012345678) # Remplace par ton ID de salon
message = await channel.fetch_message(int(message_id))
view = PersistentView(message_id)
await message.edit(view=view)
# Lancer le bot
bot.run("YOUR_TOKEN")
```I asked the question to chat gpt basically should I take inspiration from that?
have you tried using dynamic items instead? that way you dn't have t keep track of every button you send
if I need to keep all the buttons precisely on 2 specific rooms
that it is better to store everything or the dynamic because the problem is getwey if the bot restarts that the ids do not follow
then you don't need to store it anywhere and just do py bot.add_dynamic_items(you_dynamic_item)
the id will follow
because dynamic items store their data USING the id
yes but the id with Gateway (Session ID: it does not follow if? if the bot restarts the id will change so the chain will be lost
nothing to do with the session id
whenever you send any component, that has a custom id on it. dynamic items put data into that custom id. That stays the same forever on the components on that message unless you edit it yourself
I will try I just have to add the list no need for anything else?
what list
?
please just reference the example shown in this guide
okay
the best I can do is go through dynamic or custom id or directly through a stock in json
json is not a storage solution
okay
Sorry I'm new to Discord buttons too. Would you consider this a dynamic or persistent view?
https://paste.pythondiscord.com/OMTA
that's persistent.
What in the code would I need to change to make it dynamic?
This is my main, finally got undisabled, was using @dense scaffold acc 😂
Hey man. I'm glad to hear that you recovered your old acc!
Are you using discord.py? I don't remember if i previously asked you
Indeed I am
ah yes, sorry just seen the code
dynamic items are just another way of registering existing components to work. You don't need, or really want, to do both
import discord
from discord.ext import commands
class AskBtn(discord.ui.View):
def init(self, target: discord.User):
super().init(timeout=None)
self.value = None
self.target = target
# Dynamically add the button when initializing the View
self.add_dynamic_button()
def add_dynamic_button(self):
# Modifier dynamiquement les propriétés du bouton
button_label = f"Envoyer une demande à {self.target.display_name}"
button_style = discord.ButtonStyle.green if self.target.bot else discord.ButtonStyle.blurple
# Ajouter dynamiquement un bouton avec label et style personnalisés
button = discord.ui.Button(label=button_label, style=button_style)
# Associer l'action à l'événement de clic du bouton
button.callback = self.ask_callback
# Ajouter le bouton à la vue
self.add_item(button)
async def ask_callback(self, interaction: discord.Interaction):
# Logique lors de l'appui sur le bouton dynamique
if isBlacklisted(interaction.user.id):
await interaction.response.send_message(embed=discord.Embed(
title="",
color=discord.Color.red()).add_field(name="", value="Tu ne peux pas intéragir car tu as été banni(e) du système de MATCH"), ephemeral=True)
return
if isBlacklisted(self.target.id):
await interaction.response.send_message(embed=discord.Embed(
title="",
color=discord.Color.red()).add_field(name="", value="Cette personne a été banni(e)."), ephemeral=True)
return
if not isComplete(interaction.user.id):
await interaction.response.send_message(embed=discord.Embed(
title="",
color=discord.Color.red()).add_field(name="", value="Tu dois avant tout finir de créer ton profil !"), ephemeral=True)
return
if self.target == interaction.user:
await interaction.response.send_message(embed=discord.Embed(
title="",
color=discord.Color.red()).add_field(name="", value="Tu ne peux pas t'envoyer une demande à toi-même !"), ephemeral=True)
return
# Si toutes les conditions sont bonnes, envoie une réponse positive
await interaction.response.send_message(embed=discord.Embed(
title="Demande envoyée",
color=discord.Color.green()).add_field(name="", value=f"Ta demande a été envoyée à {self.target.display_name} !"), ephemeral=True)
Commande d'envoi avec bouton dynamique
bot = commands.Bot(command_prefix="!")
@bot.command()
async def envoyer(ctx, member: discord.Member):
view = AskBtn(target=member)
await ctx.send(f"Envoyer une demande à {member.display_name}", view=view)
it's good in dynamics finally you think that it solves the problem
!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.
sorry
@young dagger https://paste.pythondiscord.com/NR2Q 🙂
if you can tell me if it's like that I asked chat gpt for inspiration to be sure to start correctly
This isn't a dynamic item at all
you should never be creating a generic Button object and stapling callbacks onto it
🤷♂️
I don't understand anything
It's probably the right play to read the official docs, then ask targeted questions on what you specifically don't understand
https://paste.pythondiscord.com/IVJA is it better?
anyone know how to add mutliple languages to discord bot
I think there's a misunderstanding here of what "dynamic" means
In the context of persisting/making buttons work after restart, this very specifically refers to buttons/selects that subclass DynamicItem and implement the methods mentioned in the example. Your code does not do that
python bot = https://paste.pythondiscord.com/raw/YMXA
# notice that in line 94 u can change title and embad color
?
you are confusing us, Yousef.
what is the parameter kind in commands.Parameter? what do i set it to?
that came from inspect.Parameter.kind, you're not suppose to set it, what are you trying to do?
!d inspect.Parameter.kind
Describes how argument values are bound to the parameter. The possible values are accessible via Parameter (like Parameter.KEYWORD_ONLY), and support comparison and ordering, in the following order:
i came across commands.Parameter and it gave me an error saying kind is required, well i figured it out to use commands.parameter instead
commands.param for the shorten one
🤷🤷🤷

I need someone who have stripe and a confirmable country for me to confirm my bot, my friend country to confirm payout is not available anymore, and my country, Brazil, is also not available to confirm payout. I need help so my bot can be in more than 100 different servers, please can anyone help?
You need to find someone who you can trust. Not someone random. You have to transfer ownership of the bot to them so if it is someone random they can steal the bot
That person also needs to trust you because I believe the person who verifies is responsible for any legal actions that occurs
complicated
i put all my efforts into this bot
but discord don't help
Yeah, I'm not sure why some regions are banned. But it would be worse if someone deleted your bot.
i see
why do i get an error when im importing dotenv
@stark ingot you should know
can u help?
What environment are you using in your workspace?
Looks like VS code
ye
I mean like python virtual environment
how do i check
It should say in the corner, but you cut that off the screenshot
full screenshot
Looks like you don't have a virtual environment selected
Show the full output of the pip command you ran?
i have an interpreter if thats what u mean
just getting it but my name is mentioned multiple times so im just getting chatgpt to change all of them to Admin
its a big message where do u want me to put it
should i put it in a file and send it here
@sage crown here https://paste.pythondiscord.com/IPGA
The pypi package dotenv is actually a decoy intented to confuse you. You actually want python-dotenv
https://pypi.org/project/dotenv/ see how this was released in 2015?
ye?
Nothing that old will work anymore
i already did it in cmd
It's actually at https://pypi.org/project/python-dotenv/
thats the one i used
I know and it didn't work
No it isn't
no i used this one in cmd
It just says this:
pip install python-dotenv
Requirement already satisfied: python-dotenv in c:\users\Admin\appdata\local\programs\python\python311\lib\site-packages (1.0.1)
Ah that's the wrong pip
huh?
You need to see what interpreter Vscode is using
If you use Ctrl + Shift + P and select interpreter it should show you which one you picked
You're better off creating a .venv virtual environment in your workspace folder though
Yeah so hit + create virtual environment
Hit show logs
Maybe you have to pip install them again
Now you need to install the deps into the created virtual environment
If you open a terminal in vscode it should activate it for you
Meaning you still get those errors?
Show the terminal?
@topaz lodge ^
?
What do you get when you run where python?
Hmm nothing?
What happens if you run the script? It should print the python version to the terminal as well
Could be a problem with the linter since you installed them in a venv, not sure tho
for role.position, do I need to adjust the position for all roles? Cuz I have a "key-role" and I want to create a new one and set it over the "key-role".
I just got like role.edit(position=ey_role.position + 1)
and that doesn't quite work, the position is still at the bottom
when the role is newly created
and the bot role is on top of every role so it's not a permissions-issue
:incoming_envelope: :ok_hand: applied timeout to @last granite until <t:1726598536:f> (9 minutes and 59 seconds) (reason: duplicates spam - sent 4 duplicate messages).
The <@&831776746206265384> have been alerted for review.
Hi. I'm trying to learn py-cord using this guide:
https://guide.pycord.dev/getting-started/creating-your-first-bot
But it seems to be outdated, and it doesn't work for me...(according to google this guide is for 1.x versions of pycord, whilst the newest one should be 2.x). Does anyone have a good tutorial that I can learn everything from?
Excited to create your first bot? Once you install Pycord, you can start right
try it with discord.py instead
try checking the documentation for Role.position
Long time ago when I tried discord.py, it didn't have a lot of features that other versions have. Does discord.py do everything that pycord can?
Most probably
Alright. Is there some guide for starting and coding discord.py? Not just the docs
No
Pycord is superior. Discord.py doesn’t let you record audio from voice channels.
AI GPT Calling is the future, thus pycord is the future
I’d suggest pycord examples GitHub. They have a ton. Also just ask chatgpt for some.
Take inspiration from GitHub projects
chatgpt will tell you 3 isn't a prime number
what are you on about
Also audio receive isn't even supported by discord. It's also rife for privacy concerns, I have yet to see someone implement this legally and ethically
"legally" and "ethically", how?
it's not even documented so it's not supposed to be implemented at all
it's impossible to solve privacy concerns from a library perspective, IMO discord should do something about it: document the feature and enforce a new priviledged Intent or permission, and inform users with a prompt that it's being registered / listened by a Bot
In theory a bot could implement that opt in, plus protection of data privacy rights. I have yet to see someone even care about doing that though
But either way, weird criterion to pick a library on whether or not they support something the system itself doesn't even support
shouldn't a Bot like that be banned if discovered by discord, even though it protects the privacy of the users etc... it's still not supposed to be done
Discord refuses to ban things that are far more egregiously against law/tos
like? that's surprising
Mee6 continues to exist besides literally scamming people, violating gdpr, you name it
So in theory, me as a user could make a lawsuit to both mee6 team and discord
not that i have the money 
pycord is a rewrite of discord.py
is this just a ticket in their help website?
No, they refused to respond to me so it is with my gdpr officer
no it's free lol
4o mini says otherwise
I too can cherry pick screenshots
point being not that it is never wrong, but that it is not always right and very confident about it
What exactly is not working? Almost everything in the guide should still work. If it does not I will update it.
The guide also has content for 2.x versions.
Note we do have a bug on our docs website that says that the docs are for version 0.1 but it is actually the latest version. Just a bug in the docs code
good point
i literally just tested it 😭
The example I had was less of a direct question. It gets confused when it has to juggle multiple concepts, and will very confidently assert things that are blatantly wrong
Could someone show me how to make a slash command option accept attachment upload within Pycord?
[2;35masync def[0m [2;34mnew[0m([2;31mself[0m, [2;31mctx[0m: discord.ApplicationContext, [2;31mattachment[0m: [4;2m[1;2m[1;40mdiscord.SlashCommandOptionType.attachment[0m[0m[0m= [0mdiscord.[2;34mOption[0m([2;31mdescription[0m=[2;36m"Upload optional attachment"[0m, [2;31mrequired[0m[2;34m=[0m[2;31mFalse[0m)):
I have also tried:
[4;2m[1;2m[1;40mdiscord.Attachment[0m[0m[0m
both end up as string inputs ¯_(ツ)_/¯
It will usually assert whatever you ask.
You can follow this example:
😭
an option decorator would be lovely, but that just gets me errors
Why?
I personally use the decorators
But you can use the Option object directly in the function parameter
could you link docs about them?
https://docs.pycord.dev/en/stable/api/application_commands.html#discord.commands.option
This decorator can take all the parameters of discord.Option() but you have to pass it the name of the function argument as the first argument.
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
As in the example I sent you
just out of curiosity what do your imports look like for this example?
You can import from the discord module
from discord import option, ApplicationContext, ...
Your example works, I just had to add 'discord.' in front of things 😔
Very enlightening, TY.

tsk tsk imagine not using o1 preview (i havent used it either)
Hi?
I haven't seen you in a while mf
Yeah it's been a long long time
Imagine coming back then immediately trying to make a discord bot again
At least learn something new 😭
yo i needed help with a discord bot (sort of)
its not exactly a discord bot but a script that automates something within discord and idk where else to ask
need help getting auto captcha working
is it worth to make a discord bot in python ?
If you're talking about selfbots, do know that it is against discord TOS
It depends, it could be a good learning project
define selfbot
Automating user accounts
as in using a script to type for me?
Since you said it's not exactly a discord bot
Type for you? Send messages through your account without you actually doing it? Yes, that's selfbotting.
import pyautogui
import time
time.sleep(5)
while True:
pyautogui.write("/fish")
time.sleep(0.1)
pyautogui.press('tab')
time.sleep(0.1)
pyautogui.press('enter')
time.sleep(15)
so this is a selfbot
if so im not using it ;]
as of now yes
What are you even trying to do? Run slash commands?
i just open my discord and run that (allegedly)
its a fishing minigame in a server
/fish and you catch a fish and sell it
Ah, yeah I don't think that counts as selfbotting exactly
it works but i need a way to detect the captchas and solve them
Which captchas are we talking about?
never done any complex project before only minor school stuff hence im struggling pretty bad
tried a brute force approach and got timed out from fishing for an hour 😭
Well of course, you'd want to maintain a time gap with each time you run it at least, and with the captcha, you're on your own
you get something like 3 attempts at the captcha before you get a punishment with no time limit
You have to enter it yourself/not brute force it so you don't get the captcha at all, again, I have never used that bot so 
i worded that badly, the 3 attempts arent timed - you get three tries before a penalty
It is against tos to write any automation that utilizes a user token
I’m not using my or any token so I’m good
how do you think the discord client communicates with discord
there is not a meaningful distinction between automation clicking on the client and automation making calls directly
I’m not smart enough to know what you mean
you cannot automate a user account in any way
I gathered but I’m basically just using pyautogui to type and click for me so surely there’s a way to detect the captcha messages on my screen without having to incorporate my account in the script
this is not allowed
Aw
okay then how can I detect an image on my screen for an u related project
it is pretty obvious this is related. Don’t ask about this project again
🗿👍
tbf didn’t know it wasn’t allowed but mb
In general if any sort of game is
- connected to the internet in any way
- OR has a leaderboard/point system of some sort.
It will be breaking a rule from someone. It is also not fun for other people who are playing the game without cheating. Also after you run a script like that there is no fun in the game for you anymore so you will end up quitting anyways.
What does that have to do with discord bots

PS C:\Users\mitro> & C:/Users/mitro/AppData/Local/Microsoft/WindowsApps/python3.11.exe "c:/Users/mitro/Desktop/Novi Bot Novi Pocetak )/main.py"
Traceback (most recent call last):
File "c:\Users\mitro\Desktop\Novi Bot Novi Pocetak )\main.py", line 10, in <module>
from cogs.clear_command import Clear_Command
File "c:\Users\mitro\Desktop\Novi Bot Novi Pocetak )\cogs\clear_command.py", line 5, in <module>
from discord import Option
ImportError: cannot import name 'Option' from 'discord' (C:\Users\mitro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCac he\local-packages\Python311\site-packages\discord_init_.py)
How to fix this
What library are you using?
idk how can I check
show your pip list
You also installed some discord library at some point
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.
all of the above 😭
How much code do you have so far?
You ultimately will need to pick one discord library, uninstall the rest, and then reinstall that one
You have to decided what library you are using or that you want to use because you currently have 5+ installed
They break each other if they are installed at the same time
can I just delete everything and just install python again too my pc and install the discord import
so I mean to delete python from pc
You could, but you really don't need to
Im not sure if deleting python removes packages
Throwing the baby out with the bathwater. Just uninstall the packages you don't need
It would help if you used a virtual environment like venv so you can sort your packages better.
@bot.command()
async def buy(ctx, item_id: int, amt: int = 1):
await open_account(ctx.author)
users = await get_bank_data()
user = ctx.author
for item in shop_item:
id = item["id"]
name = item["name"]
price = item["price"]
id = int(id)
if item_id == id:
break
if item_id > id:
await ctx.send("There is no item code like that.")
return
cost = eval("price*amt")
cost = int(cost)
view = discord.ui.View()
async def Wallet_callback(interaction):
await interaction.response.defer()
if users[str(user.id)]["Wallet"] < cost:
await ctx.send("You don't have that much money.")
else:
await ctx.send(f"You have brought {name} {amt}x for ${cost}")
users[str(interaction.user.id)]["Wallet"] -= cost
for i, item in enumerate(users(str(interaction.user.id)["Bag"])):
if item["ID"] == id:
users[str(interaction.user.id)]["Bag"][i]["amt"] += amt
break
else:
users[str(interaction.user.id)]["Bag"].append({"ID": id, "amt": amt})
break
await save_data_bank(users)
view.stop()
async def Bank_callback(interaction):
await interaction.response.defer()
if users[str(user.id)]["Bank"] < cost:
await ctx.send("You don't have that much money.")
else:
await ctx.send(f"You have brought {name} {amt}x for ${cost}")
users[str(interaction.user.id)]["Bank"] -= cost
for i, item in enumerate(users(str(interaction.user.id)["Bag"])):
if item["ID"] == id:
users[str(interaction.user.id)]["Bag"][i]["amt"] += amt
break
else:
users[str(interaction.user.id)]["Bag"].append({"ID": id, "amt": amt})
await ctx.send("added")
break
await save_data_bank(users)
view.stop()
Wallet_button = discord.ui.Button(label='Wallet', style=discord.ButtonStyle.grey)
Wallet_button.callback = Wallet_callback
Bank_button = discord.ui.Button(label='Bank', style=discord.ButtonStyle.grey)
Bank_button.callback = Bank_callback
view.add_item(Wallet_button)
view.add_item(Bank_button)
msg = await ctx.send("How would you like to pay?", view=view)
await view.wait()
await msg.delete()
Can anyone tell me what is wrong in this command
Show your traceback
Showing only the code does not help, it shows what kind of error or problem you have
K
2024-09-19 08:20:15 ERROR discord.ui.view Ignoring exception in view <View timeout=180.0 children=2> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='Bank' emoji=None row=None sku_id=None>
Traceback (most recent call last):
line 430, in _scheduled_task
await item.callback(interaction)
File "<string>", line 335, in Bank_callback
TypeError: string indices must be integers, not 'str'
2024-09-19 08:20:20 ERROR discord.ui.view Ignoring exception in view <View timeout=180.0 children=2> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='Wallet' emoji=None row=None sku_id=None>
Traceback (most recent call last):
line 430, in _scheduled_task
await item.callback(interaction)
File "<string>", line 318, in Wallet_callback
TypeError: string indices must be integers, not 'str'
2 error
@dapper cobalt ??
What does users[str(user.id)] return?
Users is a helper function and it loads the json file named mainbank.json
Yeah, what does it return
Oh
Try printing users[str(user.id)]
users[str(user.id)] = {}
{"1229961335287058545": {"Wallet": 10000, "Bank": 9990000, "Bag": []}}
Does it print {}?
The number are the id
Is that helps
In that case, can u screenshot line 335 and 318?
for i, item in enumerate(users(str(interaction.user.id)["Bag"])):
if item["ID"] == id:
for i, item in enumerate(users(str(interaction.user.id)["Bag"])):
if item["ID"] == id:
Both are same
I'm not sure, but you can try replacing it with this:
for item in users(str(interaction.user.id)["Bag"]):
if item["ID"] == id:
Hold, i found the problem
You replaced [] with ()
for item in users[str(interaction.user.id)["Bag"]]:
if item["ID"] == id:
Should work
Np
Dam
My mistake and I didn't event seen that
Btw really really thanks for the help
Does anyone have a bot using pycord on github I can take a look at and see how y'all did it? Trying to figure pycord out
Yeah but these are single files. I'm trying to see a project that used cogs and stuff
Cogs have nothing to do with files
https://github.com/Dorukyum/Bond This is a bot by one of the core devs of py-cord. Im pretty sure it follows best practices.
Hope it is not too advanced
I mean like these files create the bot instance and a single command there, and creating commands in cogs is abit different so I wanted to see some examples of a project using cogs
alright thank you
I did not want to recommend my old bot as the code is not very good but the link I sent does things in a more advanced way then needed. I guess it was not the best example.
https://github.com/Icebluewolf/SurveyWolf/tree/main/bot is a more beginner friendly way to look at making cogs.
IMO these examples that conflate extensions with cogs, and that imply they must be 1:1, are a bit reductive. I strongly suggest reading the docs on these concepts separately and making informed decisions, vs just repeating a pattern
I see what you mean but the docs themselves even suggest that they are used one-one most of the time.
I also dont know any examples that do not use them one-one, so I cant do much
Use discord.py fr
Forget about the old news that it got discontinued
It's maintained rn
Thats not really good advice
They choose to use pycord there is no point to switching
I'm not advising a stranger
pycord is better than discord.py in some things
I tried both and it's easier to understand (for me)
There aren't much differences that affect understanding
I had problems with creating application commands in discord.py and searching for solutions on Google I found that library and it was easy to understand 
2024-09-19 11:23:24 ERROR discord.ui.view Ignoring exception in view <Verific ationView timeout=None children=1> for item <Button style=<ButtonStyle.secondary : 2> url=None disabled=False label='Click to Verify' emoji=<PartialEmoji animate d=False name='check_mark' id=1185706844665159820> row=None sku_id=None>
Traceback (most recent call last):
File "/usr/local/lib/python3.12/site-packages/discord/ui/view.py", line 430, i n _scheduled_task
await item.callback(interaction)
File "/cogs/verification.py", line 95, in start_verification
await interaction.response.send_message(embed=embed, file=file, view=view, e phemeral=True)
File "/usr/local/lib/python3.12/site-packages/discord/interactions.py", line 8 55, in send_message
await adapter.create_interaction_response(
File "/usr/local/lib/python3.12/site-packages/discord/webhook/async_.py", line 221, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
You have to respond within 3 seconds
How do I fix this?
Respond within 3 seconds 😂
That itself has to be done within 3 seconds
So either there are long running processes before you respond, or your entire bot has something blocking
Here is my code https://paste.pythondiscord.com/ONSA
You should not be making generic views and buttons and stapling callbacks onto them
Either way this is taking more than 3 seconds and it's on you to debug why
(As an aside, static image based captcha is effectively useless. This isn't giving you anything besides pissing off users)
What should I do instead?
There is an arrow in the error that is pointing to what is wrong.
: is not a valid character for being in between and object and a method
Show
nvm i fixed it, thanks anyway 
Make view classes
Is this better?
https://paste.pythondiscord.com/VE7A
skibidi dop dop
Beyond the fact that image captchas don't do anything, yes
Did you see the captcha images to determine that?
I think what they mean is, the fact that it's a set of predefined images that will eventually (and commonly) repeat, renders it pretty useless
The purpose of captcha is to prevent automatic processes from doing something. Simple static images where you detect a word in it does not accomplish that. These are trivially easy to break
My code function in pycharm but not in daki, it’s a database for "mariage"
Why ?
conn = await aiosqlite.connect('database.db')
try:
cursor = await conn.cursor()
# Crée la table proposals avec la colonne timestamp
await cursor.execute('''
CREATE TABLE IF NOT EXISTS proposals (
id INTEGER PRIMARY KEY AUTOINCREMENT,
proposer_id TEXT NOT NULL,
proposer_name TEXT NOT NULL,
proposee_id TEXT NOT NULL,
proposee_name TEXT NOT NULL,
guild_id TEXT NOT NULL, -- Ajout du champ guild_id
status TEXT NOT NULL,
timestamp DATETIME NOT NULL -- Ajout de la colonne timestamp
)
''')
# Crée la table mariage
await cursor.execute('''
CREATE TABLE IF NOT EXISTS mariage (
id INTEGER PRIMARY KEY AUTOINCREMENT,
partner1_id TEXT NOT NULL,
partner2_id TEXT NOT NULL,
guild_id TEXT NOT NULL, -- Ajout du champ guild_id
date TEXT
)
''')
await conn.commit()
finally:
await conn.close()
# Fonction pour ajouter la colonne timestamp si elle n'existe pas
async def add_timestamp_column():
conn = await aiosqlite.connect('database.db')
try:
cursor = await conn.cursor()
# Vérifie si la colonne timestamp existe déjà
await cursor.execute("PRAGMA table_info(proposals);")
columns = await cursor.fetchall()
if not any(column[1] == 'timestamp' for column in columns):
await cursor.execute('ALTER TABLE proposals ADD COLUMN timestamp DATETIME')
await conn.commit()
finally:
await conn.close()```
async def recreate_mariage_table():
conn = await aiosqlite.connect('database.db')
try:
cursor = await conn.cursor()
await cursor.execute('DROP TABLE IF EXISTS mariage')
await cursor.execute('''
CREATE TABLE mariage (
id INTEGER PRIMARY KEY AUTOINCREMENT,
partner1_id TEXT NOT NULL,
partner2_id TEXT NOT NULL,
guild_id TEXT NOT NULL, -- Ajout du champ guild_id
date TEXT
)
''')
await conn.commit()
finally:
await conn.close()
# Fonction de vérification des tables existantes
async def check_tables():
conn = await aiosqlite.connect('database.db')
try:
cursor = await conn.cursor()
await cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = await cursor.fetchall()
print("Tables dans la base de données:", tables)
finally:
await conn.close()
# Fonction principale
async def main():
await create_tables()
await add_timestamp_column() # Ajoute la colonne timestamp si nécessaire
# Si tu veux recréer la table mariage, décommente la ligne suivante
# await recreate_mariage_table()
await check_tables()
# Démarrage du script
if __name__ == "__main__":
asyncio.run(main())```
Once one of the views times out, it affects the other instances as well, leading to the second set of buttons becoming unresponsive. Do you have any clue why? @fast osprey
You have multiple view types here. You need to be more specific
So when they click on "Click to Verify" it sends the embed with the buttons. After 60 seconds (see the timeout in the CaptchaAnswerView class), I want it to remove the message. It does remove the message, but it times out if they have another instance as well (not removing it, but it stops responding to it)
What is the exact flow you're following?
I want to delete the embed that is created with async def start_verification
After 60 seconds
There is a timeout for class CaptchaAnswerView. When there are two instances open and the first times out, the second one stops responding too, even within the 60 seconds
How are these two connected to the same timeout?
Did you check the code?
@discord.ui.button(label="Click to Verify", style=discord.ButtonStyle.secondary, emoji=discord.PartialEmoji(name="check_mark", id=check_mark_emoji_id), custom_id='verification:start')
This one sends a message right
They click on Click to Verify it sends them await interaction.response.send_message(embed=embed, file=file, view=view, ephemeral=True)
The view is received from class CaptchaAnswerView
There is a timeout super().__init__(timeout=60)
On timeout it disabled the buttons
async def on_timeout(self): for item in self.children: if isinstance(item, discord.ui.Button): item.disabled = True
When it does, it disable other buttons too
Where are these "other buttons"
You click once and wait 40 seconds, and click again. You are expecting the first one to timeout in 20 seconds, but so does the second one
How are they coming to exist
What does this mean?
Buttons*
What actually happens on message 2? Is this all of your code? What you're describing isn't default behavior
You can debug this by giving the view instances some kind of uuid if you want and logging that out
The first one is expected to be time outed (after 60 seconds), not the second one (after 20 seconds)
@fast osprey
You need to do some debugging here
And not just look at the code and guess
Is the timeout method being called? Are these the same actual python objects?
Yes. Is this how you would do it?
https://paste.pythondiscord.com/ILRA
view.message = message
Than use it for class CaptchaAnswerView
async def on_timeout(self):
for item in self.children:
item.disabled = True
if self.message:
await self.message.edit(view=self)
How do you know if that is being called?
on timeout?
t'as essayer pip install aiosqlite?
ou tu l'a deja fait ?
J’ai trouver l’erreur, avoir accès aux database sur daki c’est payant
Yes, the timeout is being called
But it's not actually editing the message
message = await interaction.response.send_message(embed=embed, file=file, view=view, ephemeral=True) # noqa
view.message = message
pretty sure this doesn't work discord.InteractionResponse.send_message returns None
That would result in an error when they later try to use it, which is probably at least part of the problem
if they don't see that error, that's the first thing to fix
looks like this is the only place it's being used:
# Edit the original message to disable the buttons
if self.message:
await self.message.edit(view=self)
There is no error message. My problem is on_timeout method currently doesn’t distinguish between different users
though it is a bit strange that actions taken on one view affects all of them
calling .edit on None would cause an error
so you're either not calling that, or you're eating the error and you need to fix that
# Edit the original message to disable the buttons
if self.message:
await self.message.edit(view=self)
i think you need to think about this a bit more. it seems like you slapped it on there because the type checker was complaining at you (and rightfully so) without thinking of why or the consequences
I removed it, and it's still timing out for all users
https://paste.pythondiscord.com/DHMA
though tbh the way i've always done it is use view.wait() to wait for the view to expire from within the caller rather than handle it in on_timeout
And how many timeout methods are firing?
Once for every instance
If they are separate instances, it's not the library
and if you've proven that
on_timeout fires when that view object times out, which happens x seconds after the last interaction on that object
The buttons stop working in betweeen
For both users
When view timeouts for first user, it does that for second user as well
what is the rate-limit for changing a channel name? I have a loop that runs every minute which changes a channels name and I'm getting rate-limited
You should not be doing that
discord does not want you rapidly changing channel names
That's what they decided. Channel names aren't for that
they are meant to show the purpose of a channel. Not a placeholder for random data
Because I tried with my alt account to see if it affects other users as well, and it does
None of those prints tell you whether or not it's the same object
2 changes per 10 minutes iirc
i dont think its officially documented and is subject to change but that's what i've noticed
for one specific channel? Or globaly
per channel
okay
(i think)
can you show us your full code
Sure
there is no print, and you just removed the timeout completely?
This isn't going to work well if you run code A when you tell us what's happening and then send us code B
Yes I removed the print. The issue is still the same
I didn't change the codes behaviour by removing one print
so let me get this straight:
- user 1 clicks "Click to verify" button, embed with button gets sent for them (view 1)
- 20 seconds passes
- user 2 clicks "Click to verify" button, embed with buttons gets set for them (view 2)
- 40 seconds passes
- view 1 times out, causing view 2 to also time out?
No, but you remove our ability to check your work
Yes

That just isn't how timeouts work in the library
something else is going on here
I have been trying to solve this for 8 hours now 
are your interactions still failing when you press the button?
How do you mean?
is this still happening
When I press on Click to Verify it creates new instances yes
no, i mean when you click on one of the buttons 1-4, does it work as expected?
Yes, but it has to be a fresh instance after the timeout
So it's time outing out all instances that are "running"
and you believe that because your alt account was unable to use the buttons after your main account had allowed it to elapse the timeout?
Yes
Because if I create two instances by my own, both of them stops working after first gets timed out
are you creating them at the same time?
Can you put the prints back in, show us that code, and do it with one account
No, close to the timeout just to make sure
so the 2nd instance pretty much stops responding almost immediately?
Timeout set to **10 seconds **for this example
- user 1 "Click to verify" button, embed with button gets sent for them (view 1)
- 5 seconds passes
- user 2 clicks "Click to verify" button, embed with buttons gets set for them
- 5 seconds passes
- view 1 times out, causing view 2 non responding
- 5 seconds passes
- view 2 times out
^ also do this. include timestamps for when the view was sent, along with the timestamps for when it was expired and for what user
this is expected.
10 seconds passes
at this point it's been 15 seconds since view 1 was sent, so it's already timed out
it's also been 10 seconds since view 2 was sent, so it just times out
My bad
I changed it
view 1 times out, causing view 2 non responding
5 seconds passes
view 2 times out
how are you making a differentiation between "not responding" and "timing out"?
This interaction failed
it does the same thing for timeouts
I know
so how are you differentiating between not responding and timeout?
if the end result is the same?
It's happening in between before last print
yes, we asked to show the code with those print statements
And we don't know how those prints are behaving. Because you removed them
That's not the timeout
It could be eaither way right?
True. But there is no way to click on the buttons for user 2
you need to check that the wait method returned True
So I assume it's from the timeout
You shouldn't assume
you should log from the timeout
More logs don't cost you anything
also if you could attach timestamps that would be useful
maybe look into actual logging later
@fast osprey @sick birch Tried to click on one of the four buttons in between red
So clearly they aren't timing out at the same time
No but why does the second instance stops working?
Because it timed out?
You said yourself that they didn't time out at the same time, and I tried before the second timeout
Marked in red
Views time out if they have not been interacted with for the duration of the timeout
ok so they are timing out individually
nothing else causes that
can you do the same thing like this but add a timestamp for when a user presses a button:
class CaptchaAnswerButton(discord.ui.Button):
...
async def callback(self, interaction: discord.Interaction):
print(f"[{discord.utils.utcnow().strftime("%Y-%m-%d %H:%M:%S")}] User pressed button {self.label}")
It's also not entirely clear that this label is unique
No print from CaptchaAnswerButton
really? and the print is the first line?
You said the exact same thing right? Open 2 instances and wait for the first one to time out
no, click on it before it times out
So open two instances and click on one of the buttons (1-4) before the first one times out?
after the first one times out, but before the 2nd one does. increase the timeout to give yourself more time if necessary
if the 2nd one responds fine even if the first one is timed out then your views are working as intended
Same issue, and no print from class CaptchaAnswerButton
can you give a step by step of what exactly you did on discord
- Pressed "Click to verify" button (1)
- Waited 5 seconds
- Pressed "Click to verify" button (2)
- View 1 timed out (10 seconds)
- View 2 is not responding
After that View 2 timed out as well
Same as before
so the callback is not being called even though the view is not timed out
But only if there is more than one instance
try removing the custom_id argument in CaptchaAnswerButton's super initializer
It does
Yes for persistent view
class VerificationCog(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
self.bot.add_view(VerificationView())
comment it out for now
But then I can't click on the Click to Verify button
is the button you're trying to click from earlier, before a restart?
just send a new one
Doesn't change anything, same issue
I added time.time() for the custom ID for the CaptchaAnswerButton and it solved the issue
class CaptchaAnswerButton(discord.ui.Button):
def init(self, label: str, correct_answer: str):
super().init(label=label, style=discord.ButtonStyle.secondary, custom_id=f'captcha:{label}:{time.time()}')
that makes sense
it probably wants a unique button ID
though i'm not sure why discord.py isn't generating one for you
What would make it more unique than using time?
maybe a UUID
Do you know what could cause this?
Should be enough?
self.unique_id = str(uuid.uuid4())
super().__init__(label=label, style=discord.ButtonStyle.secondary, custom_id=f'captcha:{label}:{time.time()}:{self.unique_id}')
Never mind, I changed some things that depended on the custom_id, removed the custom_id, and it’s still working
Thanks Robin 
Hello
I am trying to make a transcript for my discord ticket bot, so it can record the messages and any info inside the channel
But i keep failing
Can someone help me?
Are the users consenting to having their messages recorded, and are you giving them a mechanism to ask for their data to be deleted?
What do you think this is, A Court Room?
Not really the answer of someone who has thought about those things, which is in the TOS
Okay but my ticket is for support only and i made a custom ticket bot. I just need my transcript to be saved in a channel for future learning.
Also i made the transcript to be saved but when i go to view it, it's with a white background with no colours nor logos
Right, and if you take messages that users sent and put them somewhere else, that needs to be communicated in your privacy policy and you need to give them a way to request you to delete it.
Alternatively, leave the messages as-is in an archived discord thread where their privacy rights are maintained
Yes i made a separate channel for that