#discord-bots

1 messages · Page 392 of 1

humble violet
#

but code is hella shit haha

#

ill text you if i need help.. tysmmm bro

pine granite
pine granite
mint pecan
#

you forgot to censor the last line lol

humble violet
scenic gate
#

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

fast osprey
#

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

scenic gate
#

can i

#

not agree? lol

scenic gate
wanton current
#

You can have other methods as well, but you need to have Discord's offering as well with the same price.

scenic gate
#

Understand, thanks

slate swan
scenic gate
#

understand

slate swan
#

and not following it will either get your bot terminated, get cease and desist letter or whatever else idk

fast osprey
#

Probably sued if there's enough money on the line

slate swan
#

yeah, that's after and will be mentioned in the c&d letter

spring flax
#

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

sick birch
#

there are a lot of people writing garbage bots for like 10 bucks or whatever on fiverr

spring flax
sick birch
#

Dunno. I don’t think there are a lot of skilled developers doing discord bots on fiverr

spring flax
sick birch
#

probably not

spring flax
#

Okay thank you

fast osprey
#

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

idle pine
#

i get the following error code while using discord.py

import audioop
ModuleNotFoundError: No module named 'audioop'

slate swan
#

you haven't installed it ¯_(ツ)_/¯

wanton current
#

audioop got removed from stdlib in 3.13

idle pine
wanton current
idle pine
#

thanks

humble violet
timber dragon
#

Or just install the mentioned package?

Or explicitly use the older version; no need to uninstall it.

spice warren
#

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.

limpid finch
#

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

inner copper
limpid finch
inner copper
#

why not

#

how many lines is it

limpid finch
#

is it fine

inner copper
#

yeah

#

let me see it

limpid finch
#

1 sec

#

Bruh i sant a file and got deleted

inner copper
#

😭

#

you cant send files man

limpid finch
#

How about that

inner copper
#

you cant just copy paste the code from whatever editor you use?

limpid finch
inner copper
#

screen shot

limpid finch
#

Im using replit

#

erm

inner copper
#

so what are you trying to make the bot do exactly?

limpid finch
#

hold on gtg

stark ingot
fast osprey
spring flax
#

is there a way to host a bot without requiring entering credit card information

fast osprey
#

Buy a machine and run it

spring flax
#

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?

fast osprey
#

Docker doesnt keep your computer online and running, separate concerns

spring flax
fast osprey
#

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

spring flax
#

No I don’t want to use the laptop while it’s running (just for hosting 24/7)

slate swan
mint pecan
#

how can i make interaction.response.send_message not to reply?

mint pecan
fast osprey
#

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

spring flax
slate swan
pale zenith
#

assuming it consumes 10W, at 0,21€/kWh then that's +1,5€/mo

limpid finch
light violet
#

Is it possible to steam video in voice channel?

wanton current
#

no

light violet
wanton current
#

ask Discord

fast osprey
#

Honestly kind of what activities are for

light violet
wanton current
#

yes but it's not publically documented

slate swan
#

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

slate swan
#

Hey

slate swan
#

if you're fine with your bot showing "...is thinking" for 15 mins and then fail (?), why not

autumn nymph
#

Does anyone know how to make a user discord bot. Meaning a user that acts like a bot and can do pre programed things

slate swan
autumn nymph
#

O

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

stark ingot
neon plover
#

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'

https://paste.pythondiscord.com/XHYQ

slate swan
stark ingot
#

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.

vapid parcel
#

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?
shrewd fjord
#

!d discord.app_commands.Group

