#discord-bots
1 messages · Page 392 of 1
yeah sure add me if you need to
lol
you forgot to censor the last line lol
not serios haha
Hey, i want to upload and publish my bot
My bot has a premium feature, should i use discord built in premium system or another one? I think discord takes up to 30% of your earnings
You are obligated to use discord's offering if you live in a region it supports
This is a part of the monetization agreement you have agreed to
And what happens if i just use other method instead anyways?
You can have other methods as well, but you need to have Discord's offering as well with the same price.
Understand, thanks
you already agreed when you created an application in the developer portal
understand
and not following it will either get your bot terminated, get cease and desist letter or whatever else idk
Probably sued if there's enough money on the line
yeah, that's after and will be mentioned in the c&d letter
I know this might be inappropriate for this channels I hope it’s okay but for a bot that uses a database and has 8 rather straightforward commands mainly using the database how much apart from hosting do you think this bot would cost for the service
depends on the quality
there are a lot of people writing garbage bots for like 10 bucks or whatever on fiverr
For like good/decent quality (doing everything wanted in an efficient way)
Dunno. I don’t think there are a lot of skilled developers doing discord bots on fiverr
Well do you think charging 40-50 usd is too much in general
probably not
Okay thank you
Whatever you do, do not hire someone except on a service that offers some degree of accountability and liability. Way too many people "hire" kids dirt cheap on discord just to have their money ran away with and no recourse
i get the following error code while using discord.py
import audioop
ModuleNotFoundError: No module named 'audioop'
you haven't installed it ¯_(ツ)_/¯
audioop got removed from stdlib in 3.13
oh and how can i get it?
either download the latest (d.py) version from github or you can download pip install audioop-lts
thanks
i had the same issue. just uninstall python 3.13 and work wirh 3.12.7
Or just install the mentioned package?
Or explicitly use the older version; no need to uninstall it.
3.13 is still too immature to use rn, with many dependencies not updated for it yet
I'd still recommend 3.12 for the time being.
Guys I made a pop out python discord bot and the pop out just says ''Something went wrong. Try again'' how do I fix that
I think you would need to give more information for any help
If i share my whole code?
you cant just copy paste the code from whatever editor you use?
It just says too long
screen shot
so what are you trying to make the bot do exactly?
Basically when you click the button it tkaes you to a pop out menu and you need to your ign and it stores that data in a json file
The purpose of the bot is to link discord accounts with their minecraft accounts

