#discord-bots

1 messages · Page 332 of 1

timber lotus
#

i dig it bro.

barren gyro
#

😅

timber lotus
#

my favorite feature is explain. you can hightlight code and it will explain it. very useful when debugging

barren gyro
#

Alr, nvm. I give up. 1k+ lines ain't that much.

timber lotus
#

haha you got this!!!

final iron
#

Why are you manually adding commands to the bot

timber lotus
final iron
#

Why are you manually appending commands to the bots command list

timber lotus
#

i dont understand what your asking? haha if im doing it, its because thats what i found when i was trying to figure out to do something

#

ohhh what you tagged, thats just what it said from the discord link i shared

#

this

#

or i read it wrong

final iron
#

and the guy left the server

#

great

timber lotus
#

To load this extension we call await bot.load_extension('hello'). ahh i see now haha

#

why did he leave the server? lol he got it working

final iron
#

Yes, but a whole lot of what you told him is poor practice

#

You shouldn’t be manually adding commands, especially in the on_ready event

timber lotus
#

ok and i said i was newto coding mutliple times

final iron
#

You think the on_ready event is something it isn’t

timber lotus
#

15 days bro

#

hahaha

final iron
#

Yeah, but you gave him advice and he took it

#

Now he’s going to have issues in the future

timber lotus
#

whoa now, i didnt give him advice. i clearly said i can tell him how i had to do it. which by the way, most of it i got from this discord

final iron
#

He’s using your code

timber lotus
#

my bad bro, ill shut up for now on

final iron
#

Even if you have no intention of giving him advice, he clearly took it

final iron
#

!d discord.on_ready

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.
final iron
#

Is this solved?

timber lotus
#

you tell me, i never had an issue

final iron
#

Intents.all() is generally discouraged as it causes a large amount of unnecessary caching

#

No, and it’s generally discouraged as well

#

Cogs are just classes, they have nothing to do with files/folders

timber lotus
#

so all these nots are doing it wrong using / as the command prefix?

final iron
#

they’re not using those as a command prefix

#

Dyno uses a question mark or whatever

timber lotus
#

bro.. you see the slash command prefix in the picture...

#

and dyno

final iron
#

Command prefixes have nothing to do with slash commands

#

They’re independent

weary copper
#

i basically followed the code that someone had on their repo

#

sec i'll post here

#
from discord import Intents
from env import BOT_TOKEN
from discord.ext import commands
from pathlib import Path
import os

class MyBot(commands.Bot):
    def __init__(self, command_prefix, description, intents):
        super().__init__(
            command_prefix=command_prefix,
            description=description,
            intents=intents
        )

    async def on_ready(self):
        print(f"Logged in as {self.user}.")

    async def load_cogs(self):
        cogs_dir = f"{Path(__file__).parent}/cogs"
        for file in os.listdir(cogs_dir):
            if file.endswith(".py"):
                extension_name = file[:-3]
                try:
                    await self.load_extension(f"cogs.{extension_name}")
                except Exception as e:
                    print(e)
                else:
                    print(f"{extension_name} loaded")

    async def setup_hook(self):
        """ Runs when the bot first starts up """
        await self.load_cogs()


def main():
    bot = MyBot(
        command_prefix="!",
        description="Test Bot",
        intents=Intents.all()
    )
    bot.run(BOT_TOKEN)


if __name__ == "__main__":
    main()```
#

this worked for me

#

didn't realise setup_hook was a thing. but it seems to let you define an async function that can load cogs (and whatever else you want to load when you first start the bot)

final iron
#

Yeah it’s pretty useful

weary copper
#

i still don't know why all the sample code on the internet doesn't work though

#

I presume load_extension has changed or something

#

because all the snippets I've seen treat it as a synchronous function

final iron
#

It used to be pre 2.0

weary copper
#

ohh I see. when was that?

#

oh aug 2022, i see

#

no wonder chatgpt wasn't helpful 😂

shrewd vapor
#

hey

#
if interaction.channel.id != id:
        embed_error = discord.Embed(title = "Wrong channel", description = "Please use the bot in channel", color = 0xFF0000)
        embed_error.set_image(url = "")
        await interaction.followup.send(embed = embed_error, ephemeral = True)```

I don't understand why with this the response is not ephemeral
golden portal
#

was your defer ephemeral?

sick birch
#

i don't think your followups can be ephemeral unless the original response is also

drifting arrow
#

Nope

#

They cant be.

#

However! The initial response will always be ephemeral, and you can then set the ones afterwards to be non-ephemeral if you want.

#

At least, that's what I believe is happening when I run my code and make mistakes lol

#

I would test, but that requires setting up an entire bot just to test.

shrewd vapor
#

Hmm ok ty

drifting arrow
#

I tested anyway

#

So now we know \o/

drifting arrow
#

Only the initial followup follows the defers ephemeral settings

#

The more we know (:

#

@shrewd vapor Hope my tests have helped you

shrewd vapor
#

kk ty

final iron
#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

This is only supported with the following interaction types...
final iron
#

Indicates whether the deferred message will eventually be ephemeral.

Docs are your friend. Remember to check them out

dense gyro
#

when making discord modals, is it possible to allow mentions in the text box?

note: brackets are empty because there are no user or role mentions even though it contains the default text to mention. i have also tried <@userid> and that doesnt work either

dense gyro
#

does that create a dropdown or something?

final iron
#

Yes

#

It’s a form of a dropdown

dense gyro
#

can it be epheremal?

#

i cannot do DMs for this, so i liked modals since they only appear to the user

final iron
#

Everything attached to an ephemeral message is also invisible

dense gyro
#

and i cant put a userselect in the modal instead of the TextInput?

final iron
#

no

dense gyro
#

damn, i just spent like 4 hours tryna get a modal to work and thats all useless now

final iron
#

You’ll still need it to get the team name

#

So it wasn’t wasted time

dense gyro
#

the only reason i would need a team name is if im registering a team, in which they need to mention their team members so i can assign roles and put IDs in my db

#

so i cant use it

final iron
#

?

#

You’re given Member object with a user select

#

You can get the roles and IDs with that object

dense gyro
#

yes but i cant use userselect with a modal, so the time spent trying to get a modal to work is useless

midnight oracle
#

I'm getting this when trying to install discord.py in my local machine

      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for multidict
Failed to build multidict
ERROR: Could not build wheels for multidict, which is required to install pyproject.toml-based projects
#

any idea what it is?

dense gyro
#

at least someone is having a worse day than me😂
try uninstalling discord.py if it is installed

final iron
midnight oracle
#

new pc

final iron
dense gyro
final iron
#

no

#

It’s a form of dropdown menu

dense gyro
#

well can it be in an embed?

#

i googled images of it to see if it would work

final iron
#

That isn’t in an embed

dense gyro
#

whats behind it is

#

oh, its under it completely

midnight oracle
final iron
dense gyro
#

either way if the modal isnt a one-stop everything submitted window, i may as well have all the entry boxes in the same message instead of making them do a modal and then a dropdown

final iron
dense gyro
#

thanks for your help, i didnt know what the dropdown thing was called ive seen it before

#

sad that it cant be in a modal

midnight oracle
final iron
#

They could be coming the future though

#

I believe that’s discords end goals with modals

dense gyro
#

thanks for your help btw

final iron
#

Discord devs are very special

#

The amount of dumbass shit in their API would surprise you considering they're a multi billion dollar company

dense gyro
#

😂

plain ravine
#

yo currently working on a small bot that'll be used for a few servers but i came across a problem that i cant find a solution to online. right now, since im only working on the bot in a single server, i have each command use a constant guild id- however if im wanting the bot to be in multiple servers, how would i go about identifying the servers that the bot is in? its kinda hard to explain my problem here sorry yalls im relatively new to python, comin from lua

fiery girder
#

how is message a none type

golden portal
#

!d discord.Interaction.original_response

unkempt canyonBOT
#

await original_response()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Fetches the original interaction response message associated with the interaction.

If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message) or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).