unkempt canyonBOT
#
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
```...
slate swan
#

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?

timber dragon
#

Indeed

spring flax
#

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

fast osprey
#

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

neon plover
pine granite
nova vessel
#

Using the interaction, how would I get the thread a user has used the command in from a forum channel?

fast osprey
#

Interaction.channel should be that iirc

#

!d discord.Interaction.channel

unkempt canyonBOT
slate swan
#

tracker bot attribute doesn't exist, it's custom.
Since it's something custom, you likely forgot to copy paste something :)

fast osprey
#

Also none of these "trackers" are actually functional. Discord doesnt tell you what invite was used, so all of them are just guessing

mint pecan
#

how can i add a command or a group into a cog while not being inside it?

fast osprey
#

Why would it not be?

mint pecan
#

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?

fast osprey
#

Why is it in another file?

vocal plover
mint pecan
slate swan
#

don't tell me you make one file per command

fast osprey
#

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

inner copper
#

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

slate swan
#

features, effort and time

fast osprey
#

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
sweet chasm
#

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

fast osprey
#

Code? What library are you using?

sweet chasm
sick birch
#

your question is vague, perhaps considering elaborating with more detail?

stark harness
#

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

#

alright, but that guide will walk you through the introduction for your bot

inner comet
#

Is there a problem with the API?

brisk tulip
#

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

mint pecan
inner comet
#

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

brisk tulip
brisk tulip
#

therefore, its uncatagorized, and i could post non-python, but discord bot content

mint pecan
#

How do i handle slash command errors?

shrewd fjord
unkempt canyonBOT
#

@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).
zinc gust
#

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

brisk tulip
#

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

slate swan
#

i still stand by the fact that common sense is disappearing with time

slate swan
nova vessel
#

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?

mint pecan
#

how can i add buttons to my bot presense/activity?

fast osprey
spring flax
#

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

fast osprey
#

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

spring flax
#

oh wait i think i got it

scarlet tiger
#

He is using disnake

fast osprey
#

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

scarlet tiger
#

^^^

spring flax
#

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

#

and im doing import aiosqlite
from ..all_funcs import ...
where i have main.py and all_funcs.py in the directory and then a folder with a file words.py

scarlet tiger
mint pecan
#

how can i add button to discord bot's presence anyone

timber dragon
#

Can't

#

Bots don't support that

spring flax
#

is it okay to start a tasks.loop on the on_ready event?

wanton current
#

i wouldnt

spring flax
wanton current
#

could do in a setup_hook, or a cog_load, and then have a before_loop that waits for the bot to be ready

spring flax
#

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

timber dragon
#

setup_hook is called after login

mint pecan
fast osprey
#

Same way you get it to handle any other error

shy eagle
#

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 !

wanton current
#

code?

inner copper
#

^

timber dragon
#

Use the emoji= kwarg; the label doesn't render emojis.

inner comet
#

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

fast osprey
#

if you're running dpy this will spit a warning in your console

inner comet
#

dpy?

#

can you highlight which part gives me a warning? my console is pretty much empty

fast osprey
#

yes

inner comet
#

im getting no warning in my console

fast osprey
#

Do you get anything?

nova vessel
#

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?

slate swan
#

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

inner comet
#

wait

#

your actually a genius

fast osprey
strong whale
slate swan
#

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>

dry kelp
dry kelp
slate swan
dry kelp
dry kelp
#

ctrl + shift + p if you use vsc

#

and run clear cache and reload window

inner comet
#

@fast osprey

#

this is waht I got

dry kelp
#

Else, you can ctrl + alt f4 to close vsc isisntance and just restart it up

dry kelp
#

Did you enable it in developer's portal?

inner comet
#

let me check

dry kelp
#

message content intent

inner comet
#

yea it was disabled

dry kelp
dry kelp
slate swan
#

which one

inner comet
#

@dry kelp

#

it still gives me the same error

dry kelp
dry kelp
inner comet
#

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

dry kelp
#

Ummm

inner comet
#

i removed the bot.run()

dry kelp
#

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

inner comet
#

ok let me check

slate swan
dry kelp
dry kelp
inner comet
#

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

dry kelp
#

awesome

#

No problem!

inner comet
#

nothing better than getting help from actual smart people

#

💀 wish me luck on this project

dry kelp
#

Good luck 🙂

inner comet
#

@dry kelp do you know any good resources to learn discord.py

fast osprey
#

The docs and the examples in the repo. IMO anything else I've seen written independently is outdated, garbage, or both

merry cliff
dry kelp
#

Hello

#

what's up?

slate swan
fast osprey
#

code?

slate swan
#

py

fast osprey
#

No like what is the code in that file lol

slate swan
# fast osprey 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

dry kelp
#

5 mins

slate swan
#

ok

fast osprey
#

I mean looks fine

fast osprey
slate swan
slate swan
fast osprey
tawdry sinew
#

Hi

slate swan
shut hearth
mint pecan
#

why does syncing the bot for a specific server never work?

slate swan
#

because you're likely doing it wrongly

fast osprey
#

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

mint pecan
fast osprey
#

What's your goal here? For a command to only be available in one guild?

languid dragon
#

Hi

shut hearth
#

@fast osprey

fast osprey
#

...yes?

shut hearth
# fast osprey ...yes?

everytime when i do ,afk on my bot it sends the hey you have been afk for some duration

fast osprey
#

There is already an existing away system baked into discord

shut hearth
#

how can i remove it

#

so the code can actually work

fast osprey
#

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

shut hearth
#

ima send my afk command in chat

fast osprey
#

bam, I've done something to show people I'm away

shut hearth
#

😭 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

fast osprey
#

Why do they want to go afk "with your bot". There is already something that exists

shut hearth
#

and bleed bot

fast osprey
#

Seems useless and cumbersome

abstract coral
#

py" i"

frank osprey
#

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 ?

wanton current
#

can you show your code?

#

no intent would impact this

frank osprey
vocal plover
#

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

frank osprey
#

Thank you very much

twin flower
#

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

wanton current
#

anything free is generally bad

fast osprey
#

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

hasty pike
#
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

fast osprey
#

iirc you shouldn't be sending messages in checks like this. Throw an exception and send messages in your error handling

hasty pike
#

So i should prioritize building my help command or this can be countered for now?

languid glen
fast osprey
marble prism
vocal plover
mint pecan
#

how can i send my command in message like this?

slate swan
mint pecan
slate swan
#

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

mint pecan
slate swan
#

!d discord.app_commands.AppCommand.id

unkempt canyonBOT
slate swan
#

!d discord.app_commands.AppCommand.mention

unkempt canyonBOT
slate swan
#

Last one is to directly mention without having to format yourself

mint pecan
slate swan
#

Not all Command have mentions available, only app commands

mint pecan
slate swan
#

And that returns Command or Group

mint pecan
scarlet tiger
mint pecan
scarlet tiger
mint pecan
scarlet tiger
timber dragon
#

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 mention for 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}")
jagged vortex
#

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

tropic burrow
#
    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

fast osprey
#

what OS are you on?

tropic burrow
fast osprey
#
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!
tropic burrow
#

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

mint pecan
#

why am i getting duplicate slash commands after syncing to a specific guild using tree.copy_global_to and tree.sync?

fast osprey
#

Because guild tied commands and global commands are stored separately.

#

You should not register a command in both

civic blade
#

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)

stark ingot
#
  1. Restart your IDE and try again
  2. Ensure that you only have 1 discord bot library installed.
  3. Uninstall the other discord bot libraries you are not using
  4. Reinstall the discord library you are using
  5. Restart your IDE
static sonnet
#

hi

celest bough
#

hi

#

👋

#

how are u?

static sonnet
#

can i present you guys my own AI chat bot made in python?

celest bough
#

yup

#

is that external app?

static sonnet
#

yes

celest bough
#

okay

static sonnet
#

wait, external apps cannot be used here 😭

timber dragon
wanton current
dreamy nacelle
#

hi

#

can anyone help

#

?

fast osprey
#

Sure, ask your question and if anyone knows the answer they will

dreamy nacelle
#

SSL: CERTIFICATE_VERIFY_FAILED error solution

solar pollen
#

i know this is kinda offtopic and stupid to ask but what should i name my cog for owner-only commands like sync?

tropic burrow
#
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

slate swan
#

discord.Client means an instance object, so you'd need that object and not call the function on the class itself

slate swan
#

Yeah

#

It has additional features as well, but that one is included in both

tropic burrow
#
   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

merry cliff
timber dragon
#

^ Use the > < operators on Role

if role > top_role:
    ... # role too high
fast osprey
#

Your bot should never have admin, that's an incredibly unnecessary risk

hearty cloak
#

Hello, as I understood, there is no free options to run bot 24/7?

fast osprey
#

None worth considering seriously

mint pecan
#

does bot.walk_commands include slash commands aswell?

golden portal
#

nope

mint pecan
#

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?

fast osprey
#

What library are you using?

mint pecan
fast osprey
#

iirc autocompletes only return the value, not the display name. Just typehint with the raw type in your command

twilit sparrow
#

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

fast osprey
#

Do you have a base proficiency in python? Including concepts like OOP/class design and asyncio?

twilit sparrow
fast osprey
#

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

slate swan
#

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
  • asyncio basics
  • What is "blocking?"
  • Logging
  • Reading documentation properly
fast osprey
#

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.

slate swan
#

And lots of youtube tutorials are outdated or show bad practice

#

Which e.g. leads to people doing bot = discord.Client()

slate swan
#

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

fast osprey
dreamy nacelle
#

SSL: CERTIFICATE_VERIFY_FAILED

#

@fast osprey

fast osprey
#

No like. Full error. All of the output, and again describe what you did to try to fix it

dreamy nacelle
fast osprey
#

Describe the specific steps you did, and again, paste the full error

dreamy nacelle
#

I tried all the solutions I saw on YouTube and nothing changed.

dreamy nacelle
#

(Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self-signed certificate (_ssl.c:1020)')))

#

this is result

fast osprey
#

Describe what you did.

#

Paste the full error.

vapid parcel
#

How short and long do UID get?

slate swan
#

17-19 chars

#

17 very old, 18 old, 19 newer accounts

sometime it will be 20

dreamy nacelle
#

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

#

?

vapid parcel
#

cuz I lowkey hate when I have to use str when using NUMBERS cough cough discord.

#

"int to long" GoofySkull

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.

hushed galleon
#

iirc 2084 is when discord snowflakes will exceed the signed 64-bit integer limit used by most(?) databases

vapid parcel
#

if we are alive GoofySkull

#

if nuclear war / atomic war hasn't happened by 2084 then sure 😁

inner copper
#

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

hushed galleon
# inner copper hello guys i just switched to linux and i have no clue how to install py cord co...

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

dreamy nacelle
#

@fast osprey i waiting u

#

?

fast osprey
#

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

dusty spoke
#

Is discord.js the same as discord.py? Or it has a different process

stark ingot
#

One is for javascript and one is for python but they are both for making bots

prime condor
#

what is the code for a bot to give a specific user an already exising role?

dusty spoke
mint pecan
#

how can i get the cog of a group?

late blade
#

hey

mint pecan
#

How can i get the cog assigned to a command anyone?

fast osprey
#

Why? What is this driving? Usually you can put that logic somewhere in the cog itself

fast osprey
#

What is the code you're writing that wants to know this

mint pecan
#

also my question was a bit incorrectly im trying to get the cog of an AppCommand object, if there is

fast osprey
#

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

stark ingot
#

I generally have a /info command instead of a help command that shares additional information about the bot

inner copper
hearty cloak
#

Hello, how I can make imports to my discord bot, using PyInstaller, he doesn't see library

shy eagle
#

how do i add these blue commands?

#

to my embed

shy eagle
#

what abt this?

slate swan
vapid parcel
#

So, I am trying to make discord.Spotify work right? But it won't detect that I am using spotify?

vapid parcel
#

    @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?

fast osprey
#

You don't get presence info on interactions

#

you need to look up the user

vapid parcel
#

Well, ty

junior night
#

simple question: why is this not running when i remove a reaction...

hushed galleon
unkempt canyonBOT
#

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.
hushed galleon
#

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

slate swan
#

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

slate swan
#

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

frank osprey
#

Question? does anyone know of a python based bump bot whos code i could get my hands on ?

mint pecan
#

how can i get the bot from interaction object?

golden portal
#

!d discord.Interaction.client

unkempt canyonBOT
#

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.
grizzled olive
#

hello everyone

shy eagle
#

how do i retrieve the id of a slash command

scarlet tiger
fast osprey
#

Can also get it from the client yourself

shy eagle
#

the client id?

fast osprey
#

no the discord client you're typing into now

mint pecan
#

How do i add colors to codeblock?

slate swan
mint pecan
#

how do i add description to app command's params?

fast osprey
#

!d discord.app_commands.describe

unkempt canyonBOT
#

@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...
mint pecan
# unkempt canyon

is it better if i use app_commands.Parameter(...) and then pass it to the param?

fast osprey
#

No

#

"Better" is pretty nebulous here

#

One could say that the docstring approach is better as you should be documenting your code anyways

slate swan
#

my code itself is the documentation shipit

junior night
#

quick question: does discord.py require asnyc requests when sending get requests within a command or can i just use requests.het

slate swan
#

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?

fast osprey
fast osprey
slate swan
#

and only one instance of the bot running

fast osprey
#

Are all of the fields identical?

slate swan
fast osprey
#

The values in before and after

slate swan
#

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

slate swan
fast osprey
#

They are all identical on both firings?

slate swan
slate swan
#

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

fast osprey
#

Who does the bot say is changing their presence?

slate swan
fast osprey
#

So it's saying you're changing your presence when you're not?

slate swan
#

idk how its called

fast osprey
#

So you aren't the only one in the server besides the bot, there are other bots?

slate swan
#

its not a member in the server

#

but that isnt my problem

fast osprey
slate swan
#

the problem is whenever i change my status, it calls the function twice

fast osprey
#

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

slate swan
#

i think its about that

fast osprey
#

That isn't what this is

#

Your bot is in a server with that user, period

slate swan
#

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

fast osprey
#

In a server

#

The bot corresponding to the token you're running at least

slate swan
#

the only server the bot is in is that server

#

wait actually

fast osprey
#

And how are you verifying that?

slate swan
#

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

fast osprey
slate swan
#

works fine now

fast osprey
#

Evaling out bot.guilds is also a pretty quick way to see this

#

Awesome

slate swan
cinder walrus
#

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

thin raft
#

!intents

unkempt canyonBOT
#
Using intents in discord.py

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.

fast osprey
#

(Also that is a warning, not an error, and it tells you what behavior it will cause)

tropic burrow
#

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

fast osprey
#

Bots already get a commandtree

#

and you shouldn't name a variable client if it stores a bot, different types entirely

daring helm
#

is for someone slash commands also not working?

pure basin
#

not working as in?

#

working fine for me

daring helm
#

commands not showing, if i create a new command it wont show also

pure basin
#

did u sync?

daring helm
#

yes ofc

pure basin
#

did u reload discord?

daring helm
#

yep

#

i got thisd since 3 days

pure basin
#

how are u syncing?

daring helm
#

await client.tree.sync()

#

sorry

#

await client.tree.sync(guild=discord.Object(id=1264238401981513728))

pure basin
#

i mean where, like in on_ready or in a command

fast osprey
#

Is that command registered to that guild?

daring helm
daring helm
daring helm
daring helm
fast osprey
#

Yeah firstly don't do this or change presence in on_ready. You've been lied to about how that event works

daring helm
#

so js like that

pure basin
#

the sync as well

fast osprey
#

Yeah don't sync in on_ready

daring helm
#

fuck you mean dont sync in on ready

slate swan
#

the event is not for what you think it is

fast osprey
#

There's really no other way to read that. Don't do it

daring helm
thin raft
#

!d discord.on_ready

#

wtf

unkempt canyonBOT
#

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.
fast osprey
#

Logic that cares about when cache is repopulated after a reconnect, which isn't what you're doing

daring helm
#

Where should I call them then?

fast osprey
#

Trying to change presence in on_ready can straight up disconnect you

#

You should sync manually when you need to only

slate swan
#

make a sync command

#

!d discord.Client.setup_hook # not an event

unkempt canyonBOT
#

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)...
thin raft
#

yeah that one

slate swan
#

though shouldn't sync there either

thin raft
#

better than on ready tho

daring helm
#

Won’t fix the issue 100% give me 5 mins I’ll try it

scarlet tiger
#

Why is it sometimes difficult to create application commands in discord.py? Other libraries automatically synchronize commands.

slate swan
#

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.

scarlet tiger
slate swan
#

pretty much the same as making a command and sync when needed

#

both projects also clearly have different design goals as well

scarlet tiger
#

Yes, but sometimes I find it very strange how discord.py handles application commands.

slate swan
#

it's kind of the normal behaviour to be fair

daring helm
#

oh fuck it really worked with synching via command thanks ❤️

slate swan
scarlet tiger
fast osprey
#

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

slate swan
#

and there is also a limit or commands you can create a per day ^

daring helm
#

hmm okay ty

pure basin
#

what is it?

stark ingot
#

200 global command create/edits a day.
200 guild command create/edits per guild per day

fast osprey
#

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

mint pecan
# daring helm

you need to use tree.copy_global_to if you want to sync locally i think

#

not sure

spring flax
#

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

fast osprey
#

Sure what's the question? Just want recommendations?

spring flax
#

I hope I don’t have to spend too much on it also

slate swan
fast osprey
#

First order of business is probably to profile your app(s) so you know what resources you need

spring flax
#

Profile as in see their memory usage etc?

fast osprey
#

memory, cpu, disk space, etc

#

network probably isn't going to be a bottleneck but who knows what you're doing

tame nymph
#

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

fast osprey
#

Like for interactions over http?

tame nymph
#

yes

#

u can do that with slash commands/component interactions/ and those other app commands right

fast osprey
tame nymph
#

which page is that

fast osprey
#

portal -> applications -> general information -> scroll down

tame nymph
#

my bad

#

alr i found it

steep estuary
#

bot.get_emoji() isn't working, is there any change? using discord.py

steep estuary
#

not working in my case, using discord.PartialEmoji.from_str instead

timber dragon
#

wdym it isnt't working?

steep estuary
timber dragon
#

what are you passing to it

#

and which emoji is it supposed to get

#

and do you need an Emoji obj

steep estuary
#
await ctx.send(bot.get_emoji(1299497508942250046)) # not working.
await ctx.send(discord.PartialEmoji.from_str(":s:")) # working for me

passing emoji's id

timber dragon
#

how did you get the id?

steep estuary
#

by sending \emoji

timber dragon
#

is the bot in the server with the emoji?

steep estuary
#

yes

steep estuary
timber dragon
#

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

steep estuary
#

emojis intent? is it default turned off?

timber dragon
#

no it's enabled by default

steep estuary
#

the bot is in the same server and the emoji's id is correct

timber dragon
#

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")
steep estuary
#

ok

#

very long result

timber dragon
#

what does that third line say

#

fourth*

steep estuary
#
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

timber dragon
#

the one after is None I assume?

timber dragon
steep estuary
#

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

timber dragon
#

how are your intents defined

steep estuary
#

there are only 3 intents on the discord developer portal right?

timber dragon
#

yes

#

there are three intents that require verifying if in 100+ guilds

steep estuary
#

Then what intents are you talking about?

timber dragon
#

are you not passing some intents to your Bot constructor?

steep estuary
#

why the bot isn't showing up on the members list

timber dragon
#

Bot(..., intents=<here>, ...)

timber dragon
steep estuary
#
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix=DEFAULT_PREFIX, case_insensitive=True, intents=intents, help_command=None)
steep estuary
timber dragon
#

you sure?

#

try adding it and see if anything changes

steep estuary
#

is there multiple ways of adding an app?

#

what happened to discord, what are those weird updates

#

is this even a bot?

timber dragon
#

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
timber dragon
steep estuary
#

why I can't give it a role then?

timber dragon
#

either you don't have perms to or it isn't in a server

#

how did you add it?

steep estuary
#

Add App then Add to server

timber dragon
#

and are you looking at the bot's profile in the server you added it to?

steep estuary
#

yes

timber dragon
#

and do you have permissions to add roles to members?

steep estuary
#

I am the owner

timber dragon
#

what if you click on the bot's avatar

steep estuary
#

maybe the way of adding isn't real

#

there are some mutual servers

#

still it is showing no mutuals

timber dragon
#

looks like that bot isn't in any servers lol

slate swan
#

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..

steep estuary
#

got it

slate swan
#

And if you want a default role for the bot, you gotta add a permissions query param as well

timber dragon
steep estuary
#

ok

#

thanks for helping

candid ether
#

Made a youtube player discord bot

#

Dm if you want the sourcecode as I cant post it hear

slate swan
timber dragon
candid ether
slate swan
#

We still don't need source code of stuff against rule 2/discord tos here

timber dragon
#

what's the point of sending it here? are you asking for a review or..?

candid ether
#

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

slate swan
#

YouTube -> mp3, mp4, ... -> against YouTube's ToS

Anything against a website's ToS -> against Discord (Developer) ToS

scenic gate
#

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?

polar ice
#

Hey, which is the best up to date libary for creating a discord bot?

#

Last i was here they were dis-continuing discord.py?

fast osprey
#

They have not, that was years ago

#

"best" is largely subjective at this point

slate swan
#

is there any difference between using add_item or the decorator to add a button or any item really to a View

fast osprey
#

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

mint pecan
#

should i store my bot token in a db or just .env?

merry cliff
mint pecan
merry cliff
#

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

merry cliff
#

Another bonus is that since they are the standard then more people will understand your code base easier

timber dragon
#

Or use toml as config
Db is definitely overkill as said above

desert shard
#

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?

scenic dove
#

You would have to Download the File, modify it, upload it

desert shard
#

💀

scenic dove
# desert shard 💀

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.

desert shard
#

I want manage outside of scope direct in DC by bot

scenic dove
#

Yeah but still, to edit the data you would need to get the data which is the same as downloading the file

desert shard
#

Btw I want make a panel for game servers

fast osprey
#

what why would that preclude you from downloading files

desert shard
#

💀

fast osprey
#

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

scenic dove
#

Just make a website at that point.

desert shard
scenic dove
#

DC Bot is IN DISCORD

#

A Discord bot is a script

fast osprey
mint pecan
#

how do i use Converter for app cmds? i got unsupported annotation error but it works fine for prefix commands

slate swan
#

What converter do you use

mint pecan
slate swan
#

not helping

mint pecan
#

wdym

slate swan
#

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

mint pecan
# slate swan Show it rather than describe it
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')
slate swan
#

there is no context for app commands

mint pecan
slate swan
#

don't use context

fast osprey
#

The analogy for app commands are Transformers. But you have to transform from a supported type

mint pecan
slate swan
#

no

silent portal
#

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

slate swan
#

Nope, that's how discord formats the options on client side

golden portal
# mint pecan is there any workaround to make it work for app cmds?

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
polar ice
#

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("")
polar ice
#

Ahh my bad, thanks 🙂

slate swan
#

how to bypass discord user limits 101
non-nitro users are limited to 10mb, bots still to 25mb - they haven't changed yet

slate swan
#

it's just a basic command send that sends the file according to path given

#

nothing fancy

pure basin
#

nono i mean, does discord let u forward the 25mb file

#

since non-nitro users are limited to 10mb

slate swan
#

OH

#

lmao wait

#

let's gooooo

pure basin
#

oh coolll

slate swan
#

so the file can be posted either way just normally

pure basin
slate swan
#

but still funny

sterile kettle
slate swan
#

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

sterile kettle
slate swan
#

and thanks to server boosts, can post it even if you don't have nitro (basic)

shell adder
#

does anyone know how to remove this part off of a slash command?

#

i need it off for a certain command

fast osprey
#

You don't, that's the standard ux for slash command responses. Consider responding ephemerally instead

slate swan
#

me when people want to edit discord's ui

shell adder
#

it deletes the command message and then sends the message

slate swan
#

ah that

full lily
#

yo

slate swan
trail merlin
#

Hey 👋 I'm new to coding and I have a question... how can I make a anti link can anyone give me a example?

frank osprey
#

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 ?

fast osprey
#

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

sick birch
mint pecan
#

how do i send timestamps?

golden portal
unkempt canyonBOT
#

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...
mint pecan
timber dragon
#

Read the docs

mint pecan
#

how to run all task loops at once? where should i start it?

fast osprey
#

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

mint pecan
fast osprey
#

Connect locally when you need to. Or use a connection pool

mint pecan
fast osprey
#

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

mint pecan
fast osprey
#

They can, they shouldn't

mint pecan
#

why

fast osprey
#

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)

mint pecan
fast osprey
#

size of what?

mint pecan
fast osprey
#

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

hearty cloak
#

Hello, how I can fix this? I'm trying to run music using exe createed by PyInstaller

fast osprey
#

Do you have rights to distribute that music?

hearty cloak
#

Yep

slate swan
#

Have you bought the license or are you the owner of that music?

hearty cloak
#

I'm the owner

slate swan
#

Still need more context though

#

e.g. code

#

Or the command for pyinstaller you've used

hearty cloak
#

When i'm running the code using python main.py, this music is running

hearty cloak
slate swan
#

It's for, but not related to

#

That's more of a pyinstaller issue/misconfiguration than a discord.py or whatever issue

hearty cloak
#

okay

spring flax
#

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?

fast osprey
#

Sure, you can use importlib yourself. That's really all the extension framework does

spring flax
#

oh okay ill check it out thank you

shut hearth
#

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
fast osprey
#

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

stark ingot
# shut hearth ```python C:\Users\o_o\AppData\Roaming\Python\Python312\site-packages\discord\c...

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.