hold on gtg
You should be getting a error in your console. Or at least a print statement with a partial error because you use a bare except.
You also should use a proper database, not a flat json file, to store data your application generates/tracks. As is you are risking randomly corrupting all of your data each time you write it
is there a way to host a bot without requiring entering credit card information
Buy a machine and run it
Ohh I just remembered I have an old windows laptop
Thanks
Although how would I use it to run 24/7?
Docker would be good right?
Docker doesnt keep your computer online and running, separate concerns
I know but like it keeps it running in the background automatically no?
I mean are you planning on using this machine while it's hosting? Docker sure is one option but so is opening a command prompt and typing python mybot.py. Depends on your requirements
No I don’t want to use the laptop while it’s running (just for hosting 24/7)
ready to get your electricity bill go higher? 
how can i make interaction.response.send_message not to reply?
what database do you recommend?
Depends entirely on the nature of the data being stored and the needs of the application
sqlite is appropriate for like 95% of what I see people build here but folks should make an informed decision
Will it actually go like noticeably higher?
The electricity bill is expected to increase significantly in the upcoming billing cycle.
Probably not noticeably, laptops consume very little power
assuming it consumes 10W, at 0,21€/kWh then that's +1,5€/mo
ok Im gonna try storing data differently
Is it possible to steam video in voice channel?
no
Why . If it's possible to stream audio by music bots then why not video
ask Discord
Honestly kind of what activities are for
🤠can't we stream in the same way broo? Then can we record voice?
yes but it's not publically documented
you can't, as an interaction needs a reply - what you can do is reply, delete and then send a separate message
but you'll have to reply to the interaction at least at some time, otherwise people will get the interaction failed error message
you can just send a message to interaction.channel but i belive you need to still somehow respond to interaction anyways
yeah
yeah
yeah
hi turtle
Hey
can just defer
if you're fine with your bot showing "...is thinking" for 15 mins and then fail (?), why not
Does anyone know how to make a user discord bot. Meaning a user that acts like a bot and can do pre programed things
You don't because that's against the tos and will get yourself terminated aka banned from using discord
O
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
And this will only last for 15 minutes.
jo whats good i have a error as soon i click on one of the buttons in the drop down
File "C:\Users\Philipp\Desktop\Avenity Services\Utils - Discord Bot\ticket_system.py", line 78, in select_callback await interaction.response.defer() AttributeError: 'Select' object has no attribute 'response'
iirc interaction comes before the select in the parameters list
Note: This is different in other libraries. Some have interaction first some dont. So I would make sure that you are using the method that you library supports. The reason I mention this is because you might have the wrong library installed.
How to do sub commands while using @app_commands?
I am switching from hybrid to app commands.
@commands.hybrid_group(
name="perm",
invoke_without_command=True,
strip_after_prefix=True,
case_insensitive=True,
)
@commands.guild_only()
@app_commands.guilds(SYNC_GUILD_ID)
async def perm(self, ctx: commands.Bot):
"""
Base owner commands.
"""
if ctx.invoked_subcommand is None:
await ctx.send_help(ctx.command)```
this is how you would do it with Hybrid, how can I do it with app_commands?
!d discord.app_commands.Group
class discord.app_commands.Group(*, name=..., description=..., parent=None, guild_ids=None, guild_only=..., allowed_contexts=..., allowed_installs=..., nsfw=..., ...)```
A class that implements an application command group.
These are usually inherited rather than created manually.
Decorators such as [`guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only), [`guilds()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guilds), and [`default_permissions()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.default_permissions) will apply to the group if used on top of a subclass. For example:
```py
from discord import app_commands
@app_commands.guild_only()
class MyGroup(app_commands.Group):
pass
```...
i think i can just defer it
won't it just show as "... is thinking" for 15 minutes and then show the same error as not responding because you failed to send a followup?
Indeed
is it possible to make one bot have multiple different "accounts" so each one can do something like send a different message? I think i saw a bot like mee6 have custom bots which you could do different things on
You, the human developer, can register as many applications as discord lets you and do whatever you want them. Though this sounds obnoxious to maintain for what's just a gimmick
You can also post to a webhook and declare the display username/avatar each time you post to it
okay i try that
traceback: https://paste.pythondiscord.com/UVLQ
linkutils code: https://paste.pythondiscord.com/L22Q
little info here but its alot to explain go to #1296452013873299498 if u can help
Using the interaction, how would I get the thread a user has used the command in from a forum channel?
The channel the interaction was sent from.
Note that due to a Discord limitation, if sent from a DM channel recipient is None.
tracker bot attribute doesn't exist, it's custom.
Since it's something custom, you likely forgot to copy paste something :)
Also none of these "trackers" are actually functional. Discord doesnt tell you what invite was used, so all of them are just guessing
how can i add a command or a group into a cog while not being inside it?
Why would it not be?
i get discord.app_commands.errors.CommandSignatureMismatch error when i try to import a command from another file and add it to the current cog, how do i fix this?
Why is it in another file?
They function fine they're just hard on the API calls, they get all invites, which includes number of uses, and diff that against a previously cached version; they work they just fetch all invites on every join which is a bit ehhhh
i wanted to separate it
don't tell me you make one file per command
You shouldn't separate things on a feeling. There should be a functional reason, and the file just feeling too long isn't functional
Long files aren't bad, and that's an important bad habit to get over
sup fellas so someone is asking me to make them a pretty high level bot and im not really sure how to come up with prices for bots
features, effort and time
There's the age old advice of
- pick an hourly price, estimate how long it'll take, put that as your quote
- adjust that price up and down until your supply (time) balances with demand
anyone have any idea why
@client.event
async def on_connect():
if client.auto_sync_commands:
await client.sync_commands()
throws an error of
Ignoring exception in on_connect
Traceback (most recent call last):
File "/home/codespace/.python/current/lib/python3.12/site-packages/discord/client.py", line 412, in _run_event
await coro(*args, **kwargs)
File "/workspaces/bloxbot/main.py", line 37, in on_connect
await client.sync_commands()
File "/home/codespace/.python/current/lib/python3.12/site-packages/discord/bot.py", line 761, in sync_commands
app_cmds = await self.register_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/codespace/.python/current/lib/python3.12/site-packages/discord/bot.py", line 538, in register_commands
prefetched_commands = await self._bot.http.get_guild_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/codespace/.python/current/lib/python3.12/site-packages/discord/http.py", line 368, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
Ive tried doing everything including giving admin perms kicking and readding the bot and more
the bot works fine but new commands arent syncing no idea why
thank you
Code? What library are you using?
nvm seems like in one of my cogs i had a typo in the dev server id
you're adding your bot through the discord developer page i hope?
(im asking this cause i remember someone trying to make a bot join through an api call)
doing it through the oauth2 page?
select "bot"
third option on the third column
click it, select your server
add
code them, upload them to your preferred host/server
do you know python
yeah thats fair
my first project was a crap discord bot, anyways refer to this https://discordpy.readthedocs.io/en/stable/intro.html
alright, but that guide will walk you through the introduction for your bot
Is there a problem with the API?
can somebody help me with a js project? its abt discord oauth, if you're interested, and know how stuff related to it, please DM me, thx
its not just its too long i needed to separate it so it doesnt mess up with the cog before its handled then add it later
Can somebody help me fix my bot. I wrote up some basic with the help of the discord.py documentation. I have the right token and permissions set. My code runs fine but my commands do not work at all. I ran it through chat gpt and chat gpt says my code should work and is functional + shows no errors.
if anybody is interested in helping me please shoot me a dm. I'm heading to work so you most likely hear from me in the morning
this is py server not js
pretty sure #web-development cant have .py
and becuase on that, we can see that this server does not SOLELY focus on python
and this is #discord-bots
not #python-discord-bots
therefore, its uncatagorized, and i could post non-python, but discord bot content
How do i handle slash command errors?
!d discord.app_commands.CommandTree.error
@error(coro)```
A decorator that registers a coroutine as a local error handler.
This must match the signature of the [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.on_error) callback.
The error passed will be derived from [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError).
just ask for help on a javascript server
this is a python based server
i mean its obv that u can only get help with python there
just try to connect atleast 2 braincells
i made several neuro networks in python before
in fact, if i couldn't connect 2 braincells, i couldn't have moved my finger
so i couldn't have typed
therefore, your statement/argument is incorrect/non-valid
i still stand by the fact that common sense is disappearing with time
it totally can, get yourself informed before saying random stuff lmao
How do I get the ID of the channel and the thread ID of the channel that I use a command in if it's a Forum Channel?
how can i add buttons to my bot presense/activity?
^
Can someone tell me how to setup cogs again, im not familiar with the new changes. I get this error:
4: RuntimeWarning: coroutine 'setup' was never awaited
setup(self)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Ignoring exception in on_ready
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/disnake/client.py", line 703, in _run_event
await coro(*args, **kwargs)
File "/Users/tenuka/Documents/Projects/word bot/main.py", line 13, in on_ready
await bot.load_extension('cogs.words')
TypeError: object NoneType can't be used in 'await' expression
Those are extensions, not cogs. And everything is async as of v 2.0 if you're using discord.py
Also don't do this in on_ready
Okay so from where is the error coming?
oh wait i think i got it
He is using disnake
Yeah don't mix libraries. If the one you're using isn't async in extension loading, don't await. Either way you shouldn't be using on_ready for one time setup steps
^^^
yeah thats mb
but now iget this disnake.ext.commands.errors.ExtensionFailed: Extension 'cogs.words' raised an error: ImportError: attempted relative import beyond top-level package
You can try using absolute imports
how can i add button to discord bot's presence anyone
is it okay to start a tasks.loop on the on_ready event?
i wouldnt
then where?
could do in a setup_hook, or a cog_load, and then have a before_loop that waits for the bot to be ready
Oh well what if you don’t have extensions?
Like in the main.py itself. Because there’s just one function so I don’t think extensions would be very helpful
setup_hook is called after login
how can i make discord.py handle custom errors?
Same way you get it to handle any other error
yo, so a custom emoji is not popping up on a button i have created and only the id and name shows on the button !
code?
^
Use the emoji= kwarg; the label doesn't render emojis.
import discord
from discord.ext import commands
Set up intents
intents = discord.Intents.default()
intents.messages = True # Enable message intents
Create the bot instance with command prefix
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name} (ID: {bot.user.id})')
@bot.command()
async def ping(ctx):
latency_ms = round(bot.latency * 1000)
await ctx.send(f"test! {latency_ms} ms")
@bot.event
async def on_message(message):
if message.author == bot.user:
return # Ignore messages from the bot itself
await bot.process_commands(message) # Process commands
bot.run('')
Can somebody tell me whats wrong with this code?
my commands dont work but my bot goes online
if you're running dpy this will spit a warning in your console
dpy?
can you highlight which part gives me a warning? my console is pretty much empty
do you mean discord.py?
yes
im getting no warning in my console
Do you get anything?
How do I get the ID of the channel and the thread ID of the channel that I use a command in if it's a Forum Channel?
channel.id for getting the forum and thread id
channel.parent_id for getting the forum id where channel is a thread and not a forum channel
💀 no its my first time using this discord.py . Your saying that there is a warning in my console if the it isnt working and my console is entirely empty
wait
your actually a genius