Repeated calls to this will return a cached value.
golden portal
#

use that right after send_message to get the mesage

fiery girder
#

ok ill try that

fiery girder
golden portal
#

welcoem

fiery girder
# golden portal welcoem

if i open a file with with open will it interfere with the async function or do i have to use async with open to open files

golden portal
vapid parcel
#

is sniping against discord tos?

#

like message sniping

desert kiln
vapid parcel
#

Say you delete a message

#

the bot will put it in a list, you run /snipe

#

it gives you the last deleted message

#

you can also store it in a db, but you really have no reason to do so.

desert kiln
#

it's a 50/50 with discord

#

because they're logging bots, even Dyno has it, but it's a grey area

vapid parcel
#

well see

#

a friend said, most logs are in a staff area

#

but snipping can be ran by anyone

#

sniping*

fiery girder
#

i use to save messages in a db but i stopped

#

but it was for staff only

vapid parcel
#

Example video

dreamy dune
#

I don't think it's against tos/enforced but it's still an invasion of privacy

fiery girder
vapid parcel
vapid parcel
#

Im mainly needing to know if its against tos tbh

desert kiln
dreamy dune
vapid parcel
#

like say a friend send a stupid message then deleted it

#

you could snipe it then bully them :)

fiery girder
#

jsut read the TOS

#

simple

vapid parcel
vale wing
fiery girder
#

i have never read it in my life

vapid parcel
#

to much reading

desert kiln
fiery girder
#

my pc even agree with me i pulled up the tos and it just showign a black screen

vapid parcel
desert kiln
vapid parcel
#

I thought logs like dyno n mee6 are fine?

fiery girder
#

loggings for staff perpose is legal

vapid parcel
#

Okay, sniping is deleted then, imma add logs tho later, for staff, been needing to do all of that ngl lol

desert kiln
vapid parcel
#

im not using a self bot

#

you realize that right 😭

desert kiln
#

it's more accurate than Discords website itself.

vapid parcel
#

this is part of a discord bot, not a self bot GoofySkull

desert kiln
vapid parcel
#

See gpt doesnt even know bro 😭

#

'maybe'

desert kiln
# vapid parcel

you go with whatever floats your boat, but if you or your bot gets disabled for breaking ToS, I told you so.

vale wing
vapid parcel
#

Okay okay, just wondering tho

#

how is this bot still up 😭

vale wing
#

Report it for breaking developer policy (but actually check their privacy policy aforehead cause they might state that)

desert kiln
# vapid parcel

because that bot has it's use stated, and if it's added, people can leave the server, but if you're making one, with the idealogy to "bully" that's against ToS.

vapid parcel
#

dont twist it now 😭

vapid parcel
vale wing
#

Legal problems in discord bots are the hardest tbh 💀

desert kiln
vale wing
vapid parcel
#

Nah when i mean bully, i mean like tease, not like actually bully bro

fiery girder
vapid parcel
fiery girder
#

i know i spelt that wrong

vapid parcel
#

'like say a friend'

#

just saying shrug

desert kiln
#

Okay so, you don't understand correct english grammar.

vapid parcel
fiery girder
vapid parcel
vale wing
#

My bot has some grey area functionality, invite tracking to be precise, but I state that in privacy policy and also the ways to omit invite being saved to my db

vale wing
vale wing
#

Nobody here really knows since we're programmers and not lawyers

vapid parcel
#

You are 100% a lawyer, you showed me your ID.. totally

vapid parcel
#

Well technically

#

i already state that we store messages

#

So i should be fine honestly, discord has already verified me, not like they actually fucking read the bots, they are to lazy, but i mean, i do state what i do.

latent pier
#

what can i do about this

vapid parcel
#

we dont have magic powers 😭

latent pier
vapid parcel
#

its a command that is rate limiting you

#

what command is running a lot?

#

like example, role add, delete channels, add roles, mass delete roles..?

latent pier
vapid parcel
#

if you do role add to 100 people

#

could cause rate limit

fiery girder
#

heck if you delete to many messages

latent pier
#

its testing bot i dont use it much

vapid parcel
#

ive never been rate limited ngl

#

cuz of private vps!!

vapid parcel
#

idk how else I could help without seeing some type of command or saying just add cool down

latent pier
vapid parcel
#

name them.

latent pier
#

wait

#
test:
  test 
​No Category:
  av   Shows user avatar.
  help Shows this message
  slap .slap <user>

Type .help command for more info on a command.
You can also type .help category for more info on a category.
#

these are all

vapid parcel
#

what is your host?

#

or vps

latent pier
vapid parcel
#

never used it, idk how you could be getting rate limited then...

#

How many servers?

latent pier
latent pier
vapid parcel
latent pier
#

or less

vale wing
latent pier
vapid parcel
vale wing
#

Do you have ability to test it locally

latent pier
#

but i tried to change token and stilll same warning

vale wing
#

Because it's IP based

latent pier
vale wing
#

God knows what runs on gh codespaces

latent pier
#

gotcha ill change, thanks

desert kiln
#

Anyone have the issue of when hosting a bot locally, your ping is 100ms+?

hardy geyser
#
  File "/home/container/main.py", line 4, in <module>
    import discord, aiohttp