shut hearth
fast osprey
#

What library(ies) do you have installed?

shut hearth
#

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```
tawny junco
#

discord.py is outdated right? Which lib should I use?

stark ingot
#

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?

tawny junco
stark ingot
#

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?

tawny junco
stark ingot
#

yes

tawny junco
#

Okay lemme see

stark ingot
#

You probably pip installed something. That is called a library

tawny junco
# stark ingot yes

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?

stark ingot
#

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

tawny junco
#

It's okay and thanks!

dense crest
#

what is a good (preferably free) way to host a custom bot?

stark ingot
#

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)

fast osprey
#

Thankfully there are methods of exchanging your time for currency that you can then use to rent a reliable host

dense crest
sick birch
#

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

slate swan
#

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

mint pecan
slate swan
#

who wants to make a bot with me 💀

gleaming inlet
slate swan
gleaming inlet
slate swan
gleaming inlet
gleaming inlet
#

ok good luck with that

fast osprey
stark ingot
#

+1, Pretty much all librares that you are using should be async

hushed galleon
hushed galleon
fast osprey
#

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

wheat summit
#

Hello! I'd like to create my fist Discord bot with Python! Where should I start?

trail merlin
#

How can I make a welcome card like that?

worn gate
#

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

trail merlin
fast osprey
#

How much python experience do you have?

sick birch
pale zenith
#

I doubt that's what they meant

worn gate
fast osprey
#

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

languid jungle
plush zealot
#

Wondering how I make a calculator with multipliers like 8x and 13x + 1000 <playerhit>, and if they have fireballs <yes> or <no> with python?

karmic oriole
#
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

mint pecan
fast osprey
#

I can guarantee you aiosqlite and asqlite work when implemented properly

mint pecan
#

i got ValueError: Connection closed

slate swan
stark ingot
karmic oriole
stark ingot
#

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

karmic oriole
stark ingot
#

You can view your countries accepted documents here it is more than just license, notably passport is another option

delicate cape
#

Hey, Guys,

Can someone give me direction about how to make 1 bot to read the messages from another bot in the channel ?

pure basin
#

!on_message

unkempt canyonBOT
#
The discord.py `on_message` event

Registering the on_message event with @bot.event will override the default behavior of the event. This may cause prefix commands to stop working, because they rely on the default on_message event handler.

Instead, use @bot.listen to add a listener. Listeners get added alongside the default on_message handler which allows you to have multiple handlers for the same event. This means prefix commands can still be invoked as usual. Here's an example:

@bot.listen()
async def on_message(message):
    ...  # do stuff here

# Or...

@bot.listen('on_message')
async def message_listener(message):
    ...  # do stuff here

You can also tell discord.py to process the message for commands as usual at the end of the on_message handler with bot.process_commands(). However, this method isn't recommended as it does not allow you to add multiple on_message handlers.

If your prefix commands are still not working, it may be because you haven't enabled the message_content intent. See /tag message_content for more info.

slate swan
#

whats the easiest way to make buttons owner only

#

owner of the command*

fast osprey
#

Who owns a command?

#

And which command?

delicate cape
#

@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.

pure basin
#

bots cannot use commands

stark ingot
# slate swan whats the easiest way to make buttons owner only

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