hacker
C:\Users\mulle\Downloads\discord bot>py bot.py
Traceback (most recent call last):
File "C:\Users\mulle\Downloads\discord bot\bot.py", line 2, in <module>
from discord import app_commands
ImportError: cannot import name 'app_commands' from 'discord' (C:\Users\mulle\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord_init_.py)
C:\Users\mulle\Downloads\discord bot>
I don't personally use d.py, but i've looked into examples, the import seems to be right, are you sure you have it instaleld?
try running pip install -U discord.py in your terminal
says same thing
could you do pip freeze and send a screenshot?
Else, you can ctrl + alt f4 to close vsc isisntance and just restart it up
This says you are missing message intent
Did you enable it in developer's portal?
let me check
message content intent
yea it was disabled
Try restarting, It should work now
@slate swan did this fix your current issue?
Welp, you look like you've enabled it, How are you using your intents in the file?
import discord
from discord.ext import commands
Set up intents
intents = discord.Intents.default()
intents.messages = True # Enable message intents
Create the bot instance with command prefix
bot = commands.Bot(command_prefix='-', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name} (ID: {bot.user.id})')
@bot.command()
async def ping(ctx):
latency_ms = round(bot.latency * 1000)
await ctx.send(f"!test {latency_ms} ms")
@bot.event
async def on_message(message):
if message.author == bot.user:
return # Ignore messages from the bot itself
await bot.process_commands(message) # Process commands
Ummm
i removed the bot.run()
i use disnake, could you try replacing this line
intents.messages = True
with
intents.message_content = True
Let me also look in they're library to make sure
Yes, my assumption was right
ok let me check
Try restarting your pc
Just replace that line with intents.message_content = True
I did and it worked
let me see if I can send commands
ok well it worked so I don't get an error anymore for the intent so tty
nothing better than getting help from actual smart people
💀 wish me luck on this project
@dry kelp do you know any good resources to learn discord.py
The docs and the examples in the repo. IMO anything else I've seen written independently is outdated, garbage, or both
A hands-on guide to Discord.py
now it dont say anything
code?
py
No like what is the code in that file lol
import discord
from discord import app_commands
import os
import json
intents = discord.Intents.default()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)
Load bot token from config file
with open('config.json') as f:
config = json.load(f)
TOKEN = config['token']
@tree.command(name="send-embed", description="Send an embed from a file")
@app_commands.describe(embed="The embed file to send", channel="The channel to send the embed to")
async def send_embed(interaction: discord.Interaction, embed: str, channel: discord.TextChannel):
embed_folder = "embeds"
embed_file = f"{embed_folder}/{embed}.json"
if not os.path.exists(embed_file):
await interaction.response.send_message(f"Embed file '{embed}' not found.", ephemeral=True)
return
with open(embed_file, 'r') as f:
embed_data = json.load(f)
embed = discord.Embed.from_dict(embed_data)
await channel.send(embed=embed)
await interaction.response.send_message(f"Embed sent to {channel.mention}", ephemeral=True)
@tree.command(name="upload-emojis", description="Upload emojis from a folder")
async def upload_emojis(interaction: discord.Interaction):
emoji_folder = "emojis"
uploaded = 0
failed = 0
for filename in os.listdir(emoji_folder):
if filename.endswith(('.png', '.jpg', '.jpeg', '.gif')):
with open(f"{emoji_folder}/{filename}", 'rb') as image:
try:
emoji_name = os.path.splitext(filename)[0]
await interaction.guild.create_custom_emoji(name=emoji_name, image=image.read())
uploaded += 1
except:
failed += 1
await interaction.response.send_message(f"Uploaded {uploaded} emojis. Failed to upload {failed} emojis.", ephemeral=True)
@client.event
async def on_ready():
await tree.sync()
print(f'Logged in as {client.user}')
client.run(f'{TOKEN}')
@dry kelp dm
5 mins
ok
I mean looks fine
Eh. I personally have qualms with some of the things there. But anything that's not maintained by the library itself is only as good as the individual maintaining it
ik i think it somthing with my pc dont the the right thing
with some personal design choices, which yeah are not bad but not ideal either
What happens if you just run python on its own
Hey! How are you doing?
Hi
good ig
why does syncing the bot for a specific server never work?
because you're likely doing it wrongly
Typically this comes from not putting commands into the right scope and then syncing on that scope. If you want a command to only show up on one guild, you have to tag it to that guild and then specifically sync to that guild
how? i sync it using tree.sync then i pass the guild to the method
what scope? and how to tag
What's your goal here? For a command to only be available in one guild?
Hi
@fast osprey
...yes?
everytime when i do ,afk on my bot it sends the hey you have been afk for some duration
There is already an existing away system baked into discord
I'm suggesting you remove all of this and let people use the system they already have vs asking them to update two completely different things for the same purpose
ima send my afk command in chat
what you mean by system
bam, I've done something to show people I'm away
😭 you talking about that, but i tried making an afk command for my bot because my friend couldnt go afk with my bot and got mad
Why do they want to go afk "with your bot". There is already something that exists
i dont know, they are used to dyno bot and carl bot
and bleed bot
Seems useless and cumbersome
py" i"
so ok im very new to python very very new but im trying to get the bot to post a embed it does but for some reason the thumbnail image comes up with that 💩 image where it cant find the image so im wondering where im going wrong
or it just spins
come to think of it could it be a intent im missing ?
that imgur link doesn't link the actual image it's just a link to a webpage, you're looking for https://i.imgur.com/zdG9JFD.png which is the source image for the page
so it fails to render because discord's media proxy is finding html, not an image file
Thank you very much
What service do y'all use to deploy your bots?
Preferably with a free tier, this is just for a small project that pulls in no income as of now
pylexnodes
anything free is generally bad
Either they're making money off of you somehow, or they're going to eventually force you to pay either directly or via frustration. Nobody is going to spend their own money running your stuff for you eternally
def guild_owner():
async def predicate(ctx):
if ctx.author.id == ctx.guild.owner_id:
return True
await ctx.send(f"{me.alert} | **Only server owner can use this command**")
return False
return commands.check(predicate)
This sends message everytime i run help command
iirc you shouldn't be sending messages in checks like this. Throw an exception and send messages in your error handling
https://github.com/Rapptz/discord.py/blob/master/discord/ext/commands/help.py#L656 when figuring out what commands to show, it runs the checks on all of them and does a try/except around it
I don't have custom help command built yet
So i should prioritize building my help command or this can be countered for now?
yea i've hard a hard time trying to find a good one
i ended finding a friend who nicely shared me her Raspberry Pi and i'll buy my own next summer i think
What I said had nothing to do with a custom help command. Your checks should not have side effects like sending a message, that should be done in error handling
which partnered server do you own
Nextcord
how can i send my command in message like this?
</NAME:COMMAND_ID>
how do you get the command id
If it's fixed for like the same command, you can do as if you execute the command, and right click the small rectangle that pops up above your message
Otherwise probably in the integrations settings of the server
And if you want it dynamic, e.g. for a help command
how can i get it from a Command object?
!d discord.app_commands.AppCommand.id
The application command’s ID.
!d discord.app_commands.AppCommand.mention
property mention```
Returns a string that allows you to mention the given AppCommand.
Last one is to directly mention without having to format yourself
i got AttributeError: 'Command' object has no attribute 'mention'
read again
Not all Command have mentions available, only app commands
the object is from cog.walk_app_commands
And that returns Command or Group
how would i extract app commands from a cog then
discord.py
Cog.get_app_commands()
Py-cord:
Cog.get_commands()
i still get Command object which doesnt have mention
Why Command is a prefixed command, not the same as AppCommand
and Cog.get_app_commands is supposed to return AppCommands?
Hmmm in the documentation the mention attribute does not appear
Strange, sorry I don't use Discord.py
For these things it's better ask in the specific lib's server
Anyways, see :
In order to mention app commands through discord.py, a custom CommandTree is required to store the ID from API methods such as .sync() and .fetch_commands().
For a comprehensive example or recommended implementation, see this gist ("discord.py MentionableTree implementation").
Individual command ID
- You can get the ID of a particular command on Discord by right-clicking the name before invoking it. See
?tag slash mentionfor a preview. - You can also get the ID of the running command via
interaction.data.
@...command(...)
async def slash_command(interaction: discord.Interaction, ...):
command_id = interaction.data["id"]
command_mention = f"</{interaction.command.qualified_name}:{command_id}>"
await interaction.response.send_message(f"The ID of this command is: {command_id}. Click the following to invoke this command again: {command_mention}")
someone help me in this shit pls https://discord.com/channels/267624335836053506/1297907745525071974 its been a week but still hasnt been fixed
basically what happens is both players choose 5 moves each and after the first player chooses his moves when the second player starts choosing the bot changes all circles to squares (it was squares originally and changes into a circle everytime you select a move)for player 1 and changes the username of player 2 to that of player 1 and continues on with the duel therefore displaying nothin in the round result part
raise ClientConnectorCertificateError(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)')]
im just trying to test a basic bot and that happens
what OS are you on?
macos sonoma
Getting [SSL: CERTIFICATE_VERIFY_FAILED] on Python 3 on OS X?
Navigate to your Applications/Python 3.X/ folder and double click the Install Certificates.command to fix this.
Happy coding!
worked like a charm tys
Traceback (most recent call last):
File "/Users/anshg/Documents/Python/.venv/lib/python3.12/site-packages/discord/client.py", line 449, in _run_event
await coro(*args, **kwargs)
File "/Users/anshg/Documents/Python/bot/bot.py", line 41, in on_member_join
await msg.edit("Welcome! Please read the rules!")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Message.edit() takes 1 positional argument but 2 were given
whats wrong with this
msg = await user.send(f"Welcome! Please read the rules. \n-# {word}")
fixed nvm
why am i getting duplicate slash commands after syncing to a specific guild using tree.copy_global_to and tree.sync?
Because guild tied commands and global commands are stored separately.
You should not register a command in both
C:\WINDOWS\system32\cmd.exeC:\Users\mitro\Desktop\Novi Bot Novi Pocetak )>python 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\LocalCache\local-packages\Python311\site-packages\discord__init.py)
- Restart your IDE and try again
- Ensure that you only have 1 discord bot library installed.
- Uninstall the other discord bot libraries you are not using
- Reinstall the discord library you are using
- Restart your IDE
if using discord.py: do this #discord-bots message
hi
can i present you guys my own AI chat bot made in python?
yes
okay
wait, external apps cannot be used here 😭

Sure, ask your question and if anyone knows the answer they will
SSL: CERTIFICATE_VERIFY_FAILED error solution
i know this is kinda offtopic and stupid to ask but what should i name my cog for owner-only commands like sync?
A guide on fixing verification of an SSL certificate.
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Client.get_guild() missing 1 required positional argument: 'id'
guild = discord.Client.get_guild(server_id)
roles = guild.roles
so what did i do wrong
nvm im stupid
ok what i did also didnt work
discord.Client means an instance object, so you'd need that object and not call the function on the class itself
is client similar to Bot()
user = ctx.author
id = user.id
word_code = random_word(id)
if isinstance(ctx.channel, discord.channel.DMChannel):
code = code.lower()
if code in codes or code == word_code:
role_id = codes[code]
role = get(guild.roles, id=role_id)
await user.add_roles(role)
await ctx.send(f"You Found Rule {role}!")
bot has admin perms, but still unable to add any roles.
error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'User' object has no attribute 'add_roles'
i thought ctx.author returns a Member
so in a DM Channel it doesnt?
ok i partially fixed it, but now im getting a permission error even though i know for a fact that it has admin perms
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
help
check the role hierarchy: is the user that the bot is attempting to give a role higher on the role hierarchy than the bot itself?
^ Use the > < operators on Role
if role > top_role:
... # role too high
Your bot should never have admin, that's an incredibly unnecessary risk
Hello, as I understood, there is no free options to run bot 24/7?
None worth considering seriously
does bot.walk_commands include slash commands aswell?
nope
why am i getting
TypeError: Choice annotation unsupported for
autocomplete parameters, consider using a regular annotation instead
using Optional[app_commands.Choice[str]] as my annotation?
What library are you using?
iirc autocompletes only return the value, not the display name. Just typehint with the raw type in your command
are there any good beginner websites/videos to learn discord bot coding with python? I have setup my bot in vsc, and turned it online. I'm not sure where to start after it
Do you have a base proficiency in python? Including concepts like OOP/class design and asyncio?
im not sure what that means, can you explain
If you don't know what those things are, you're better off with general lessons and resources. Not jumping right into a highly advanced framework like these
There was a good gist or message about what people should know before making bots
Prerequisites
Some prerequisites for writing a Discord bot in Python.
Required:
- Primitive data types
- Operators
- Control flow
- Function definitions
- String formatting
- Variables, namespace and scope
- Importing
- Classes, objects, attributes and methods
- OOP
- Data structures
- Exception handling
- Console usage, interpreters and environments
- Decorators
Useful to know:
- Databases
asynciobasics- What is "blocking?"
- Logging
- Reading documentation properly
The official python tutorial is comprehensive but dense. There are lots of good beginner resources. From experience though videos are awful for this, especially on places like YouTube where there's no accountability or quality control.
And lots of youtube tutorials are outdated or show bad practice
Which e.g. leads to people doing bot = discord.Client()
it didn't work
Perfect example of people giving any permission to bots (200k+ members server)
Edit: it's actually their own bot, so bad programming (sanitizing/allowed mentions) and permissions as well
Can you describe what you did, and what exact error you're getting now?
No like. Full error. All of the output, and again describe what you did to try to fix it
A guide on fixing verification of an SSL certificate.
Describe the specific steps you did, and again, paste the full error
I tried all the solutions I saw on YouTube and nothing changed.
and this too
(Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self-signed certificate (_ssl.c:1020)')))
this is result
How short and long do UID get?
uring handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\oyund\OneDrive\Desktop\Yeni klasör (4)\Yeni klasör\dembele.py", line 12, in <module>
r = requests.post('https://discord.com/api/v9/channels/1298027330408681475/messages')
File "C:\Users\oyund\AppData\Local\Programs\Python\Python313\Lib\site-packages\requests\api.py", line 115, in post
return request("post", url, data=data, json=json, **kwargs)
File "C:\Users\oyund\AppData\Local\Programs\Python\Python313\Lib\site-packages\requests\api.py", line 59, in request
return session.request(method=method, url=url, **kwargs)
~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\oyund\AppData\Local\Programs\Python\Python313\Lib\site-packages\requests\sessions.py", line 589, in request
resp = self.send(prep, **send_kwargs)
File "C:\Users\oyund\AppData\Local\Programs\Python\Python313\Lib\site-packages\requests\sessions.py", line 703, in send
r = adapter.send(request, **kwargs)
File "C:\Users\oyund\AppData\Local\Programs\Python\Python313\Lib\site-packages\requests\adapters.py", line 698, in send
raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='discord.com', port=443): Max retries exceeded with url: /api/v9/channels/1298027330408681475/messages (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self-signed certificate (_ssl.c:1020)')))
PS C:\Users\oyund\OneDrive\Desktop\Yeni klasör (4)>
@fast osprey
?
positive?
cuz I lowkey hate when I have to use str when using NUMBERS cough cough discord.
"int to long" 
Like bro, why allow us to use int but have a limit on the ints when they aren't even that long? I just find it really really really stupid.
iirc 2084 is when discord snowflakes will exceed the signed 64-bit integer limit used by most(?) databases
hello guys i just switched to linux and i have no clue how to install py cord correctly
someone help me out before i rage
generally you want to create a virtual environment for your project, activate it, then install your dependencies in there
for debian-based distros it usually goes something like: sh ~ $ sudo apt update ~ $ sudo apt install python3-venv ~ $ cd my-project ~/my-project $ python3 -m venv .venv ~/my-project $ source .venv/bin/activate (.venv) ~/my-project $ pip install some-package (.venv) ~/my-project $ python main.py it's easy to make mistakes during this process though, so you may want to post in #1035199133436354600 if you get stuck
I have a life besides helping people for free lol. You still haven't described what you did, and just saying "I did the article" doesn't give us confidence that you did it correctly. Also, this has nothing to do with discord bots at all and is just the ssl certs on your python installation
Is discord.js the same as discord.py? Or it has a different process
One is for javascript and one is for python but they are both for making bots
what is the code for a bot to give a specific user an already exising role?
Maybe theres a guide in the docs
how can i get the cog of a group?
hey
How can i get the cog assigned to a command anyone?
Why? What is this driving? Usually you can put that logic somewhere in the cog itself
what does that mean?
What is the code you're writing that wants to know this
help command
also my question was a bit incorrectly im trying to get the cog of an AppCommand object, if there is
It's generally recommend you don't write this. The / menu exists to already document and search your app commands
It was designed to be a consistent ux for every bot so that people could discover commands in one place, rather than every individual bot implementing their own differently formatted non-interactive help command
I generally have a /info command instead of a help command that shares additional information about the bot
thank you man the struggle was real
Hello, how I can make imports to my discord bot, using PyInstaller, he doesn't see library
^
every message format is documented
https://discord.com/developers/docs/reference#message-formatting
So, I am trying to make discord.Spotify work right? But it won't detect that I am using spotify?
@info_cmds.command(name="debug_activities")
@app_commands.describe(user="The user to get activities information from.")
async def debug_activities(self, interaction: discord.Interaction, user: discord.Member = None):
"""Debug command to show all activities of a Member."""
await interaction.response.defer()
user = user or interaction.user
print(f"Activities: {user.activities}")
activities_info = "\n".join([f"{type(activity).__name__}: {activity}" for activity in user.activities])
if not activities_info:
activities_info = "No activities found."
await interaction.followup.send(f"Activities for {user.name}:\n{activities_info}")```
it says everyone who has an activity, that they don't have an activity, I also have all intents on.
Its not reading anything properly? Whats up with Presence and Activities?
I have the Intents enabled, and I have Intents all on, and it is still not working?
simple question: why is this not running when i remove a reaction...
!d discord.on_raw_reaction_remove should only take one parameter, the raw payload given by discord
discord.on_raw_reaction_remove(payload)```
Called when a message has a reaction removed. Unlike [`on_reaction_remove()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_reaction_remove), 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.
if you didnt see any traceback in the console, it might mean your logging isn't configured correctly or you have an on_error handler suppressing the error
grant_type is not valid or the data you're submitting is in an invalid format (make sure you POST in content-type application/x-www-form-urlencoded), your code would help though
could be expired or not matching what the server expects
i'd guess i'd throw a different error
that's likely the common thing where people don't send the right content-type
Question? does anyone know of a python based bump bot whos code i could get my hands on ?
how can i get the bot from interaction object?
!d discord.Interaction.client
property client```
The client that is handling this interaction.
Note that [`AutoShardedClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AutoShardedClient), [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot), and [`AutoShardedBot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.AutoShardedBot) are all subclasses of client.
hello everyone
how do i retrieve the id of a slash command
It's different in every library
Can also get it from the client yourself
the client id?
no the discord client you're typing into now
How do i add colors to codeblock?
how do i add description to app command's params?
!d discord.app_commands.describe
@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.
Example:
```py
@app_commands.command(description='Bans a member')
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
await interaction.response.send_message(f'Banned {member}')
``` Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings...
is it better if i use app_commands.Parameter(...) and then pass it to the param?
No
"Better" is pretty nebulous here
One could say that the docstring approach is better as you should be documenting your code anyways
my code itself is the documentation 
quick question: does discord.py require asnyc requests when sending get requests within a command or can i just use requests.het
im making a on_presence_update event
@commands.Cog.listener()
async def on_presence_update(self, before: discord.Member, after: discord.Member):
channel = await self.bot.fetch_channel({id})
if after.id == {id}:
if after.desktop_status == discord.Status.online and before.status != after.status:
await channel.send('message')
...
whenever i change my status it runs the if statement twice?
Dpy aside, you shouldn't use blocking requests in any asyncio application. You are blocking your entire app while you wait for that request to come back. Use aiohttp
Do you share multiple guilds with the bot?
nope
and only one instance of the bot running
Are all of the fields identical?
what do you mean by fields
The values in before and after
import random
from termcolor import colored
class PseudoGenerator:
def init(self):
self.prefixes = ["Super", "Mega", "Ultra", "Cool", "Epic"]
self.suffixes = ["Warrior", "Ninja", "Hunter", "Master", "Gamer"]
self.keywords = []
self.censored_words = {"sexe", "drogue", "crime", "violence", "harcèlement"}
def add_keyword(self, keyword):
if keyword.lower() not in self.censored_words:
self.keywords.append(keyword)
print(colored(f"[INFO] Le mot-clé '{keyword}' a été ajouté.", 'green'))
else:
print(colored(f"[ERREUR] Le mot '{keyword}' est censuré.", 'red'))
def generate_pseudo(self):
prefix = random.choice(self.prefixes)
suffix = random.choice(self.suffixes)
keyword = random.choice(self.keywords) if self.keywords else ""
pseudo = f"{prefix}{keyword}{suffix}".strip()
return pseudo
def main():
generator = PseudoGenerator()
print(colored("Bienvenue dans le générateur de pseudos !", 'cyan'))
print(colored("=========================================", 'cyan'))
# Ajout de mots-clés personnalisés
while True:
keyword = input("Ajoutez un mot-clé (ou appuyez sur Entrée pour arrêter) : ")
if keyword:
generator.add_keyword(keyword)
else:
break
print(colored("\nGénérateur de pseudos :", 'cyan'))
print(colored("=========================================", 'cyan'))
while True:
print(colored(generator.generate_pseudo(), 'yellow'))
if input(colored("Voulez-vous générer un autre pseudo ? (o/n) : ", 'cyan')).lower() != 'o':
break
print(colored("Merci d'avoir utilisé le générateur de pseudos !", 'cyan'))
if name == "main":
try:
from termcolor import colored
main()
except ImportError:
print("Veuillez installer le module 'termcolor' avec la commande : pip install termcolor")
pip install termcolor
yeah
They are all identical on both firings?
Completely unrelated to discord bots -> #1035199133436354600
oh sorry didnt understand the question, the before and after are different but both the firings are the same
i setup some print statements and apparently sometimes the code goes off even when i dont change my status
and im the only one in the server other than the bot
Who does the bot say is changing their presence?
just me
So it's saying you're changing your presence when you're not?
oh i think its one of those discord bots
idk how its called
So you aren't the only one in the server besides the bot, there are other bots?
no, ive never seen that username before
its not a member in the server
but that isnt my problem

the problem is whenever i change my status, it calls the function twice
Your bot doesn't get events for random users
Your bot shares a server with that user/bot
Or you're running on a different token than you think you are
i know, but for example if you use a ip logger in a dm on discord there will be more than two people's ip
i think its about that
then i dont know, but i can tell you that there is no one else in that server but me and my alt account and the bot
And how are you verifying that?
hold on let me check
well i am stupid
i played around with the same bot and apparently i never deleted another old testing server that i forgot about

thanks though, i was so confused
works fine now
yeah thats what i tried
hello 👋 recently decided to make a discord bot now ive got some time as you do i made the app in the dev portal but now this error keeps showing up 2024-10-25 22:00:48 WARNING discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected. if anyone could help that would b amazing
!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.
(Also that is a warning, not an error, and it tells you what behavior it will cause)
why cant i do this
client = commands.Bot(command_prefix="!", intents=intents)
tree = app_commands.CommandTree(client)
the error im getting is that it already has a command tree
im new to how slash commands and commandtrees work
im trying to make a bot with both prefix and slash commands
Bots already get a commandtree
and you shouldn't name a variable client if it stores a bot, different types entirely
is for someone slash commands also not working?
commands not showing, if i create a new command it wont show also
did u sync?
yes ofc
did u reload discord?
how are u syncing?
await client.tree.sync()
sorry
await client.tree.sync(guild=discord.Object(id=1264238401981513728))
i mean where, like in on_ready or in a command
Is that command registered to that guild?
what
100% not needed it worked some days ago
Yeah firstly don't do this or change presence in on_ready. You've been lied to about how that event works
the sync as well
Yeah don't sync in on_ready
fuck you mean dont sync in on ready
the event is not for what you think it is
There's really no other way to read that. Don't do it
and for what then
discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.guilds) and co. are filled up.
Warning
This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
Logic that cares about when cache is repopulated after a reconnect, which isn't what you're doing
Where should I call them then?
Trying to change presence in on_ready can straight up disconnect you
You should sync manually when you need to only
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready) event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for) and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready)...
yeah that one
though shouldn't sync there either
better than on ready tho
Won’t fix the issue 100% give me 5 mins I’ll try it
Why is it sometimes difficult to create application commands in discord.py? Other libraries automatically synchronize commands.
because auto sync is not recommended at all
you should only sync when you actually need to
e.g. when you add or remove commands, or edit its structure - so parameters, description, etc.
In py-cord you should only pass False to the client 
pretty much the same as making a command and sync when needed
both projects also clearly have different design goals as well
Yes, but sometimes I find it very strange how discord.py handles application commands.
it's kind of the normal behaviour to be fair
oh fuck it really worked with synching via command thanks ❤️


If you sync on any regular cadence, that is rate limited and you will lock yourself out of development
The core issue was you were syncing to a guild while having a global command, but none of that matters if you completely lock yourself out
and there is also a limit or commands you can create a per day ^
hmm okay ty
there is?
what is it?
200 global command create/edits a day.
200 guild command create/edits per guild per day
Unlikely to ever hit it if you sync as you develop. If you unnecessarily sync every time your bot does a routine reconnect, that's another story
you need to use tree.copy_global_to if you want to sync locally i think
not sure
Can I ask about hosting here?
I’m looking for a platform to host my bots (maybe up to 10-15) but each are for one server, only a few might be a little complex but generally pretty simple
Sure what's the question? Just want recommendations?
Yes recommendations , sorry I wasn’t clear
I hope I don’t have to spend too much on it also
This article lists recommended VPS services and covers the disasdvantages of utilising a free hosting service to run a discord bot.
First order of business is probably to profile your app(s) so you know what resources you need
Profile as in see their memory usage etc?
memory, cpu, disk space, etc
network probably isn't going to be a bottleneck but who knows what you're doing
hello guys was the http api removed? I haven't been in the bot dev world for a long time
I can't find where to input the url
on developer portal
Like for interactions over http?
yes
u can do that with slash commands/component interactions/ and those other app commands right
which page is that
portal -> applications -> general information -> scroll down
bot.get_emoji() isn't working, is there any change? using discord.py
Nope, still the same
not working in my case, using discord.PartialEmoji.from_str instead
wdym it isnt't working?
it isn't getting the emoji
what are you passing to it
and which emoji is it supposed to get
and do you need an Emoji obj
await ctx.send(bot.get_emoji(1299497508942250046)) # not working.
await ctx.send(discord.PartialEmoji.from_str(":s:")) # working for me
passing emoji's id
how did you get the id?
by sending \emoji
is the bot in the server with the emoji?
yes
the PartialEmoji method is working for me
PartialEmoji.from_str does not check anything so that doesn't mean anything
bot.get_emoji tries to get the emoji from cache
so it returning None means the emoji isn't in cache
which can happen if 1. the bot cannot see the emoji or 2. the emojis intent is disabled
emojis intent? is it default turned off?
no it's enabled by default
the bot is in the same server and the emoji's id is correct
could you add the following and send the result please
eid = 1299497508942250046
eml = [e.id for e in ctx.bot.emojis]
print(ctx.bot.emojis, bot.emojis, eml, eid in eml, ctx.bot, bot, ctx.bot.get_emoji(eid), sep="\n")
False
<discord.ext.commands.bot.Bot object at 0x000001E00E57B550>
<discord.ext.commands.bot.Bot object at 0x000001E00E57B550>
this is the result basically
the last 3
btw this isn't the main bot let me try it again
the one after is None I assume?
does this bot share a server with the emoji you want
yes
SequenceProxy(dict_values([]))
SequenceProxy(dict_values([]))
[]
False
<discord.ext.commands.bot.Bot object at 0x000002208403B550>
<discord.ext.commands.bot.Bot object at 0x000002208403B550>
None
this is the actual result
the bot shares the server but idk what is happening I am working on discord bots after a year
there are only 3 intents on the discord developer portal right?
Then what intents are you talking about?
are you not passing some intents to your Bot constructor?
why the bot isn't showing up on the members list
Bot(..., intents=<here>, ...)
because it isn't in the server?
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix=DEFAULT_PREFIX, case_insensitive=True, intents=intents, help_command=None)
it is
is there multiple ways of adding an app?
what happened to discord, what are those weird updates
is this even a bot?
there are two types of apps now
- user app: installs to your profile and commands configured by the dev can be used anywhere
- guild app: add to a specific server like before
that is a bot yes
why I can't give it a role then?
Add App then Add to server
and are you looking at the bot's profile in the server you added it to?
yes
and do you have permissions to add roles to members?
I am the owner
what if you click on the bot's avatar
maybe the way of adding isn't real
there are some mutual servers
still it is showing no mutuals
looks like that bot isn't in any servers lol
What is the link that you're using
You're probably adding the app but not the bot
Make sure you have the bot scope in the URL
Yeah you have no scopes at all, won't go far..
got it
And if you want a default role for the bot, you gotta add a permissions query param as well
construct the link at https://discord.com/developers/applications/BOTID/oauth2
Made a youtube player discord bot
Dm if you want the sourcecode as I cant post it hear
advertising something that is against the discord tos - not so smart
Its more of a case study than I actually want to use it or publish it tho
We still don't need source code of stuff against rule 2/discord tos here
what's the point of sending it here? are you asking for a review or..?
I wanted to share the code so others can learn from it not for marketing abuse of the tos
If you want I'll take it down
I didnt know this code was against discord's tos
YouTube -> mp3, mp4, ... -> against YouTube's ToS
Anything against a website's ToS -> against Discord (Developer) ToS
Hey, so i had a problem with Payout settings, and i'd like to change the country. But it doesn't let me change the country of the team, at least i can't see a way. Is it possible to change it?
Hey, which is the best up to date libary for creating a discord bot?
Last i was here they were dis-continuing discord.py?
is there any difference between using add_item or the decorator to add a button or any item really to a View
Not really, no. Just the contexts in which you can use those
the decorators are declared statically so they can't have dynamic properties in them
should i store my bot token in a db or just .env?
.env should be fine for tokens - databases are primarily for storing things you migght have a large amount of or is dynamic (you won't know what the value will be until the runtime)
im also using the db for other stuff shouldnt combining them make it cleaner?
Cleaner isn’t necessarily more compact
Also if you are putting your code somewhere public then you can share the db without leaking the token
The standard is to put the tokens either in a .env file or just in the system variables for the sake of security
Another bonus is that since they are the standard then more people will understand your code base easier
Or use toml as config
Db is definitely overkill as said above
It's possible to edit a file via discord???
Like I have create a file in: Crt/Games/Config.yml
I want edit the file form dc
Like I want make a file manager upload, delete, create, edit but in bot
So how I can?
You would have to Download the File, modify it, upload it
💀
Why are you that shocked? It would have to do that for all websites as to edit the data you need to HAVE the data which means retrieving it which in other words is DOWNLOADING it.
I want manage outside of scope direct in DC by bot
Yeah but still, to edit the data you would need to get the data which is the same as downloading the file
Btw I want make a panel for game servers
why would that preclude you from downloading files
💀
I think you're misunderstanding what a bot even is
It's a process that runs on a machine somewhere. A process that can download, modify, and upload files
In DISCORD???
Just make a website at that point.
Inside a dc bot

how do i use Converter for app cmds? i got unsupported annotation error but it works fine for prefix commands
What converter do you use
subclass of commands.Converter
not helping
wdym
Show it rather than describe it
Some stuff is not supported by app commands because discord doesn't allow it
e.g. you can't set some default converters for app commands because app commands don't have that option type
class DurationConverter(Converter):
async def convert(self, ctx: commands.Context, argument: str) -> datetime.timedelta:
multipliers = {
's': 1, # seconds
'm': 60, # minutes
'h': 3600, # hours
'd': 86400, # days
'w': 604800 # weeks
}
try:
amount = int(argument[:-1])
unit = argument[-1]
seconds = amount * multipliers[unit]
return datetime.timedelta(seconds=seconds)
except (ValueError, KeyError):
raise commands.BadArgument('Invalid duration')
there is no context for app commands
is there any workaround to make it work for app cmds?
don't use context
The analogy for app commands are Transformers. But you have to transform from a supported type
will transformers work for prefix commands aswell?
Is there a way to have an attachment argument set as optional but still showing like this for a slash command? When I put in attachment = None in the arguments of the command it is shown on the right with +1 more
Nope, that's how discord formats the options on client side
just inherit both transformer and converter, i.e ```py
class DurationConverter(Converter, Transformer):
async def convert(self, ctx: commands.Context, argument: str) -> datetime.timedelta:
return self.do_convert(argument)
async def transform(self, interaction: discord.Interaction, current: str) -> datetime.timedelta:
return self.do_convert(current)
def do_convert(self, argument):
# do datetime.timedelta convert
Hey, im trying to scrape some logs from and FTP Server. the code i have is working but im having to do scrape them individually using
fetcher = FetchFiles(type="chat")
fetcher.execute()
fetcher = FetchFiles(type="kills")
fetcher.execute()
Is there a way i can scrape all the logs at once instead of having to call them all manually? Apologies if its a bone question im pretty new to all this. Cheers 🙂
class FetchFiles:
def __init__(self, type):
self.type = type
def execute(self):
# Remove old log files
log_files = glob.glob(f"logs/{self.type}_*.log")
print(self.type)
for log_file in log_files:
os.remove(log_file)
# Connect to the FTP server
with ftplib.FTP() as ftp:
ftp.connect(FTP_HOST, FTP_PORT)
ftp.login(FTP_USERNAME, FTP_PASSWORD)
ftp.set_pasv(True)
# List files in the FTP directory
entries = ftp.nlst(FTP_BASE_PATH)
for entry in entries:
# Get the basename of the entry
basename = os.path.basename(entry)
# Check if the entry is a file and starts with the specified type
if basename.startswith(f"{self.type}_"):
if not os.path.exists(f"logs/_processed/{basename}"):
with open(f"logs/{basename}", 'wb') as local_file:
ftp.retrbinary(f"RETR {FTP_BASE_PATH}/{basename}", local_file.write)
print(f"Downloaded {basename}")
print("")
Better to ask in #1035199133436354600
Ahh my bad, thanks 🙂
how to bypass discord user limits 101
non-nitro users are limited to 10mb, bots still to 25mb - they haven't changed yet
are u able to forward that?
it's just a basic command send that sends the file according to path given
nothing fancy
nono i mean, does discord let u forward the 25mb file
since non-nitro users are limited to 10mb
oh coolll
just works for server with boosts
so the file can be posted either way just normally
ah i see
but still funny
Wait 👀 how would you forward it ? I can't even upload 20mb file
here you can
because of boosts
so i sent the file with a bot in a private server, because bots are not yet affected by the change from 25mb limit to 10mb
then forwarded it here, but it's pointless because you can post them here normally because of guild boost
if you forward in a dm or a server without boost, won't work
Nice. Thank for sharing your knowledge ❤️
e.g. that's a 25mb+ file
and thanks to server boosts, can post it even if you don't have nitro (basic)
Mm 🫡
does anyone know how to remove this part off of a slash command?
i need it off for a certain command
You don't, that's the standard ux for slash command responses. Consider responding ephemerally instead
me when people want to edit discord's ui
no i was told to do it by someone but i fiugred out it doesnt remove that
it deletes the command message and then sends the message
ah that
yo

Hey 👋 I'm new to coding and I have a question... how can I make a anti link can anyone give me a example?
what is an anti link
ok im asking, im using pycord but apparently everyones going with discord.py so even though pycord is a fork what one should i use ?
They're largely on feature parity, so pick which one you like more
There are design and functional differences but they're relatively minor in the grand scheme of things tbh
would recommend discord.py purely based on the fact that more people use it and therefore has more support and resources
how do i send timestamps?
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) for presentation within Discord.
This allows for a locale\-independent way of presenting data using Discord specific Markdown...
whats the style param?
Read the docs
how to run all task loops at once? where should i start it?
That's on you to decide which loops you want to start and when
In general I discourage these "Do X across all Y's in my entire app" exercises as it abstracts you from making a meaningful decision you should be considering in each case
if i want to implement sqlite database for my bot do i keep the connection alive the entire runtime or connect it everytime?
Connect locally when you need to. Or use a connection pool
how about i just make a single connection and make it into a bot attribute? is that bad?
In an async application, yes
Unless you lock that connection and make sure only one task uses it at a time, in which case you should just be using a pool of connections
why cant multiple tasks use it at a time tho?
They can, they shouldn't
why
You can cause race conditions if multiple parts of your code try to use the same connection simultaneously
(This includes a single task firing multiple times even if it's the same code)
which size should i even choose?
size of what?
pool size
idk man I don't know your application lol
there's not a single Right Number
trade off of how much your db can handle + how concurrent your app is + how long you're willing to wait for a connection to free up + how much memory you have/want to allocate to this
Hello, how I can fix this? I'm trying to run music using exe createed by PyInstaller
Do you have rights to distribute that music?
Yep
Have you bought the license or are you the owner of that music?
I'm the owner
Still need more context though
e.g. code
Or the command for pyinstaller you've used
Actually that's not an issue related to this channel, so should go in #1035199133436354600
It's bot for discord, that's why i thought it's here
It's for, but not related to
That's more of a pyinstaller issue/misconfiguration than a discord.py or whatever issue
okay
So I have a file 'modals.py' where I define my modal for use in an extension file called 'forms.py' (in the forms.py file i make a command where i reference and use the modal from modals.py)
So I made a reload command for reloading the forms extension but if i make changes to the modals.py and reload the bot, it doesn't reflect this change. can i fix this without making mdoals.py another extension?
Sure, you can use importlib yourself. That's really all the extension framework does
oh okay ill check it out thank you
C:\Users\o_o\AppData\Roaming\Python\Python312\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 afk.py: object list can't be used in 'await' expression
Failed to load cog casino.py: object list can't be used in 'await' expression
Failed to load cog games.py: object list can't be used in 'await' expression
Failed to load cog misc.py: object list can't be used in 'await' expression
Failed to load cog mod.py: object list can't be used in 'await' expression
Failed to load cog music.py: object list can't be used in 'await' expression
Failed to load cog restart.py: object list can't be used in 'await' expression
Failed to load cog social.py: object list can't be used in 'await' expression
Failed to load cog utility.py: object list can't be used in 'await' expression
Sure, but unless they've given you guarantees anything you build is likely to break the moment they make a trivial display change. You should really be asking yourself if there is a more stable API you could use, or at least talk to the bot owners first
If you are not using discord.py, you accidentally installed discord.py or some other discord lib. Uninstall all of the discord libs you have discord discord.py py-cord interactions.py disnake nextcord etc. And only install the one you want to use (you do not ever need to install discord)
If you are using discord.py they made extension loading asynchronous. I dont use discord.py so I cant help you with that.
PS C:\Users\o_o\Downloads\yo> python crazy.py
Traceback (most recent call last):
File "C:\Users\o_o\Downloads\yo\crazy.py", line 6, in <module>
intents = discord.Intents.default()
^^^^^^^^^^^^^^^
AttributeError: module 'discord' has no attribute 'Intents'
PS C:\Users\o_o\Downloads\yo>
What library(ies) do you have installed?
i fixed it
thank you guys
2024-10-28 16:52:30 INFO discord.client logging in using static token
2024-10-28 16:52:31 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 296664b8f8b10e6b20bf96c2064a512f).
Logged in as crazy (1297466846454222898)
Bot is online as crazy#4559
Loaded cog: afk.py
Loaded cog: casino.py
Loaded cog: games.py
Loaded cog: misc.py
Loaded cog: mod.py```
discord.py is outdated right? Which lib should I use?
Which one do you use?
discord.py started back up on development so it is no longer outdated
However there are still some other options that you can use mainly py-cord nextcord and disnake as well as some more. I recomend looking at the examples for each to see what ones you like the best although they are still very similar. I personally use py-cord
This site keeps a semi up to date comparison of the major libraries
what do you have so far? What library are you using (Or are you using the API directly). Is there a reason that you want to use prefix commands instead of slash commands?
Well you must have some code
Generally you dont need to delete your code if it does not work...
What library are you using? Have you looked at the examples for that library?
I had a problem when installing discord.py
It said that I didn't have the audioop.py dependency. I tried installing it but it doesn't install. Is there a fix for this? Because I have an application written in discord.py and I'd rather not start over
Python 3.13 got rid of audioop from the standard library. In the mean time you can install audioop-lts or downgrade to python 3.12
Well what tutorial/example/docs were you following when you tried the first time?
I can just pip install that, right?
yes
Okay lemme see
You probably pip installed something. That is called a library
I got past that part but now I ran into another depndency that doesnt run. Should I just downgrade like you said earlier?
How do you downgrade again?
If you are running the bot in an IDE I think you change just configure it to use a different python version. I dont know that much about updating/downgrading python tho sorry
It's okay and thanks!
what is a good (preferably free) way to host a custom bot?
There are no good free ways to host a bot. Every free host has its drawbacks.
In general you can get a VPS or self host on a raspberry pi + electricity costs
There are some services that give you free trials/credits for VPSes if you enter in your credit card info (and cancel it before they start charging you)
Thankfully there are methods of exchanging your time for currency that you can then use to rent a reliable host
thanks. I've heard of digital ocean before but thats one of the ones u gotta put in ur card
most will require that
most reliable ones, that is
aws has tier for small ec2 instance for a year. if you decide you want your project to keep running then you can pay whatever the nominal fee is for the small instance then
You can wait for message delete events and add a check to wait for the message ID to be the same as your bot's response
Something like
msg := send bot message
wait for message delete event where the message id == msg.id
delete msg
hi
i wonder if i should switch to aiosqlite because the standard sqlite3 module is synchronous only?
who wants to make a bot with me 💀
Have you made one before?
yes
what does it do?
moderation
Why would others wanna make a bot with you?
idk
ok good luck with that
Definitely don't use a synchronous driver in an async application. asqlite is also a good choice i would recommend
+1, Pretty much all librares that you are using should be async
try asking in #1035199133436354600 , parsing RCON output is more of a general topic
technically sqlite3 is more viable in async than typical databases since it has no network latency and can execute simple queries in the order of microseconds, but of course you'd want to be pretty confident all your queries will perform that fast before committing to it (pun intended)
Yeah stdlib sqlite is very fast for reasonable data volumes. Good to get in the habit of async but from a practical standpoint you'd probably not notice it especially in a hobbyist application
Hello! I'd like to create my fist Discord bot with Python! Where should I start?
How can I make a welcome card like that?
Hey so I got redirected here for my question, I am trying to create a script with python that can lock/unlock a channel in discord automatically based on the start and end time, it would be doing the job daily. After some research it looks like it is recommended I have a bot help me. The one thing I am confused is do I need to make the bot on my own or use a preexisting bot like mee6? I needmthe channe id and the token of the bot to do this. So far online the only examples I found that allows me to get the token of the bot is when the bot is made locally
Is there any tutorial bc I'm stupid?
?
How much python experience do you have?
if mee6 has that feature already it would be easiest to just use that
I doubt that's what they meant
I didn’t see anything. I read online that a script can be done I just need a bot and the channel id. But to use a bot I need the token. And everywhere the token is only available if I make a bot using discord instead of just importing an already existing bot
If you cannot find an existing bot that does what you want to do, you will need to make your own. Fully end to end. This is a deep endeavor, not only do you have to go through the bot creation flow you need to write/test the code and then find somewhere to host the bot
Hey, see if either of the two tutorials listed here interests you https://www.pythondiscord.com/resources/?topics=discord-bots
We're a large, friendly community focused around the Python programming language. Our community is open to those who wish to learn the language, as well as those looking to help others.
Wondering how I make a calculator with multipliers like 8x and 13x + 1000 <playerhit>, and if they have fireballs <yes> or <no> with python?
Thank you!!
better ask in #1035199133436354600
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
class MyBot(commands.Bot):
async def setup_hook(self):
await self.tree.sync(guild=None)
bot = MyBot(command_prefix="!", intents=intents)
@bot.tree.command(name="hello", description="Hello World")
async def hello(interaction: discord.Interaction):
await interaction.response.send_message("world")
bot.run("This token is not for u ;)")
i cant figure out how to make the commands show up in dms
i used the following auth
https://discord.com/oauth2/authorize?client_id=000000000000000&integration_type=1&scope=applications.commands
i removed the client Id for privacy
ive tried using aiosqlite but my connection is always closed
I can guarantee you aiosqlite and asqlite work when implemented properly
import aiosqlite
import asyncio
async def main():
db = aiosqlite.connect('main.db')
print(db.is_alive())
print(await db.execute_fetchall('SELECT * FROM sqlite_master;'))
asyncio.run(main())
what is wrong in this code?
i got ValueError: Connection closed
Looks like a #databases issue
You likely need to set up interaction contexts and installation context for your command. I dont know how to do this in discord.py but it should give you a start
I learned that to do what I want, I need to be 18 and have and ID to prove that, do I gave up
Discord does not require you to be 18 or have an ID for a bot?
You have to be 16 and have an ID to verify the bot (thus allowing it to be in more than 100 servers)
But even if you are not you can transfer ownership of the bot to a trusted individual like a parent to verify for you
Oh I thought it was 18, this gives me more reasons to get an ID/license, but I’m too lazy
You can view your countries accepted documents here it is more than just license, notably passport is another option
Hey, Guys,
Can someone give me direction about how to make 1 bot to read the messages from another bot in the channel ?
use on_message event
!on_message
Registering the on_message event with @bot.event will override the default behavior of the event. This may cause prefix commands to stop working, because they rely on the default on_message event handler.
Instead, use @bot.listen to add a listener. Listeners get added alongside the default on_message handler which allows you to have multiple handlers for the same event. This means prefix commands can still be invoked as usual. Here's an example:
@bot.listen()
async def on_message(message):
... # do stuff here
# Or...
@bot.listen('on_message')
async def message_listener(message):
... # do stuff here
You can also tell discord.py to process the message for commands as usual at the end of the on_message handler with bot.process_commands(). However, this method isn't recommended as it does not allow you to add multiple on_message handlers.
If your prefix commands are still not working, it may be because you haven't enabled the message_content intent. See /tag message_content for more info.
@pure basin is there another way of 1 bot to use app commands of another bot ? I don't think this will work in my case.
bots cannot use commands
Pass the user_id of user that ran the command into your View and save it as an instance variable. Then use interaction_check is that is a thing in your library. If it is not you can just create a function/if-statement to put in all of your button callbacks to check is the interaction user for the button press is the same as the user that you have stored in your view