ModuleNotFoundError: No module named 'discord'```
#

anyone know this ?

slate swan
hardy geyser
fiery girder
#

it executes perfectly when i run the command but it fails whe my friends run it

slate swan
fiery girder
#

but it works fine for me

slate swan
#

If error appears then how can it work fine pithink

fiery girder
#

when i run the command it works fine

#

when my friends runs it

#

it gives error

#

it only works for me and my alt

#

nothing else

slate swan
#

Then this is weird since I'd say you don't respond in 3 seconds ducky_yellow

#

for sure sqlite3 is blocking so I'd consider using asqlite

fiery girder
#

but how is it working when i or my alt do it not when my friend do it

slate swan
#

No idea

fiery girder
#

you can check the code

fiery girder
slate swan
#

I did and thats why I don't have idea

fiery girder
#

pip install discord.py run this in the terminal @slate swan

slate swan
#

and what did it output after installing?

fiery girder
#

try
pip install discord.py --update

slate swan
fiery girder
slate swan
#

do you by any chance have few python versions installed?

fiery girder
#

what IDE u use?

slate swan
#

like lets say 3.11 with 3.10

#

do you have more than 1 python version installed?

fiery girder
#

in the botton there is a panel in there there should be one thing called python beside that should be a version tell that

fiery girder
#

oh 3.12

slate swan
#

!dashm

unkempt canyonBOT
#
Install packages with `python -m pip`

When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.

Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.

Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.

slate swan
#

or be specific

fiery girder
#

yea i guess

slate swan
#

uninstall it first tho

#

this should work yeah

#

and does it still say ModuleNotFound?

#

how do you run python file

#

i mean how do you run it

final iron
#

Could you show the interpreter you’re using?

slate swan
#

show the command it runs for you

hushed galleon
#

judging from these screenshots, vscode is running your virtual environment but discord.py was installed to your microsoft store python instead

#

normally opening the terminal in vscode will automatically activate the virtual environment, but since you're using a separate terminal, you have to activate it yourself before you're able to install packages to the virtual environment: ps1 PS C:\> cd C:\path\to\my_project PS C:\path\to\my_project> Set-ExecutionPolicy Unrestricted PS C:\path\to\my_project> .\.venv\Scripts\activate (.venv) PS C:\path\to\my_project> pip install ...

#

(if you no longer see the PS prefix you've probably switched from the powershell terminal to command prompt, in which case you don't need Set-ExecutionPolicy)

plain ravine
final iron
plain ravine
final iron
plain ravine
#
guild = 0 # The guild ID

@tree.command(name = "join", description = "Joins the selected Military.", guild=discord.Object(id=guild))
#

also during the on_ready, the tree.sync also syncs it with the guild id

final iron
plain ravine
#

id assume so, if im wanting it to work for multiple servers

slate swan
#

if you want it to work for every server you don't
have to specify the guild in commands and syncing

plain ravine
#

oh

#

ill try it out, cheers

plain ravine
compact ruin
#

Quick question i am using buttons inside a cog. How do i run checks to only allow the button to work if the person who pressed it is the same as the person who used the command?

slate swan
#

and sync after it

slate swan
plain ravine
#

in the on_ready?

slate swan
# plain ravine in the on_ready?

Usually it's recommended to implement custom
command that sync but if you want to really do
that automatically then consider using setup_hook

Downsides can be ratelimits so if you want to
create a command then consider looking at this

compact ruin
slate swan
compact ruin
shrewd apex
#

just like how u would add default emojis

compact ruin
shrewd apex
#

!d discord.ui.Button.emoji u set for this?

unkempt canyonBOT
shrewd apex
#

also u sure emoji was valid?

#

can u give an example code of how u set it

compact ruin
#

@shrewd apex Thanks i got it

final iron
#

you’re going to need to give a lot more information than that if you want a partner

compact ruin
#

Does anyone know why when i click a button to edit my embed which has new buttons it auto interacts and fails before i can actually use the new buttons

clever heart
#

Hi everyone ! I’m 25M, just started learning python last year, currently working on an IT automation course. I’ve been working alone and think I could benefit from some collaboration now. If anyone is willing to mentor me or work on projects together let me know. My goal is to treat this like I’m a junior engineer and do similar tasks/work flows

compact ruin
final iron
compact ruin
final iron
#

Yes…

compact ruin
#

Oh....

#

Lol alr one sec

#

Apologies took me awhile never used the pastebin for python lol

#

The issue i have is when it edits the embed to the 2nd one

#

it starts an interaction right away which fails

#

after that it works fine

trail maple
#

any good libraries to use for components in my bot?

slate swan
#

@trail maple how did u learn py?

final iron
vapid parcel
#

'maximum number of slash commands exceeded 100 globally'?

#

You can only have 100 slash commands??

final iron
vapid parcel
#

But like, ive seen bots with way more?

final iron
#

You can have more subcommands

vapid parcel
#

yeah

#

was just informed

#

Time to make a lot of sub commands GoofySkull

vital axle
#

Im new to decorators and decided to become familiar with that. Im trying to code a discord bot with interactions.py.

def require_login(func):
    async def wrapper(ctx: SlashContext, *args, **kwargs):
        # print(args, kwargs)
        user_account = await DatabaseWrapper.retrieve_account(ctx.author.id)
        if user_account is None:
            await ctx.send("You need to login first")
        else:
            await func(ctx, account, *args, **kwargs)
    return wrapper

@slash_command(name="set_profile_picture", description="Set your profile picture")
@slash_option(name="picture", description="Picture you want to set as profile picture", required=True,
              opt_type=OptionType.ATTACHMENT)
@require_login
async def my_command(ctx: SlashContext, account, picture: Attachment):
    await ctx.defer()
    picture_url = picture.url
    await ctx.send(picture_url)

I get this error
TypeError: my_command() missing 1 required positional argument: 'picture'
when trying the command.

pale zenith
#

I've never used interactions.py but I bet it's similar to how you create slash commands in discord.py, read their docs. There must be a way to define checks for a command, rather than doing it through a normal decorator (well, it'd still be a decorator, but done in the discord.py way)

#

unfortunately, normal decorators and discord.py do not mix well

#

alternatively, you can use the @functools.wraps(func) function above wrapper to fix this (make it inherit the annotations)

vital axle
#

but I do pass all args and kwargs i get from decorators over it

pale zenith
vital axle
#

ohh makes sense

green quest
#

WHy wont it respond to my command

#

import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.messages = True # Add more intents as needed

bot = commands.Bot(command_prefix='!', intents=intents)

@bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')

@bot.event
async def on_message(message):
if message.author.bot:
return # Ignore messages from other bots

if 'music' in message.content.lower():
    channel = message.author.voice.channel
    voice_channel = await channel.connect()

    voice_channel.play(discord.FFmpegPCMAudio('https://commondatastorage.googleapis.com/codeskulptor-demos/DDR_assets/Kangaroo_MusiQue_-_The_Neverwritten_Role_Playing_Game.mp3'))

    while voice_channel.is_playing():
        await discord.ext.tasks.sleep(1)

    await voice_channel.disconnect()

await bot.process_commands(message)

bot.run('')

final iron
green quest
final iron
unkempt canyonBOT
#

Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:

• The message was sent by the client

• The message was sent in direct messages

• The message mentions the client

This applies to the following events...

coral mirage
#

I keep getting error 429

subtle solar
latent jay
#

@app_commands.choices() can I check which was chosen by using the value provided?

gray mantle
#

can someone tell me why my discord bot not registering commands and not showing debug errors aswell -_- im irritated bruh

shrewd fjord
#

Slash command or prefix?

#

If slash command then make sure you have invited your bot with applications.command scope enabled and synced commands
If prefix command, make sure you dont have a on_message with @bot.event deco

gray mantle
gray mantle
# shrewd fjord Provide code
import os
from discord.ext import commands
from discord import Activity, ActivityType
import traceback
import discord
# Define all intents
intents = discord.Intents.default()
intents.message_content = True
cogs_to_load = [
    'cogs.general',
    'cogs.antinuke',
    'cogs.autoresponders',
    'cogs.errorhandler',
    'cogs.fun',
    'cogs.moderation',
    'cogs.owner',
    'cogs.help.cog',
    'cogs.music',
    'cogs.pythonshell'
]

# Create an instance of the bot with intents
bot = commands.Bot(command_prefix=".", intents=intents)
bot.remove_command('help')

async def load_cogs():
    for cog in cogs_to_load:
        try:
            bot.load_extension(cog)
            print(f"Loaded extension: {cog}")
        except Exception as e:
            print(f"Failed to load extension {cog}: {e}")

@bot.event
async def on_ready():
    print(f"Logged in as {bot.user.name} ({bot.user.id})")
    print("Bot is ready!")
    activity = Activity(type=ActivityType.listening, name=".help")
    await bot.change_presence(activity=activity)
    await load_cogs()

# CommandNotFound error handling
@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandNotFound):
        return  # Ignore unknown command errors
    traceback.print_exception(type(error), error, error.__traceback__)
    raise error

# Run the bot with your bot token
bot.run("token")
#

pls tell me how to fix

fiery girder
#

you dont even have commads than how will it register

#

oh cogs

gray mantle
fiery girder
#
await bot.load_cog(cog)```
#

you have it wrong

gray mantle
fiery girder
#

no

#

wait a sec

#

in setup_hook

#
async def setup_hook(self):
        self.add_view(Invite())
        
        print(f"Loaded Views For {self.user}")
        
        await self.add_cog(setup.Setup(self))
        await self.add_cog(admin_commands.AdminCommands(self))
        await self.add_cog(tickets.Tickets(self))
        await self.add_cog(ban.Ban(self))
        await self.add_cog(warn.Warn(self))
        await self.add_cog(usercommands.UserCommands(self))
        await self.add_cog(embed.EmbedBuilder(self))
        await self.add_cog(hangman.Hangman(self))
        
        print(f"Loaded Cogs For {self.user}")
        await self.tree.sync()
        print(f"Synced slash commands for {self.user}.")
gray mantle
#

setup_hook ?

fiery girder
#

yes

gray mantle
#

should i add this in main file ?

fiery girder
#

yes

gray mantle
#

hm wait

fiery girder
#

its a bot.event i think

#

i have it on my class so i dont need to add @bot.event

fiery girder
#

cogs need to be a Class

#

!d discord.ext.commands.Cog

unkempt canyonBOT
#

class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.

A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html#ext-commands-cogs) page.

When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CogMeta) are equally valid here.
vale wing
#

💀

fiery girder
vale wing
#

You don't need to import cogs, stop misleading

#

Strings are extensions

gray mantle
vale wing
#

And are loaded via load_extension

fiery girder
vale wing
#

Cogs are added in setup() function in extension

vale wing
vale wing
gray mantle
#

@vale wingcan u fix my issue pls?

vale wing
fiery girder
#
from handlers import setup
from commands import admin_commands, tickets, ban, warn, usercommands, embed
from handlers.views import *
from games import hangman
``` bruh moment
gray mantle
gray mantle
fiery girder
#

bruh

#

how

vale wing
fiery girder
#

this is like my 4th bot

#

and i am knowing this now

vale wing
gray mantle
gray mantle
#

but didnt respondiong to any cmds

desert kiln
#

Cogs is a way to have bot command sections, on seperate files, and such, they need to be in a class, and loaded on the main bot.py file, and they are loaded on the bot setup hook.

vale wing
#

@gray mantle first of all, do not ignore command not found errors

#

Either respond that such command doesn't exist or log

gray mantle
desert kiln
vale wing
#

Second, please show one of your extensions (a small one so I can see what I need)

gray mantle
vale wing
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

gray mantle
#

@vale wing `

fiery girder
fiery girder
#

well

desert kiln
desert kiln
fiery girder
desert kiln
vale wing
vale wing
naive briar
fiery girder
gray mantle
desert kiln
naive briar
#

Who would expect that you need to do things differently when changing to a different library

desert kiln
#

Do not, use replit.

gray mantle
#

@vale wingbro are u on replit ? i can share my whole srccode with u there

naive briar
gray mantle
vale wing
gray mantle
desert kiln
vale wing
#

I also remember some libs had recursive load_extensions

fiery girder
vale wing
fiery girder
fiery girder
#

that you need to await it

vale wing
#

Ok not in dpy

fiery girder
#

not the s

vale wing
#

!d disnake.ext.commands.Bot.load_extensions

unkempt canyonBOT
vale wing
#

Disnake my beloved ☺️

desert kiln
vale wing
#

Ok now to @gray mantle issue

gray mantle
fiery girder
#

!d discord.ext.commands.Bot.load_extension

unkempt canyonBOT
#

await load_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.

Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine).
vale wing
#

Comment out your error handler

fiery girder
#

this function is a corountine

gray mantle
vale wing
#

@fiery girder you're next on queue wait please ☺️

desert kiln
vale wing
gray mantle
gray mantle
desert kiln
fiery girder
#

ok anyways

vale wing
#

Damn typing code on phone with one eye closed is inconvenient af

desert kiln
#

I'm losing my brain cells

desert kiln
gray mantle
desert kiln
fiery girder
desert kiln
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

fiery girder
#
cogs = [
    'handlers.setup',
    'commands.ban',
    'commands.embed',
    'commands.warn',
    'commands.tickets',
    'commands.admin_commands',
    'commands.usercommands',
    'games.hangman',
    'games.tictactoe',
]



class Bot(Bot):
    def __init__(self):
        super().__init__(intents=Intents.all(), help_command=None, command_prefix="!")
        self.testing_guild = discord.Object(id=1169236151467511822)        

    async def setup_hook(self):
        self.add_view(Invite())
        print(f"Loaded Views For {self.user}")
        
        for cog in cogs:
            await self.load_extension(cog)
            
        print(f"Loaded Cogs For {self.user}")
        await self.tree.sync()
        print(f"Synced slash commands for {self.user}.")

    async def on_ready(self):
        activity = discord.Game(name="/help | Made By FedxD", type=3)
        await self.change_presence(status=discord.Status.online, activity=activity)

        print(f"Logged in as {self.user}.")

    async def on_command_error(self, ctx, error):````
desert kiln
vale wing
#
from pathlib import Path

class MyBot(commands.Bot):
    async def setup_hook(self):
        for p in Path("./ext").glob("*.py"):
            await self.load_extension(p.as_posix()[:-3].replace("/", "."))

bot = MyBot(...)

@fiery girder @gray mantle solution to your both problems actually. Just make sure to put your extensions into ext directory 😀

#

And make sure your extensions have

async def setup(bot):
    await bot.add_cog(Cog(bot))

At the end

fiery girder
#

def setup(bot: Bot): bot.add_cog(Setup(bot))

gray mantle
#

kk let me try

fiery girder
#

in handlers.setup

vale wing
#

In dpy

gray mantle
vale wing
#

One of reasons I hate dpy real hard 😡

#

Society if everyone used disnake

fiery girder
#

cog it running

#

the async was the problem

vale wing
vale wing
naive briar
#

I'm already used to it

vale wing
#

👄👁️👄

vale wing
#

@gray mantle was your problem solved

vapid parcel
#

How to do double sub?

naive briar
unkempt canyonBOT
#

class discord.app_commands.Group(*, name=..., description=..., parent=None, guild_ids=None, guild_only=..., nsfw=..., auto_locale_strings=True, default_permissions=..., extras=...)```
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
```...
gray mantle
#

@vale wingbro here it comes this error

vapid parcel
#

you can also load cogs a different way if you wanted.

vale wing
#

You sure BlackWolfAi inherits from Cog

#

Error is not that hard to read

gray mantle
vapid parcel
naive briar
#

Some just are too afraid to

vapid parcel
#

you kinda just showed your whole token.

vale wing
gray mantle
naive briar
gray mantle
vapid parcel
#

Nextcord isnt good..

vale wing
#

Uninstall it

vapid parcel
#

best out of all wrappers is like pycord maybe

vale wing
#

No it didnaek 😡😡

#

Disnaek best lib!1!1!1!

vapid parcel
vale wing
#

Rating of discord.py and forks

1: disnake
∞: nextcord
 + 1: pycord
∞^∞: discord.py
vapid parcel
#

disnake is poop

fiery girder
#

is it good to sync all app command to a single guild first for development than syncing it globally?

naive briar
#

I'd just make a completely different bot for testing

fiery girder
#

but doesnt it take time to sync app commands in discord i heard

vale wing
#

That's exactly what we have in Bobux except we have like 10 different bots

naive briar
fiery cairn
#

Any idea how I can fix this error? ```

Traceback (most recent call last):
File "D:\PROJECTS\james-util-bot\bot.py", line 2, in <module>
from discord import app_commands
File "C:\Users\rscdo\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands_init_.py", line 12, in <module>
from .commands import *
File "C:\Users\rscdo\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 51, in <module>
from ..enums import AppCommandOptionType, AppCommandType, ChannelType, Locale
ImportError: cannot import name 'AppCommandOptionType' from 'discord.enums' (C:\Users\rscdo\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\enums.py)```

naive briar
#

Do you have multiple Discord wrappers installed?

fiery cairn
#

Possibly

#

How do I check / uninstall any that is not discord.py?

naive briar
#

Use pip freeze to see your installed packages and remove the unused Discord libs

fiery cairn
#

oK

gray mantle
#

thanks alot bro u fixed my issue @vale wing

vapid parcel
#

I was abt to say

#

I didnt do anything lol

#

I only said nextcord is bad lol

fiery cairn
#

I don't seem to have any other discord packages...

#

discord==2.3.2
discord.py==2.3.2

naive briar
#

Try uninstalling discord

fiery cairn
#

nvm I got pycord

vale wing
naive briar
fiery cairn
vapid parcel
#

How to get sub commands in a help command?

pale zenith
#

!d discord.ext.commands.HelpCommand.send_group_help

unkempt canyonBOT
#

await send_group_help(group, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Handles the implementation of the group page in the help command. This function is called when the help command is called with a group as the argument.

It should be noted that this method does not return anything – rather the actual message sending should be done inside this method. Well behaved subclasses should use [`get_destination()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HelpCommand.get_destination) to know where to send, as this is a customisation point for other users.

You can override this method to customise the behaviour.
fiery girder
naive briar
fiery girder
#

huh?

fiery girder
#

so how is this making it not work

naive briar
fiery girder
#

how

#

i only have one on_message

#

oh

naive briar
#

!e

class A:
    def b(self):
        print(1)
    def b(self):
        print(2)

A().b()
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.12 eval job has completed with return code 0.

2
fiery girder
#

i got it

naive briar
#

Sign

fiery girder
#

thanks

old vine
#

how to make a command that would work like this:

if subject_code == "0417" and ranses == "w" and paper_number == "2" or "3" and ranyear == "2019":```

i want it to proceed only if all the conditions are accepted
fiery girder
#

!d discord.app_commands.check

unkempt canyonBOT
#

@discord.app_commands.check(predicate)```
A decorator that adds a check to an application command.

These checks should be predicates that take in a single parameter taking a [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure) exception is raised and sent to the appropriate error handlers.

These checks can be either a coroutine or not.

Examples

Creating a basic check to see if the command invoker is you...
fiery girder
#

for appcommand

#

!d discord.ext.commands.check

unkempt canyonBOT
#

@discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command) or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command.checks).

These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure) exception is raised and sent to the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error) event.

If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error).
fiery girder
#

for prefix/hybrid command

fiery girder
gray mantle
#

@cyan pumice

#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

gray mantle
#

!paste

stark nexus
#

How suppose i fix this?

@client.hybrid_command(description="Check the status of Minecraft server")
async def minecraft_server(interaction : discord.Interaction, server_ip : str):
    server = JavaServer.lookup(server_ip)
    try:
        status = server.status()
    except:
        status = "Not found"
    try:
        latency = server.ping()
    except:
        latency = "Not found"
    try:
        query = server.query()
        query_name = query.players.names
    except:
        query_name = "Not found"
    
    
    embed = discord.Embed(title=f"Server name : {server_ip}", description = f"Status : \n•Online players : {status.players.online}\nLatency : {status.latency}\nServer : \n•Latency : {latency}\nPlayers : \n{', '.join(query_name)}", color = 0xfc9803)
    embed.set_thumbnail(url="https://cdn.icon-icons.com/icons2/2699/PNG/512/minecraft_logo_icon_168974.png")
    
    await interaction.response.send_message(embed=embed)```

attributeerror: 'context' object has no attribute
golden portal
#

hybrid gets a Context object, not interaction, just rename your interaction to ctx and use ctx.send instead to send messages

stark nexus
#

K

golden portal
#

welcome

stark nexus
# golden portal welcome

I edited to this

@client.hybrid_command(description="Check the status of Minecraft server")
async def minecraft_server(ctx, server_ip : str):
    server = JavaServer.lookup(server_ip)
    try:
        status = server.status()
    except:
        status = "Not found"
    try:
        latency = server.ping()
    except:
        latency = "Not found"
    try:
        query = server.query()
        query_name = query.players.names
    except:
        query_name = "Not found"
    
    
    embed = discord.Embed(title=f"Server name : {server_ip}", description = f"Status : \n•Online players : {status.players.online}\nLatency : {status.latency}\nServer : \n•Latency : {latency}\nPlayers : \n{', '.join(query_name)}", color = 0xfc9803)
    embed.set_thumbnail(url="https://cdn.icon-icons.com/icons2/2699/PNG/512/minecraft_logo_icon_168974.png")
    
    await ctx.send(embed=embed)```
#

Unknown interaction error

#

(error code : 10062)

golden portal
#

you should start sending the full error because it's quite vague

#

an interaction require you to respond within 3 seconds, more than that you get an unknown interaction if you try to send a message, its possible that your lookup/ping method there is more than 3 seconds, so you can use await ctx.defer() before you do the lookup so you have more time to respond

stark nexus
#

*sry I can't copy them so i only can send screenshot

golden portal
#

i see, yea i guessed it correctly, you would have to defer first so you can respond longer than 3 seconds

golden portal
#

await ctx.defer()

stark nexus
golden portal
#

no, just use ctx.send

stark nexus
#

K

slate swan
#

im getting some import errors, how do i fix?

sick birch
#

depends on the import error

slate swan
#

this one

#

might be software related

#

it also shows me this when deleted so there could be more

#

and everyones favorite

#

undefined variables

#

ping with answers if anyones got em

#

ty

#

oh btw everything was coded in replit and it didn't work and nothing showed up as an error there so when i moved it to vsc to try and debug it more this started happening.

shrewd apex
#
  • u have discord.py and nextcord for some reason which is causing some name space conflicts
  • as for undefined variables its as python says ctx dosent exist
slate swan
shrewd apex
slate swan
#

nuts

#

well how about the ctx?

#

Uninstall the forks and nextcord first

#

and then add a ctx param

#

gotcha

#

so im going to have to rewrite most of my code aint i?

slate swan
#

so its not uninstalling

#

I keep getting 'WARNING: Skipping nextcord as it is not installed.'

#

even tho it keeps telling me to uninstall discord

final iron
slate swan
#

I was going for both, but i didn't know they were incompadible

#

now i think im too far in

slate swan
#

why would you use 2 libraries designed to do the same thing

final iron
#

They both cover the entirety of the API. There’s no reason to use both

slate swan
#

im an idiot for this but, i didn't know how to make a bot to do what i wanted. i looked up multiple yt tutorials, found some that used discord and others nextcord.

#

lesson learned

#

they get out of date quickly too

vale wing
#

And hikari but we don't talk about that here

vale wing
slate swan
#

Now i gotta reorg and recode several functions, break out the caffine this is gonna be a long one

final iron
#

Their features and such

slate swan
#

witch is better?

final iron
#

It’s mainly preference for the features

slate swan
#

nextcord FIRE

final iron
slate swan
final iron
#

Tutorials shouldn’t be a factor in your choice

slate swan
final iron
#

I’d probably be looking at:
Stability
Implementations of items like components and application commands
Documentation
Ease of use

#

Stability: Both Nextcord and discord.py are very stable and update quickly
Components/Application Commands: They both have all of discords available items, but have differing implementations
Documentation: Very similar documentation style
Ease of use: Very similar structure with a few large style differences

umbral spear
#

Could someone please lend a hand by testing the commands of my Discord bot in the server? Feel free to send me a direct message for the invitation. Thank you

winged linden
#

Does anyone know any good APIs for gathering cryptocurrency data for usage within a discord bot?

final iron
#

People aren’t really going to join your server and do allat. You’ll have better luck creating an alt and testing with it

winged linden
#

I want to be able to convert different crypto amounts to usd and different usd amounts to crypto

final iron
winged linden
#

I have never made a google search using the APIs before

old vine
#

ok so, i am trying to use requests and get if the website exists or not... if the site doesn't exist.. it should send the message Paper not found with ephemeral=True but if the site exists, it should send a embed with ephemeral=False

sick birch
old vine
sick birch
#

can you show us your code?

old vine
#

give me a sec

final iron
#

There’s definitely some API you can find online though

#

Shouldn’t have to resort to using Google

old vine
sick birch
old vine
sick birch
#

Not sure. Never used it so I can't tell

drifting arrow
#

What's a good or recommended way to sanitize a users input or message?

sick birch
drifting arrow
#

No.

#

it's for the on_message function.

#

I want to ensure nobody is sending anything that can mess with my bot

drifting arrow
#

So when someone sends a message in chat.. the bot reads it and sends a message back

#

if you're asking for "How exactly they can fuck with the bot" - NFI that's why im here.

hushed galleon
drifting arrow
#

I don't think so?
The user messages the bot, and the bot then takes that message and sends it to a channel.

hushed galleon
#

and do you think your code does something poorly while manipulating the user's string?

drifting arrow
drifting arrow
final iron
#

Safari says it can’t connect

final iron
#

!d nextcord.InteractionResponse.defer

unkempt canyonBOT
#

await defer(*, ephemeral=False, with_message=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.
drifting arrow
#

I love a good deferral

hushed galleon
final iron
final iron
drifting arrow
drifting arrow
old vine
# final iron So when the embed sends it’s not ephemeral when it should be?

nono.. so i defered the message cuz i was using requests and i wanted it to ephemeral the message "We are sorry, but the paper you are looking for is not available. Perhaps you can try a new search." becuz the page doesn't exist and it returned 404. if it returns 200, then it should send the embed without ephemeral

tiny coyote
#

im having alot of issues importing discord.

final iron
tiny coyote
#
No suitable Python runtime found
Pass --list (-0) to see all detected environments on your machine
or set environment variable PYLAUNCHER_ALLOW_INSTALL to use winget
or open the Microsoft Store to the requested version.
#

What do i do

drifting arrow
strong scarab
#
import discord

class MyClient(discord.Client):
    async def on_ready(self):
        print("Logged on as {0}!".format(self.user))
    async def on_message(self, message):
        print("Message from {0.author}: {0.content}".format(message))


client = MyClient()
client.run('my bot token')
  File "c:\Users\Usuário\Documents\discord.py\meu_bot.py", line 10, in <module>
    client = MyClient()
             ^^^^^^^^^^
TypeError: Client.__init__() missing 1 required keyword-only argument: 'intents'

why its happening this

im beginner

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.

tiny coyote
final iron
#

First install a supported version, 3.9-3.12

#

Then we’ll work from there

drifting arrow
#

always the latest version.

tiny coyote
old vine
tiny coyote
#
-V:3.12 *        Python 3.12 (64-bit)
final iron
#

So it’s installing into your 3.6 environment, which it says doesn’t exist

hushed galleon
strong scarab
#

i got another problem aa

tiny coyote
final iron
#

You need to specify pip as a module or python thinks it’s a file

final iron
#

Miss-ping

tiny coyote
tiny coyote
final iron
#

It installed properly?

#

Multidict should be throwing an error

tiny coyote
#

still installing

final iron
#

It’ll error

tiny coyote
#
   check.warn(importable)
      copying multidict\__init__.pyi -> build\lib.win-amd64-cpython-312\multidict
      copying multidict\py.typed -> build\lib.win-amd64-cpython-312\multidict
      running build_ext
      building 'multidict._multidict' extension
      error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for multidict
Failed to build multidict
ERROR: Could not build wheels for multidict, which is required to install pyproject.toml-based projects
hushed galleon
final iron
#

Multidict is missing wheels for 3.12, so you can fix it two ways:
Install using umbras wheels: pip install -U --force-reinstall discord.py --extra-index-url https://abstractumbra.github.io/pip/

Downgrade to Python 3.11.7

#

Two options

hushed galleon
#

or if you don't trust their index but still want 3.12, you can follow the link in that error message to install the C++ build tools yourself

final iron
#

Danny has also recommended using the wheels as a fix, so he trusts them

tiny coyote
final iron
#

Prefix it with what you used to install discord.py before

final iron
tiny coyote
#

finished

#

do i install discord now

final iron
#

That did install discord

tiny coyote
#

alr installed got it thanks btw

#

how do i get sqlite now 😅

final iron
#

sqlite3 is installed by default, but you’ll want to use an asynchronous version

#

asqlite can be installed from GitHub

tiny coyote
#

github huh

#

alr

unkempt canyonBOT
paper cipher
#

context.py

from discord import Color, Embed, Message
from discord.ext import commands

import config

class Context(commands.Context):
    async def neutral(
        self, content: str, color: int = config.Color.neutral, emoji: str = "", **kwargs
    ) -> Message:
        return await self.send(
            embed=Embed(
                color=color,
                description=f"{emoji} {self.author.mention}: {content}",
            ),
            **kwargs,
        )

information.py

from discord import Embed, Color
from discord.ext.commands import Cog, Command, Group, command

from time import time

from helpers.rogue import Rogue
from helpers.utilities.human_timedelta import human_timedelta
from helpers.variables import colors
from helpers.managers.context import Context

import config

class Information(Cog):
    def __init__(self, bot : Rogue):
        self.bot: Rogue = bot 

@command(
        name="uptime"
    )
    async def uptime(self, ctx: Context):
        """
        View the bot's uptime
        """
        
        return await ctx.neutral(
            f"**{self.bot.user.display_name}** has been up for: **{human_timedelta(self.bot.uptime, suffix=True)}**",
            emoji=":alarm_clock:"
        )

config.py

class Color:
    neutral = 0x5f9ea0 # cadetblue
    approve = 0x9acd32 # yellowgreen
    deny = 0xdc4747 # failurered
    warn = 0xffa500 # orange
    
class Emoji:
    approve = "✅"
    deny = "❌"
    warn = "⚠"

when i run my bot, and run the uptime command, why do i get this error?:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'neutral'

my file tree (rogue.py stores my bot class, main.py runs it):

fiery girder
shrewd apex
#
class MyBot(commands.Bot):
    async def get_context(self, message: discord.Message, *, cls=CustomContextHere):
        return await super().get_context(message, cls=cls)
midnight oracle
#

I organize my commands in cogs inside of a "cogs" folder and then loading them automatically using the code bellow but, if I wanted to separate my cogs in folders inside of the cogs folder. Would this way I'm using go through each folder inside of the cogs folder and load each .py file inside correctly?

@bot.event 
async def on_ready():
    for cog_file in settings.COGS_DIR.glob("*.py"):
        if cog_file.name != "__init__.py":
            await bot.load_extension(f"cogs.{cog_file.name[:-3]}")
paper cipher
shrewd apex
finite salmon
#

You haven't separated the values in the list with a comma

#

app_commands.Choice(name="⭐️", value="one")
Is one element and app_commands.Choice(name="⭐️⭐️", value="two") is another element. Since they're in an array each element here needs to be separated by a comma

true vector
#

I just ran into this, how would I go about editing this ?

pale zenith
true vector
#

thanks

slate swan
#

Hi, it's been a few days since python reads me anymore the fivem library, can anyone tell me how to do it? I redid the "pip install FiveM" but it doesn't work anymore

shrewd apex
#

!pypi fivem

unkempt canyonBOT
shrewd apex
#

what exactly dosent work and how?

slate swan
#

It's always worked, but not anymore

shrewd apex
#

in terminal run

py -0
slate swan
shrewd apex
#

thats weird does the bot run?

#

also did ur pip install command work?

slate swan
#

PS C:\Users\stefa\Desktop\BotPython\Bot\botiii> pip install fivem
Requirement already satisfied: fivem in c:\users\stefa\appdata\local\programs\python\python311\lib\site-packages (1.1)
Requirement already satisfied: requests in c:\users\stefa\appdata\local\programs\python\python311\lib\site-packages (from fivem) (2.31.0)
Requirement already satisfied: charset-normalizer<4,>=2 in c:\users\stefa\appdata\local\programs\python\python311\lib\site-packages (from requests->fivem) (3.2.0)
Requirement already satisfied: idna<4,>=2.5 in c:\users\stefa\appdata\local\programs\python\python311\lib\site-packages (from requests->fivem) (3.4)
Requirement already satisfied: urllib3<3,>=1.21.1 in c:\users\stefa\appdata\local\programs\python\python311\lib\site-packages (from requests->fivem) (2.0.4)
Requirement already satisfied: certifi>=2017.4.17 in c:\users\stefa\appdata\local\programs\python\python311\lib\site-packages (from requests->fivem) (2023.7.22)

brazen geyser
#

hey guys, is there any way to make error handler for all commands in Group?

slate swan
#

no

shrewd apex
#

whats the traceback u get when running it

slate swan
slate swan
# shrewd apex whats the traceback u get when running it

PS C:\Users\stefa\Desktop\BotPython\Bot\botiii> & C:/Users/stefa/AppData/Local/Programs/Python/Python311/python.exe c:/Users/stefa/Desktop/BotPython/Bot/botiii/HADES[RP].py
Traceback (most recent call last):
File "c:\Users\stefa\Desktop\BotPython\Bot\botiii\HADES[RP].py", line 26, in <module>
from fivem import FiveM
ModuleNotFoundError: No module named 'fivem'
PS C:\Users\stefa\Desktop\BotPython\Bot\botiii>

slate swan
#

What do I need to install?

final iron
#

Whatever you’re trying to import

vale wing
#

!venv

unkempt canyonBOT
#
Virtual environments

Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.

To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)

Then, to activate the new virtual environment:

Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate

Packages can then be installed to the virtual environment using pip, as normal.

For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.

Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.

Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
vale wing
#

Although the path of packages and py executable seems the same it's likely cause of path issues

hushed galleon
#

the hours= parameter in your loop is set to 23, did you mean to write 24?

polar slate
#

Is there someone that is good with / command and using discord.py that could guide me on how to make my bot and help me if I struggle on things here pls ?

hushed galleon
#

well if they trigger at the same time asyncio event loop will simply run both tasks concurrently

#

also if you happen to be using discord.py>=2.0, there's a time= parameter which lets you specify one or more datetime.time()s to run the loop on

hushed galleon
polar slate
#

And do you know how I could make simply a leaderboard command for my EXP system (it's made) but with buttons to change the pages of the leaderboard

#

I struggle with the buttons

hushed galleon
lament depotBOT
hushed galleon
polar slate
#

Ty

hushed galleon
#

well, if you start at 12AM and then sleep 23 hours, the next iteration is going to be at 11PM

polar slate
#

I will read that when i'll be rested a bit

desert kiln
#

good afternoon everybody

timber lotus
#

what does mod mail do?

#

is like a support ticket bot or something?

desert kiln
#

via, a private channel, Or something similar

timber lotus
#

oh i gotcha, so if im createing a bot for my server thats a probably a good feature to install eh? sounds easy

desert kiln
#

it can be a good project to work on too

timber lotus
#

it is. yea thats what im thinking. dont sound too difficult. i dont know anything about bots recieving dms but probably just sent it up so if anyone sends a dm to that bot it posts a message in the mod channel?

pale zenith
#

A good modmail feature is slightly harder than you think

timber lotus
desert kiln
#

and make the bot return a confirmation message, with a report ID, that can be used to refer To, as the reporter, Or admin etc

timber lotus
desert kiln
timber lotus
#

hahaha i overexaggerated slightly but you got my point haha

desert kiln
pale zenith
desert kiln
pale zenith
timber lotus
#

thanks bro. i have some other things i want to do first but i added it to my list. i just finished some giveaway commands and going to work on history comamnds.

desert kiln
pale zenith
#

yes, but it's more organized

desert kiln
#

true

timber lotus
# pale zenith like:

whatchat mean forum channel? i saw the mailbot and was curioous what it does. but definitely need some sort way to message the mods i assume, for my server

hushed galleon
# timber lotus what does mod mail do?

there's also the git repo you can check out, but at a glance their source code is quite complex
https://github.com/python-discord/modmail
their readme has a summary of what it does:

When a member sends a direct message to the bot, Modmail will create a channel or "thread" into a designated category. All further DM messages will automatically relay to that channel; any available staff can respond within the channel.

pale zenith
#

my modmail needs database stuff and everything (source code for context)
That's why I said modmail is slightly less easy than it may seem haha

timber lotus
#

i tried look at sir lancelot code and cant even figure that out hahah

hushed galleon
#

any codebase is hard to tackle all at once, but you can try focusing on one feature at a time when you're exploring their source

#

regardless you have a lot of ways to implement a modmail, so have fun with it

vale wing
slate swan
vale wing
#

Why

polar slate
#

We agree that to make a discord bot I dont need anything else than VS code, I don't need something like django or else ?

loud junco
#

@vale wing is this tutorial a bit too old
https://www.youtube.com/watch?v=4EIy0bw7s-s

Welcome to the updated discord.py series - the series where I teach you how to build a discord.py bot for your server! Below are some links to get you started.

Series requirements can be found here:
https://files.carberra.xyz/requirements/discord-bot-2020

You'll also need an IDE; I use Sublime Text in this series:
https://www.sublimetext.com/
...

▶ Play video
vale wing
polar slate
vale wing
#

To develop a discord bot in python you need python interpreter >=3.9 or smth I forgor what libs support

#

Vscode is merely a code editor

#

If you are skilled enough you can use notepad

#

And actually if you're skilled enough

#

Nvm I thought of something so epic matrix servers exploded

hushed galleon
vapid parcel
#

Anyone know a good spot to just see a lot of idea commands based on Presence Intent?

languid sequoia
#

Is it possible to edit things on my own account with a bot?

languid sequoia
#

Is it possible in general?

final iron
#

wdym in general

#

Messages can only be edited by their owners

drifting arrow
#

I forgot how much you can fit into a single embed description lol.
quite a lot it turns out.

timber lotus
# pale zenith like:

can you do that so the bot also posts a picture? without a url tho, like the user just drops and drags?

drifting arrow
timber lotus
drifting arrow
#

Using a discordbot, the only 2 ways I know of how to send an image a user has sent is to either temporarily download it and send it, or to grab the image URL and send it as part of an embed

#

there may be other better more ideal ways

timber lotus
#

ok let me clarify tho, my original question was about bot the modmail bot and the one guy let me know they can also create forum posts. well i want to adapt that for commands to create forum posts which wold be added to a database for some other reasons. so it wouldnt be through dm if that makes a difference, it would be though commands. can i add an image that way, the same way if i was just doing it?

drifting arrow
#

I've never worked with forum posts, most servers I operate within refuse to update to include forums, mostly coz their communities cannot be trusted..
So I dont know specifically how forums work, I would assume they work the same as any channel and you just need a channel ID and you can send to that specific channel.

#

As for the rest of what you said, it confused me so I didnt comment on it lol

timber lotus
#

lol..... i dont want to have to upload an image before posting, but i think you already answered my question. i just need to research the discord download thingy and see if that is what im talking about

timber lotus
timber lotus
#

you know when you doing commands and if an option is channel, it shows up with all the channels, how do you that with custom options? like if the option was sport, how do i get the pop window to show the different sport names instead of having to write it in?

final iron
#

If you want a text channel specifically you just annotate it with TextChannel

final breach
#

hi there i want to use choices in slash commands but the choises are in database how to make the bot get the choices and add them to the command

final breach
hardy geyser
#

how to define?

shrewd apex
#

define what?

hardy geyser
hardy geyser
# shrewd apex define what?

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'satureafk' is not defined

shrewd apex
#

make command with that name then

hardy geyser
#

def satureafkon(): right ?

shrewd apex
#

no

@bot.command()
async def satureafkon(ctx):
    ...
#

u should probably do through the documentation

hardy geyser
#

mm

shrewd apex
#

!d discord.ui.button

unkempt canyonBOT
#

@discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.

The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button) being pressed.

Note

Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button) manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
dawn lion
#

Nextcord good

golden portal
#

eh nextcord is a copy paste of discord.py when it comes for button/view implementation, without the newer discord.py's features within view and probably still have the view memory leak problem

naive briar
#

Is there any thing that nextcord does better than discord.py? pithink

pale zenith
#

In my humble opinion no, they're mostly the same lol

#

Only pet peeve for me is that a Cog.cog_(un)load method(s) can't be async in nextcord

#

Plus (afaik) nextcord doesn't have the new discord.ui.DynamicItem class (unsure)

nimble plume
#

while being rate limited. we get token ratelimit or ip ratelimit?

#

or its the same thing

shrewd apex
high apex
#
@t.command(name="balance", description="Check your current balance.")
async def balance(interaction, member: discord.Member = ):

how do i make the member argument optional?

slate swan
#

set default value to None

high apex
slate swan
#

this is only a typing error but if you wanna fix it you can annotate it as union of Member and None

high apex
#

ok

#

thanks

stray cliff
#

Assalamun Alaykum Warahmatullahi Wa Barakatuhu

I know that it probably is some stupid issue from my side but when i run my discord bot it just simply says that there is no module called discord.

This is what i have imported so far: discord.py, discord.ext and requests

Thanks in advance for any help 😀

west holly
#

what is the coding to avoid chat spam?

stray cliff
#
import discord.py
from discord.ext import commands
import requests
#

Is this what you mean?

west holly
stray cliff
#

Ohh nvm i thought you meant something else

west holly
#

!custom-cooldown

unkempt canyonBOT
#
Cooldowns in discord.py

Cooldowns can be used in discord.py to rate-limit. In this example, we're using it in an on_message.

from discord.ext import commands

message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)

@bot.event
async def on_message(message):
    bucket = message_cooldown.get_bucket(message)
    retry_after = bucket.update_rate_limit()
    if retry_after:
        await message.channel.send(f"Slow down! Try again in {retry_after} seconds.")
    else:
        await message.channel.send("Not ratelimited!")

from_cooldown takes the amount of update_rate_limit()s needed to trigger the cooldown, the time in which the cooldown is triggered, and a BucketType.

final iron
stray cliff
stray cliff
fiery girder
#

if i defer and interaction the time i answer the interaction do i do interaction.response.send_message or interaction.followup.send

final iron
final iron
fiery girder
final iron
#

Yes

fiery girder
#

ok thanks

stray cliff
crude flame
#

@ashen notch I can't talk 💀

#

I forgot I am not active in this server

#

Wrong channel

final iron
fiery girder
#

is it worth switching to python 3.12 for discord bot coding?

stray cliff
livid roost
#

everytime I try pip install discord.py it gives this error:

  ERROR: Failed building wheel for multidict
Failed to build multidict
ERROR: Could not build wheels for multidict, which is required to install pyproject.toml-based projects``` any fixes?
final iron
#

pip install -U --force-reinstall discord.py --extra-index-url https://abstractumbra.github.io/pip/

@livid roost @stray cliff

livid roost
#

thanks! worked

slate swan
fiery girder
slate swan
fiery girder
#

nah i prefer watching a vid on a features

#

any of you fimilar with Merriam-Webster dictionary api
i want to make a defind function but i dont know which list have the synonyms and its a huge json mess

final iron
fiery girder
#

yea i will

paper cipher
#

whenever i run the avatar command,

async def avatar(self, ctx: Context, *, member: Member | User = None): 
        member = member or ctx.author
           
        gif = member.avatar.with_format("gif") if member.avatar.is_animated() else "" 
        jpg = member.avatar.with_format("jpg")
        png = member.avatar.with_format("png")
        webp = member.avatar.with_format("webp")
        
        
        return await ctx.send(
            embed = Embed(
                title=f"{member.name}'s avatar",
                url=((gif if member.avatar.is_animated() else png) or member.default_avatar),
                description=f"[[jpg]]({jpg}) [[png]]({png}) [[webp]]({webp})" + ((f" [[gif]]({gif})") if member.avatar.is_animated() else "")
            ).set_image(url=(member.avatar or member.default_avatar))
        )```
and i dont supply a valid member from the server, it gives this error:
```discord.ext.commands.errors.BadUnionArgument: Could not convert "member" into Member or User.```
how can i handle this and return an error message with ctx.send()? i've tried some stuff but it always returns the same error
final iron
paper cipher
#

i thought for this one it would be better to make a specific error? since i want to make it say something like "could not find user or id" and not something general just for that error

final iron
#

!d discord.ext.commands.Command.error

unkempt canyonBOT
#

@error```
A decorator that registers a coroutine as a local error handler.

A local error handler is an [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error) event limited to a single command. However, the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error) is still invoked afterwards as the catch-all.

Changed in version 2.0: `coro` parameter is now positional-only.
paper cipher
#

ahh thanks

pale zenith
#

What you usually do is to have 2 views

pale zenith
ashen river
#

Can someone let me know that do we need intents to get our discord bot working or we can do without it as well

#

like the presence or guild one should not be used unless you are looking for welcome and leaving activity of a user or their status whether they are online or offline