#discord-bots

1 messages · Page 333 of 1

ashen river
#

i don't get the messsage_content one

final iron
#

It's self explanatory

final iron
ashen river
ashen river
# final iron Which slash command messages

2024-01-04 22:02:47 WARNING discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected.
2024-01-04 22:02:47 | WARNING | discord.ext.commands.bot | Privileged message content intent is missing, commands may not work as expected.

#

i see this on screen

final iron
#

That is a warning, yes

ashen river
final iron
#

Not unless you need it

ashen river
#

so that does not require it?

hushed galleon
# ashen river does this intent affect your slash command messages if it is disabled? Like my ...

you can see the various exceptions in the API docs:
https://discord.com/developers/docs/topics/gateway#message-content-intent

Apps without the intent will receive empty values in fields that contain user-inputted content with a few exceptions:

  • Content in messages that an app sends
  • Content in DMs with the app
  • Content in which the app is mentioned
  • Content of the message a message context menu command is used on
    in short, the message content intent only affects messages your bot sees from other users, so if your slash command takes an Attachment parameter it won't be affected by the intent
final iron
#

Slash command invocations are not messages

#

You won't need the messages content to invoke them

ashen river
#

i understand it now thanks guys

ashen river
#

Also one more thing my hosting server memory goes beyond its limit when i run my bot like it is 75/52 GB RAM and then bot crashes and i have to restart again

#

i've searched on internet and it is maybe called as memory leak

#

anyone can recommend any solution for this?

final iron
#

Do you mean MB?

final iron
#

Phrasing just confused me a bit

ashen river
ashen river
final iron
#

It’s pretty straightforward

final iron
# ashen river

Honestly I don’t know how to interpret this. I doubt you have 52GB of memory unless you’re paying hundreds, or even thousands of dollars a month

#

Could you show the entire screenshot

ashen river
final iron
#

Are you sure that’s the memory reading?

ashen river
final iron
#

Are you paying 0.405/hour?

ashen river
final iron
#

That’s almost $300 monthly

ashen river
#

yup

final iron
#

Why

thin vector
#

When you have money, you can do whatever you want

ashen river
#

the discord bot is not the main usage on it, its being used for some other stuff as well

final iron
#

Are you sure the bot is using up the 36GB of memory?

#

And it’s not another program?

ashen river
#

the bot keeps on increasing the usage memory i've also tested it on another cloud server

#

and it gradually increases it by 2 GB after each usage

final iron
#

Sounds like a memory leak

#

Do you know the part of the code that’s causing it?

#

If not, there’s some profilers you can use

ashen river
#

not yet thats what i'm trying to identify

final iron
ashen river
#

ok ill check it rn

final iron
#

Actually, it might be CPU calls only

#

I’m not sure if it will show memory utilisation

hushed galleon
ashen river
#

this can work?

final iron
#

Looks fine

#

Memray seems to be more extensive though

ashen river
#

alright

acoustic kernel
#

How can I run a command that deletes the message before it before responding?

tender bobcat
final iron
#

You want to delete the message invoking the command?

acoustic kernel
#

no I just want to delete the message before any command then the response is stull visible

#

im using / commands too

final iron
acoustic kernel
#

no heres what I want to do.

  1. RANDO test I want to delete
  2. Command/response

I want to delete 1. the rando text in the channel before the response

final iron
#

Oh

#

Which part are you asking for help with

acoustic kernel
#

how do I fetch the message then delete it

final iron
#

!d discord.TextChannel.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) that enables receiving the destination’s message history.

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) to do this.

Examples

Usage...
final iron
#

You’d want to have a limit of 2

#

On the second one you’ll call

#

!d discord.Message.delete

unkempt canyonBOT
#

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

Deletes the message.

Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages).

Changed in version 1.1: Added the new `delay` keyword-only parameter.
acoustic kernel
#

awesome thanks

languid sequoia
final iron
#

Or set_thumbnail

languid sequoia
#

Okay

silent flame
#

how to execute some code when the server logs in new participant?

latent jay
#

How could I create a certain amount of buttons without knowing beforehand?

latent jay
unkempt canyonBOT
#

discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).

This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) to be enabled.
silent flame
latent jay
final iron
#

Should be pretty straightforward

#

I have a system to do the same thing for modals

latent jay
#

can you show an example Im a bit slow

final iron
#

Honestly I can't be bothered to create a whole example right now

#

self._modals = [InformationModal(chunk) for chunk in chunked_inputs]

#

This is the relevant part for you

#

InformationModal is my discord.ui.Modal subclass

#

You would then loop through that list, in my case self._modals and use

#

!d discord.ui.View.add_item

unkempt canyonBOT
#

add_item(item)```
Adds an item to the view.

This function returns the class instance to allow for fluent-style chaining.
final iron
#

To add them to a view

languid sequoia
#

Does anybody have documentation for discord.py slash commands?

strong scarab
#

can someone explain WHY

latent jay
#

discord.py already support slash commands why use that library

final iron
latent jay
hushed galleon
final iron
latent jay
#

never seen it no

final iron
#

See what it is

latent jay
#

oh modals are the list things you can choose from?

sick birch
final iron
sick birch
#

this is a discord modal

latent jay
#

ah I see it

#

I want to create a class that'll accept a list and create buttons for each item with a value of it's appropriate item, can someone lead me in the right direction?

hushed galleon
latent jay
#

Could you give some sort of psuedocode?

#
class BtnInfo(discord.ui.View):
    def __init__(self, resp_list) -> None:
        super().__init__(timeout=None)

        for line in resp_list:
            self.add_item(label=line, custom_id=f'button_{line}')

Something like this?

hushed galleon
#

almost, you instantiate a Button class with the parameters you want and use add_item() with that

#

e.g. ```py
class MyButton(discord.ui.Button):
def init(self, my_value):
super().init(label=f"Here is {my_value}", ...)
self.my_value = my_value

async def callback(self, interaction):
    await interaction.response.send_message(f"You clicked on {self.my_value}!")

class BtnInfo(discord.ui.View):
def init(self, resp_list) -> None:
super().init(timeout=None)

    for line in resp_list:
        button = MyButton(line)
        self.add_item(button)```
#

technically you could also write button = discord.ui.Button(label=...), but it doesn't have any way to define a callback function to run when the user clicks it, hence why its helpful to define your own Button subclass

latent jay
#

what're the other values for the button besides label again?

final iron
#

Documentation is your friend

#

The docs also have a helpful search function if you can't remember the exact path

latent jay
#

yeah I just hope you guys have what Im asking memorized lol you guys are geniuses

final iron
#

It's a lot easier than you think

#

You'll eventually just intuitively learn discord.py's structure

#

Learning why something is how it is, is very helpful

latent jay
#

I've only memorized some of it

#

is there a limit for label characters?

hushed galleon
latent jay
#

thanks

final iron
#

@hushed galleon I'm currently building a table to showcase the different implementations of features across different libraries, what features do you think I should cover? Currently Im looking to do Views(Buttons, Selects, Modals), App Commands (Slash and Context), Documentation, Support community, coverage of the API, Voice Support and updates

drifting arrow
#

[Stands around ominously]

drifting arrow
final iron
#

those will take a bit

#

currently I'm just going to do discord, nextcord, pycord and disnake

drifting arrow
#

why is there so many versions?!

#

discordpy best imo

#

and not because I am biased or anything.

final iron
drifting arrow
#

Lets be real tho.

#

Discordpy best one.

final iron
#
forks = [
    "nextcord",  # fork of dpy
    "py-cord",  # fork of dpy
    "py-cord-dev",  # py-cord but updated on PyPi
    "interactions.py",  # another py bots library 
    "disnake",  # fork of dpy 
    "dislash",  # extension but then discontinued and replaced by "disnake"
    "dislash.py",  # extension but then discontinued and replaced by "disnake"
    "discord-py-slash-command",  # package pointing to "interactions.py"
    "discord.py-message-components",  # fork of dpy
    "enhanced-discord.py",  # discontinued fork of dpy
    "novus",  # fork of dpy
    "hata",   # another py bots library 
    "discord-interactions",  # official tool by discord to work with interactions
    "discord.py-self",  # self-bot lib
    "discord.py-self.embed",  # discontinued self-bot lib to send embeds
    "discord2",  # package that leads to "py-cord" but is not owned by them
    "python-discord",  # package pointing to a years old clone of dpy
    "discord_py_buttons",  # extension, was renamed twice and discontinued as "discord-ui"
    "discord_slash",  # extension, doesn't exist anymore(?)
    "discord.py",  # actually dpy
    "discord",  # official dpy package pointing to (a potential outdated version of) dpy
    "discord-ext-forms",  # discontinued extension to make a Modal
    "discord-ext-alternatives",  # discontinued extensions package by previous dpy regulars
    "dpy-appcommands",  # discontinued extension for app commands
    "discord-ext-slash",  # unmaintained(?) extension for slash commands
    "discord-buttons-plugin",  # discontinued extension for.. buttons
    "discum",  # self-bot lib
]
novel apexBOT
#

This is not a Modmail thread.

final iron
#

That's forks alone, there's also other libraries like hikari

drifting arrow
#

everything else is just an extract or alteration of the OG

final iron
#

They're mainly forks

final iron
#

If we're being real though, nextcord is really the only competitor

#

All the other ones are way less popular than the two

drifting arrow
#

alternative?

final iron
#

competitor can still be used

drifting arrow
#

Alternative sounds better.

final iron
#

its not exclusive to paid products

drifting arrow
#

D:

slate swan
#

can someone help me with a bot please 🙂

slate swan
#

ty

drifting arrow
#

So

#

what we all workin' on?

hushed galleon
hushed galleon
drifting arrow
#

60 lines, the best 60 there is

split onyx
#
Failed to load extension cogs.SlashCommands.SCInfo.
ExtensionFailed: Extension 'cogs.SlashCommands.SCInfo' raised an error: AttributeError: module 'discord.ext.commands' has no attribute 'tree'

Yes it worked in the main.py but became a problem in a cog.```
final iron
#

Yes it worked in the main.py
It either didn't, or you manually created it

split onyx
drifting arrow
#

but did it?

final iron
#

Legitimately impossible unless you modified the files

#

It does not exist

naive briar
#

What worked? discord.ext.commands.tree literally doesn't exist

split onyx
#

lmao it did

drifting arrow
#

I dont even know what scinfo is

final iron
split onyx
drifting arrow
#

recreate?

#

u mean u tried, got an error, deleted?

split onyx
#

I mean I deleted that main.py code and transfered it direcetly into a cog with the correct syntax changed

drifting arrow
#

Alright

split onyx
#

Got it...

final iron
#

Can we see your code?

split onyx
#
#!------Run These When Needed------
#? .venv\Scripts\activate



#!------Imports------#
import discord
from discord.ext import commands, tasks
import os
import asyncio
from itertools import cycle #For status
import random # For eightball
import json
#?LocalImports
from cogs.Utility import Utility


#!------Bot Prefix's------#

def get_server_prefix(bot, message):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)

    return prefixes[str(message.guild.id)]


#!------Essentials------#
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix=get_server_prefix, intents=intents)

bot.remove_command('help')  # This line removes the default help command

utility = Utility(bot)
prefix = utility.get_server_prefix

#!------Guild Specific Event------!#
    #?------Sets Default Prefix, Allows 4 Custom Prefix------?#



#!------Status------#
bot_status = cycle(["type '!help' for help", "You can make a custom prefix!", "I :heart: Biscuits!"]) #Available Statuses

@tasks.loop(seconds=10) #Changes Status Every x Seconds (Can use minutes and hours too) 
async def change_status():
    await bot.change_presence(activity=discord.Game(next(bot_status))) #Changes Status from bot_status

@bot.event
async def on_ready():
    await bot.tree.sync()  # Syncs Slash Commands
    print('------------------------------------------------------------')
    print('Logged in as', bot.user.name)
    print('------------------------------------------------------------')
    change_status.start()
    


@bot.tree.command(name="ping", description="Returns the bot's latency.")
async def ping(interaction: discord.Interaction):
    bot_latency = round(bot.latency * 1000)
    await interaction.response.send_message(f'*Pong! __{bot_latency * 1000}ms__*')```
final iron
#

Where is the discord.ext.commands.tree?

split onyx
#

doesnt need to be their

final iron
#

Also, if you want to have a rotating status you should start the loop in the setup_hook event, not on_ready

#

on_ready isn't what you think it is

hushed galleon
#

are you trying to define slash commands in a cog? if so, you want to use @discord.app_commands.command() as the decorator, rather than tree.command()

split onyx
split onyx
hushed galleon
#

sure

split onyx
#

sure?

#

what should I change here? I am unfamiliar with slash commands. py async def ping(self, interaction: discord.Interaction): bot_latency = round(self.bot.latency * 1000) await interaction.response.send_message(f'*Pong! __*{bot_latency * 1000}ms*__')

final iron
#

Looks fine

split onyx
#

ok

final iron
#

Just try it and see

hushed galleon
#

sure as in it would work, no sarcasm about that

#

though you'll see in the documentation that the app_commands module is usually imported directly using from discord import app_commands (or at least implied), making it a bit shorter to write out @app_commands.command(...)

final iron
#

Read through the error please. It'll be clear what the issue is

split onyx
#

The slash command isnt working in discord and no error messages are occuring.```py
import discord
from discord.ext import commands
from discord import app_commands

class SCInfo(commands.Cog):
def init(self, bot):
self.bot = bot

@commands.Cog.listener()
async def on_ready(self):
    print('[SC COGS] - SCInfo cog loaded successfully.')


@app_commands.command(name="ping", description="Returns the bot's latency.")
async def ping(self, interaction: discord.Interaction):
    bot_latency = round(self.bot.latency * 1000)
    await interaction.response.send_message(f'*Pong! __*{bot_latency * 1000}ms*__')

async def setup(bot):
await bot.add_cog(SCInfo(bot))```

final iron
#

Have you synced?

split onyx
#

yes

#

shit

final iron
#

Does it show in your servers integration tab?

split onyx
#

hold on

split onyx
final iron
#

Restart your discord client

split onyx
#

ok

split onyx
#

😃

final iron
#

@hushed galleon This is how the current setup is, what do you think? I'm going to change the Buttons, those are just placeholders for now

hushed galleon
final iron
#

I was trying to format the Views and App Commands like that, but each heading would be too nested

#

ill try again tomorrow and see what i can do

drifting arrow
final iron
latent jay
torn sail
final iron
#

Whenever a bot is in a VC I always deafen it if I can because who knows what the owners are doing

final iron
hallow kernel
#

Ok i know it is possible to send slash command like that:
</command:469569755461925990263140>

But can is send like, with filled arguments, so it would be
/command arg1:value1

#

Ah

#

With positional is just space amd it works

#

Like that
</tag regex:123>

shrewd apex
#

nice

final iron
#

Oh that’s interesting

hushed galleon
final iron
#

Oh I thought he said receive

#

My bad

hushed galleon
#

ah, fair enough

paper cipher
#

hey, i tried this this morning and implemented an on_command_error function in my main bot class file:

async def on_command_error(self, ctx: Context, error: Exception): 
        ignored = (
            commands.CommandNotFound,
            commands.NotOwner,
            commands.CheckFailure,
            commands.DisabledCommand,
            commands.UserInputError
        )
        if type(error) in ignored:
            return
        
        if isinstance(error, commands.MissingRequiredArgument):
            return await ctx.send_help()
        
        elif isinstance(error, commands.BadUnionArgument):
            if error.converters == (Member | User):
                return await ctx.warn(
                    "Unable to find that **member** or **ID**"
                )
        elif isinstance(error, commands.MemberNotFound):
            return await ctx.warn(
                "Unable to find that **member** or **ID**"
            )
        elif isinstance(error, commands.UserNotFound):
            return await ctx.warn(
                "Unable to find that **user** or **ID**"
            )

however now when i run the avatar command and supply a user that doesnt exist, i get no output from the bot and no output in my console? the other errors i have accounted for work fine (like in my ban command)

#

i thought it might have to do with the member: Member | User = None or member = member or ctx.author in my avatar command

shrewd apex
paper cipher
#

ah i fixed it

#

had to make it if error.converters == (Member, User): instead of if error.converters == (Member | User):

desert hollow
#

dWZhaDQtcWZiYjMtd29hbGctaWFidWItbGFhNGEtdGJmbngtY3h4aWgtaTVzd3Item1rcjItZWlraWwtYnFlOlFYTE9XVkFF

shrewd apex
#

?

frank whale
#

Hello there

#

i start to build my own bot on discord and i get an error when i call the external command "XXX"

#
2024-01-05 09:22:25 ERROR    discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "get_bitcoin" is not found```
#
import os
from dotenv import load_dotenv
import discord
from discord.ext import commands

# Initialisation des intentions
intents = discord.Intents.default()
intents.messages = True  # Assurez-vous que les intentions nécessaires sont activées
intents.typing = False
intents.presences = False

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

# Événement lorsque le bot est prêt
@bot.event
async def on_ready():
    print(f'Connecté en tant que {bot.user.name}')
    extensions = ['commands.bitcoin', 'commands.direBonjour']
    for extension in extensions:
        try:
            bot.load_extension(extension)
            print(f'Extension {extension} chargée avec succès.')
        except commands.ExtensionError as e:
            print(f'Erreur lors du chargement de l\'extension {extension}: {e}')
   
# Démarrer le bot
load_dotenv()
bot.run(os.getenv("TOKEN"))

#

import requests
from discord.ext import commands

# URL de l'API CoinGecko pour obtenir le prix du Bitcoin en USD
bitcoin_api_url = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd"

class Bitcoin(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(name='get_bitcoin')
    async def bitcoin(self, ctx):
        response =  requests.get(bitcoin_api_url)
        if response.status_code == 200:
            data = response.json()
            bitcoin_price_usd = data["bitcoin"]["usd"]
            await ctx.send(f"Le prix du Bitcoin est actuellement de {bitcoin_price_usd} USD.")
        else:
            await ctx.send("Désolé, je ne peux pas obtenir le prix du Bitcoin en ce moment.")

def setup(bot):
    bot.add_cog(Bitcoin(bot))
#
/home/ubuntu/Dev/Bot_Discord_BlockchainSpot/init.py:21: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
  bot.load_extension(extension)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Extension commands.bitcoin chargée avec succès.
Extension commands.direBonjour chargée avec succès.

shrewd apex
#

await bot.load_extension in bot

frank whale
# shrewd apex async def setup in cogs

yes i tried to do that but : ```

/home/ubuntu/Dev/Bot_Discord_BlockchainSpot/commands/bitcoin.py:23: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(Bitcoin(bot))

shrewd apex
#

!d discord.ext.commands.Bot.add_cog

unkempt canyonBOT
#

await add_cog(cog, /, *, override=False, guild=..., guilds=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Adds a “cog” to the bot.

A cog is a class that has its own event listeners and commands.

If the cog is a [`app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group) then it is added to the bot’s [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) as well.

Note

Exceptions raised inside a [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog)’s [`cog_load()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.cog_load) method will be propagated to the caller...
shrewd apex
#

u need to await the add_cog also btw

frank whale
#

yes 🙂 thanks @shrewd apex

#

ok so the good way is :


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

fading yew
#

Sorry for asking a question that's probably been asked a billion times, but what's the best library for making discord bots? (never made them before) It seems like discord.py is the most popular, but then some say it's been abandoned, but then it's had a comeback..¿ Is it currently maintained? Is it good, or would u recommend something else? Thx

shrewd apex
naive briar
#

I wonder why the last two are on the same line

fiery girder
#

how to make a global app_command_error handler like on_command_error

slate swan
fiery girder
#

how?

slate swan
#

The approach I take is to subclass CommandTree, do what I want in there and then set tree_cls keyword argument in the Bot constructor to my new tree class

fiery girder
#
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}")
        self.tree.copy_global_to(guild=self.testing_guild)
        await self.tree.sync(guild=self.testing_guild)
        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}.")````
#

I have this

slate swan
#

Bot(Bot) 🤔
Another way could be to just make your own on_app_command_error method inside Bot and then something like self.tree.on_error = self.on_app_command_error inside Bot.__init__

fiery girder
#

ok

#

so i just link it to a function?

slate swan
#

Essentially yes
But I would read the docs on on_error to make sure your function has the correct signature and stuff

fiery girder
slate swan
#

Read through the link I sent, it'll answer your question

#

This is part of why I prefer the subclassing approach, many editors will warn you when a child class's overridden method signature is incompatible with that of the parent class

vocal plover
hasty pike
#

Error:
Command raised an exception: AttributeError: 'Shoya' object has no attribute 'top_role'

Shoya is my bot class

I tried self.client.top_role.position

hasty pike
#

Got it, nvm

brazen geyser
#

hey guys, can someone please tell me why this error handler isnt working?

hasty pike
#

Why don't you make universal error handler

brazen geyser
#

pls i need that

hasty pike
brazen geyser
hasty pike
#

That's a event

brazen geyser
hasty pike
#

That's how i handle errors

hasty pike
brazen geyser
#

ohh, i forgot that its that cog listener ._.

brazen geyser
# hasty pike That's how i handle errors

even after that im still getting this

2024-01-05 14:11:20 ERROR    discord.app_commands.tree Ignoring exception in command 'set'
Traceback (most recent call last):
  File "C:\Users\danie\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\danie\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 849, in _invoke_with_namespace
    if not await self._check_can_run(interaction):
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\danie\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 987, in _check_can_run
    return await async_all(f(interaction) for f in predicates)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\danie\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\utils.py", line 703, in async_all
    for elem in gen:
  File "C:\Users\danie\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 987, in <genexpr>
    return await async_all(f(interaction) for f in predicates)
                           ^^^^^^^^^^^^^^
  File "C:\Users\danie\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\checks.py", line 232, in predicate
    raise MissingRole(item)
discord.app_commands.errors.MissingRole: Role 1154457410677788732 is required to run this command.  
hasty pike
#

Unhandled error

brazen geyser
#

how can it be unhandled

dreamy dune
hasty pike
#

Is that so?

#

I use hybrid so I'm not sure

brazen geyser
fiery girder
#

how many context menus can i add into my message

warm totem
#

is it ok if i post here ads? or nah

fiery girder
#

idk why am igetting this error can someone tell code and error bot in the paste

slate swan
#

discord.Message is unsupported annotation in commands

fiery girder
#

but i have used it before

#

with hybrid commands

fiery girder
fiery girder
# slate swan discord.Message is unsupported annotation in commands
@bot.hybrid_command(name="reactionrole", description="Create a reaction role")
@commands.has_permissions(manage_roles=True)
async def reactionrole(
    ctx,
    message: discord.Message,
    role: discord.Role,
    emoji: discord.Emoji = "✅",
    limit=10000,
):
    db.execute(
        "INSERT INTO reaction_roles VALUES (?, ?, ?, ?, ?, ?, ?)",
        (
            ctx.guild.id,
            message.channel.id,
            message.id,
            role.id,
            emoji,
            limit,
            dt.datetime.now(),
        ),
    )
    main_db.commit()
    await message.add_reaction(emoji)
    await ctx.author.send(
        embed=Embed(
            title="Reaction Role",
            description=f"Reaction Role Created\nRole: {role}\nEmoji: {emoji}\nLimit: {limit}",
            color=Color.green(),
        )
    )
    main_db.commit()

One of my prevous commands

golden portal
#

hybrid converts unsupported annotations for slash into the regular converter, but plain app commands doesnt support it

golden portal
#

you can't, for discord.Message annotation, only that is for context menus specifically

fiery girder
#

any other way i can get a message?

final breach
#
class EmbedSender(commands.Cog):
    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot

    async def send_embed(self, discord_id: str, embed_type: str = "login") -> None:
        channel_id = settings.PLAYERS_LOG_CHANNEL_ID
        if channel_id is None:
            return
        channel = self.bot.get_channel(int(channel_id))
        if embed_type == "login":
            embed = await login_embed(discord_id)
        elif embed_type == "logout":
            embed = await logout_embed(discord_id)
        await channel.send(embed=embed)
        logger.info(f"Message {embed_type} embed has been sent successfully")


async def setup(bot: commands.Bot) -> None:
    await bot.add_cog(EmbedSender(bot))

i made this cog in cogs folder
how to get this function outside bot files
(i have function out side discord bot i need here to send embed message)

golden portal
fiery girder
#

ok

golden portal
#

no int is too small to contain a snowflake

#

javascript L issue

fiery girder
#

ok got t

fiery girder
golden portal
#

if all you do is send a message, maybe use a webhook? you dont need the bot for that

fiery girder
#

webhooks are slow

golden portal
#

err i dont know about that, i mean webhook has it's own ratelimit independent of bot

fiery girder
#

is channel.get_partial_message corontine?

golden portal
#

no

fiery girder
#

ok

#

btw how many context menus can i make?

#

i alr have 3

  1. Translate
  2. Bookmark
  3. Report
#

i want to make more but idk if i can

fiery girder
golden portal
golden portal
fiery girder
#

oh thats low

#

can i have like 5 global and some other for guilds?

golden portal
#

that one i've no clue

fiery girder
#

ok

fiery girder
golden portal
#

fetch_message, get_partial_message is only used for calling another method related to the message but they aren't filled with message values

fiery girder
#

ok

fiery girder
golden portal
#

guild.audit_logs

#

Then get it by action message_delete

fiery girder
#

umm

#

!d discord.Guild.audit_logs

unkempt canyonBOT
#

async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) that enables receiving the guild’s audit logs.

You must have [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log) to do this.

Examples

Getting the first 100 entries:

```py
async for entry in guild.audit_logs(limit=100):
    print(f'{entry.user} did {entry.action} to {entry.target}')
```...
fiery girder
golden portal
#

ye

queen pond
#

any tutorials to get started with discord bots,i know the basics of python but all of the tutorials go straight to making a discord but none i found that thoroughly explain the discord module

fiery girder
#

!d discord

queen pond
fiery girder
#

if you want any help you can ask me

#

or any one in this server they will help

queen pond
#

the docs u sent actually explain the module

fiery girder
#

well there is a lot more

#

do you want prefix command or app_commands?

#

you can make prefix app and hybrid(both prefix and hybrid)

queen pond
fiery girder
#

prefix is problem the easiest

#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin) to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) and is automatically set upon instantiating the class.

async with x Asynchronously initialises the bot and automatically cleans up.

New in version 2.0.
queen pond
fiery girder
#

and you will also need this

#

!d discord.Intents

unkempt canyonBOT
#

class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.

Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.

To construct an object you can pass keyword arguments denoting the flags to enable or disable.

This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client).

New in version 1.5.
fiery girder
#

!d discord.ext.commands.Bot.command

unkempt canyonBOT
#

@command(*args, **kwargs)```
A shortcut decorator that invokes [`command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.command) and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command).
queen pond
fiery girder
#

np

lean lark
#

Is there any way to get the count of all the messages a user has sent in the server without looping through the ctx.channel.history(limit=None) async generator?

winter coral
#
class DevTools(commands.Cog):
    def __init__(self, bot) -> None:
        self.bot = bot

    @commands.Cog.listener()
    async def on_message(self, *_):
        print('msg got')

    @commands.Cog.listener()
    async def on_ready(self):
        print('bot up')
```I have this cog. the `on_message` event runs, but the `on_ready` event does not. The cog is loaded from the bots `on_ready`, which I assume is the problem. Is there some on_cog_loaded event? Or should I move the bot ready notification (it will send a msg to a log channel) to the bot itself. I don't want to bloat the bot class too much.
slate swan
#

you should move your startup code to setup_hook event

winter coral
slate swan
#

isnt bot.guilds always the same guild hence can be hardcoded?

pale zenith
unkempt canyonBOT
#

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

A special method that is called when the cog gets loaded.

Subclasses must replace this if they want special asynchronous loading behaviour. Note that the `__init__` special method does not allow asynchronous code to run inside it, thus this is helpful for setting up code that needs to be asynchronous.

New in version 2.0.
pale zenith
#

and also cog_unload, it's sister method

slate swan
pale zenith
#

(also you shouldn't do startup stuff in on_ready as it can fire many times lol, best to create_task a coroutine with a await bot.wait_until_ready() call as the first thing)

winter coral
slate swan
#

how is the main on_ready event defined?

winter coral
#

we do already have a .env file, I will just add a bunch of sanity checks and call it a day

winter coral
slate swan
#

yeah but the actual on_ready definition

#

you use the @bot.event ?

winter coral
slate swan
#

ok actually i see the self here so i assume you subclass the Bot and override the method

winter coral
#

yup

winter coral
#

yeah, I will just use that then.

#

ty

slate swan
#

One message removed from a suspended account.

#

One message removed from a suspended account.

#

One message removed from a suspended account.

hushed galleon
#

!d discord.utils.format_dt

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

you er, give it a datetime and the style that you want to show and it formats it into the correct string for showing the timestamp py my_time = datetime.datetime.now() timestamp = discord.utils.format_dt(my_time, "R") await ctx.send(timestamp) which results in <t:1704480462:R> (<t:1704480462:R>)

slate swan
#

One message removed from a suspended account.

#

One message removed from a suspended account.

slate swan
hushed galleon
slate swan
#

One message removed from a suspended account.

hushed galleon
slate swan
#

One message removed from a suspended account.

hushed galleon
#

markdown formatting gets ignored if you wrap it in backticks, so er don't use that

slate swan
slate swan
slate swan
#

trying to just send a message when the on_presence_update occurs to get a test message to go through for a possible logging channel setup. why doesn't this send a message?
i'm using a CHANNEL_ID and using the self.fetch_channel(CHANNEL_ID) I also tried self.get_channel(CHANNEL_ID)to get the discord channel to do channel.send, but it doesn't send a message? I'm using this as an example because I'm trying to make custom messages to be sent when events happen from outside discord api events. So I can log those in a certain channel.

if after.activity is not None:
            print(after.guild.id)
            channel_id = CHANNEL_ID
            channel = self.fetch_channel(channel_id)
            await channel.send(f"<t:{int(unix_time)}:T> After:\n{after.activity.type} || {after.activity.name}")
#

do I have to like... check and see if user is in that guild.id first, then use guild as my base? like this...?

        guild = self.get_guild(GUILD_ID)
        channel = guild.get_channel(CHANNEL_ID)
hushed galleon
#

if no to both, you might be missing the members/presences intent which are both needed to receive on_presence_update(), but otherwise get_guild()+get_channel() is the most optimal way to retrieve the channel

slate swan
#

I have intents.all on currently.
it's wrapped in my super().__init__()

#

would that be an issue?

hushed galleon
#

sounds fine... what about the print statement and errors?

slate swan
#

no errors.

#

i even did try/except catches

#

the cog is loaded.

hushed galleon
#

does the guild ID get printed though?

slate swan
#

yes

#

the guild id does, but nothing else.

hushed galleon
#

hmm, i would suspect that there was an error, but it got suppressed by either your try/except clause or an on_error handler

slate swan
#

probably on_error.

#

cause I setup all the cog listeners as tests in their own cog so I can import controllers later.

hushed galleon
hushed galleon
slate swan
#

so pass the bot through as client instead of commands.Bot?

class OnError(commands.Cog):
    def __init__(self, bot: commands.Bot) -> None:
        self.bot= bot
        self.message = None
    @commands.Cog.listener()
    async def on_error(self, event, *args, **kwargs):
        """ Usually when an event raises an uncaught exception, a traceback is logged to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.
            The information of the exception raised and the exception itself can be retrieved with a standard call to sys.exc_info().
            Changed in version 2.0: The traceback is now logged rather than printed.
            Parameters
                event (str) – The name of the event that raised the exception.
                args – The positional arguments for the event that raised the exception.
                kwargs – The keyword arguments for the event that raised the exception."""
        print(f"On Error: \nEvent: {event}\nArgs: {args}\nKwargs: {kwargs}")
        pass
async def setup(bot: commands.Bot):
    await bot.add_cog(OnError(bot))
    print('OnError loaded')

legit bare minimum right now lol

hushed galleon
#

actually based on their source code and docs, on_error doesn't support listeners so the cog doesn't have any effect

#

if you didn't define on_error in your Bot subclass, it's likely using the default handler which logs the exception according to the logging configuration

#

how do you start your bot, using bot.run() or await bot.start()?

#

if it's the latter and you haven't already set up logging yourself (docs), you should call discord.utils.setup_logging() before starting it, otherwise it won't print any exceptions from your on_presence_update()

slate swan
slate swan
# hushed galleon if it's the latter and you haven't already set up logging yourself ([docs](<http...

I tried to setup logging, but I'm assuming I did it wrong in the setup_hook.


    async def setup_hook(self) -> Coroutine[Any, Any, None]:
        await self.load_modules()

        discord.utils.setup_logging(
            level=logging.INFO,
            handler=MyFileHandler('D:\\Discord\\Logs\\info_discord.log'),
            formatter=logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')
        )
        discord.utils.setup_logging(
            level=logging.DEBUG,
            handler=MyFileHandler('D:\\Discord\\Logs\\debug_discord.log'),
            formatter=logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')
        )
        discord.utils.setup_logging(
            level=logging.WARNING,
            handler=MyFileHandler('D:\\Discord\\Logs\\warning_discord.log'),
            formatter=logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')
        )
        discord.utils.setup_logging(
            level=logging.ERROR,
            handler=MyFileHandler('D:\\Discord\\Logs\\error_discord.log'),
            formatter=logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')
        )
        discord.utils.setup_logging(
            level=logging.CRITICAL,
            handler=MyFileHandler('D:\\Discord\\Logs\\critical_discord.log'),
            formatter=logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')
        )

        print(f"Bot is online.")
        return await super().setup_hook()
hushed galleon
#

uhh the lowest level captures everything above that level, so debug_discord.log would contain INFO, WARNING, ERROR, and CRITICAL logs

#

but regardless that should write any on_presence_update errors to your log files...

hushed galleon
slate swan
#

        if after.activity is not None:
            print(after.guild.id)
            print(after.guild.name)
            print(after.activity)
            if after.guild.id == GUILD_ID:
                channel_id = CHANNEL_ID
                channel = self.fetch_channel(channel_id)
                if channel is None:
                    channel = self.get_channel(channel_id)
                print(channel)
                if channel:
                    try:
                        await channel.send(f"<t:{int(unix_time)}:T> After:\n{after.activity.type} || {after.activity.name}")
                    except Exception as e:
                        print(e)
hushed galleon
#

seems okay for debugging purposes, what did it print for the channel?

slate swan
hushed galleon
#

oh i didnt notice you were attempting to use both methods at the same time

#

self.fetch_channel() is an asynchronous function, so not awaiting it merely gives you a coroutine object rather than None

slate swan
#

oh yeah you need to await the fetch_channel

hushed galleon
#

ah thats why it didnt error, you unintentionally invoked coroutine.send() which is a valid method

slate swan
#

ohhhhhhhhhh

hushed galleon
#

i suggest sticking with get_channel() because once your bot is ready, all guilds/channels should already be cached (except if you use AutoShardedBot or you turn off the guilds intent, in which case it's safer to use get_partial_messageable() as linked earlier)

slate swan
hushed galleon
#

uhh if what returns an int? you can still use .send(), it was just getting the channel that needs to be fixed

young dagger
#

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

young dagger
hushed galleon
unkempt canyonBOT
#

discord/client.py lines 700 to 701

# sometimes, discord sends us 1000 for unknown reasons so we should reconnect
# regardless and rely on is_closed instead```
young dagger
#

I just run it on a VPS with PM2

hushed galleon
#

code 1000 is simply a clean websocket closure, it doesnt mean that discord is conveying any error status

young dagger
hushed galleon
#

if you want to sure, but receiving a close code is unlikely to suggest that there's an issue with the connection itself, because that normally results in disconnecting without any close code

young dagger
hushed galleon
#

could be some engineer at discord making changes to the gateway and forcing bots to reconnect... or perhaps they have some automated system to close connections that behave a certain way

#

whatever the cause might be, it was an intentional action by discord's servers to end your gateway connection with code 1000

#

i wouldnt worry that much about it given the downtime was 1 second

pale zenith
#

This error legit just appears sometimes

#

I got it once while polling history on every channel of a server

timber lotus
#

is commands the only way for a bot to store data in a database?

final iron
#

databases are independent from commands

#

In the case of sqlite, they're just files

#

So I don't really understand what you're asking

timber lotus
stiff oriole
slate swan
#

howdy gents its me borger

#

im proud to annouce that my bot is now functioning as intended

#

i'd like to thank the people that have helped me with coding it by providing reasorces and insight

#

yall really did me a solid

#

welp

#

back to the void

split onyx
#

I know its basically all wrongt but im unfamiliar with sql, also add the id and prefix does work but can be built upon better.

final iron
split onyx
#

its just blurred, the info is correct

#

My table in sql has guild.id and newprefix

split onyx
#

...

#

hewO?

split onyx
#

nvm

latent pier
#

How can i get reason of ban of banned user?

robust fulcrum
#

Guys do disnake have cogs watching enabled by default?

hasty pike
#

Error:
Command raised an exception: TypeError: object of type 'async_generator' has no len()

line: len(ctx.guild.bans())

slate swan
#

!d discord.Guild.bans

unkempt canyonBOT
#

async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry).

You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members) to get this information.

Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list.

Examples

Usage...
slate swan
#

See the example 2

hasty pike
#

So i can't get a length?

slate swan
#

Literally look at the second example....

hasty pike
#

I can't see examples in embed

slate swan
#

Come on.... Use at least a little bit of common sense and click on the link on "discord.Guild.bans" - it's not blue for decoration

hasty pike
#

Oh got it

#

Thanks

slate swan
#

hi, I tried to install the fivem library in the terminal and since I installed it, everything in visual studio stopped working, can anyone help me?
Thank you

#

!dash-m use that

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
#

and install discord.py not discord

unkempt canyonBOT
sacred oyster
#

hello

#

I was wondering how would you check the perms of the user who triggered (used) the command

#

in an if block

#

i was using if ctx.message.author.guild_permissions.administrator: because I found it in stackoverflow but I noticed it doesn't work and it's obsolete

slate swan
#

For what do you need to check the permissions

sacred oyster
#

a ban command

slate swan
#

For what

sacred oyster
#

to ban users

slate swan
#

Doesn't answer the question, to send a message? To warn you? To mention the user? To send a nice gif?... ...

sacred oyster
#

I had planned that if the user has enough permission to ban, it would send an embed containing who banned and who got banned

slate swan
#

Then use the decorator instead, will prevent unnecessary code

#

!d discord.ext.commands.has_permissions

unkempt canyonBOT
#

@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the current channel permissions, not the guild wide permissions.

The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions).

This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions) that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).
slate swan
#

See the example

sacred oyster
#

which example

slate swan
#

But click on the blue discord.ext.commands.has_permissions title instead

sacred oyster
#

ohh

slate swan
#

There it's for manage_messages but you can do for anything and add multiple as well

sacred oyster
#

ohhh

#

is there a list to the permissions?

#

or they're just the same name as the ones in roles

slate swan
slate swan
unkempt canyonBOT
#

class discord.Permissions(permissions=0, **kwargs)```
Wraps up the Discord permission value.

The properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit permissions.

Changed in version 1.3: You can now use keyword arguments to initialize [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions) similar to [`update()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.update).
slate swan
#

There's the entire list

sacred oyster
slate swan
slate swan
#

doesn't work, the terminal closes

#

@slate swan

#

In your terminal, you open it and use the command above

#

It won't just close

#

And no point in pinging for every message you send

slate swan
#

Show them then

timid orchid
#

Can someone help

#

i get this error when running my code

Python 3.10.11 (tags/v3.10.11:7d4cc5a, Apr 5 2023, 00:38:17) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

slate swan
timid orchid
#

It doesnt run my bot though

slate swan
#

because you didn't pass the file to run

timid orchid
#

wdym

slate swan
#

python file.py will run the file called file.py

timid orchid
#

oh

slate swan
#

just executing python will just launch python interactively

timid orchid
#

right

#

mb

smoky anvil
#

Trying to run a bot on a vps, but getting this problem, how do i solve?

fiery girder
#

this command is not working its showing interaction didnot respond and it has no errors

slate swan
#

Cause you are missing SSL certificates

shrewd apex
#

not really its more of an internet issue if he is connected to some sort of vpn

late cypress
#

How to pair discord bot with Flask app
suppose i hit route /say_hello/<name>
i want bot to send Hello <name> in channel

shrewd apex
# late cypress How to pair discord bot with Flask app suppose i hit route ```/say_hello/<name>`...

that would require quite a different custom setup ur bot will be running a webserver and u will have another webserver in the form of flask app and any request to this flask app will be forwarded to the bot where the request will further be processed a more hacky way would be you run both the flask and bot from the same program that way a single web server should suffice since you would have access to both instances

late cypress
shrewd apex
#

i did mention how u would setup the project above and how the bot and the website would interact

late cypress
shrewd apex
#

could u specify what exactly are you looking for in "setup"

#

ah ok

shrewd apex
late cypress
#

i got this error called Run time error Timeout context manager should be used inside a task

smoky anvil
late cypress
frozen verge
#

Can someone help with this

golden portal
#

i see, alright, you can't really mix flask with dpy

frozen verge
late cypress
golden portal
frozen verge
#

I also installed it with pip

golden portal
#

you should rename your file spotipy.py to another name, since that's shadowing the package

frozen verge
#

But I have another problem

golden portal
#

err, full traceback please i can't rly see why it's pointing at that

golden portal
frozen verge
golden portal
# late cypress IPC? What is it?

interprocess communication, it's a way to communicate to another process, it's a general concepts, but you can use websocket/db/ and other ways

frozen verge
#

IDK What intent it is

#

I have the message one, Voice one

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.

astral lotus
#

anyone know how to fix this

Error: ENOENT: no such file or directory, read

final iron
edgy plinth
drifting arrow
#

Can discordbots issue timeouts?

sick birch
#

!d discord.Member.timeout

unkempt canyonBOT
#

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

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta).

You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members) to do this.

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit).
drifting arrow
#

oh

#

apparently u dont put "until"

sick birch
#

means "positional only"

drifting arrow
#

Neat

#

So does it mean everything before the / has to be in that order?

#

or just the immediate one?

sick birch
#

I'll get back to you on that

drifting arrow
#

Coz I know the * means everything after has to be specified, so if you got my_func(*,a,b,c) it doesnt matter order, but you still have to say my_func(b=1,c=3) for example. u cant just do 1,3

sick birch
final iron
#

Show some code

edgy plinth
#

that could be making it longer then 3 seconds

mild token
#

How many buttons are possible to add on one interaction?

slate swan
#

Clicking a button, using an application command, choosing an option in a select menu, etc. is an interaction, so the question doesn't make much sense

#

If you mean how many per message, 25 (5 rows with each 5 buttons)

fiery girder
#

i am making a giveaway command what is the best way to make the waiting system

#

cause if i just use ayncio.sleep than it can go off when i restart the bot

rugged shadow
#

store times in your database

fiery girder
#

and if i use db with the @task.loop it stil doesnt feel right

#

cause of the off set

rugged shadow
#

or seconds

fiery girder
#

hours

#

i aint running the loop every minnute

#

i was thinking about doing an hour but it was the offset

#

so i set it to 10 minutes

rugged shadow
#

compute the time left and put that into the tasks.loop

fiery girder
#

wdym?

fiery girder
# rugged shadow no like
@tasks.loop(minutes=10)
    async def giveawayloop(self):
        db.execute(
            "SELECT * FROM giveaways"
        )
        giveaways = db.fetchall()
        for giveaway in giveaways:
            time = giveaway[8]
            minspent = giveaway[7]
            if minspent < time:
                minspent += 10
                db.execute(
                    "UPDATE giveaways SET minspend = ? WHERE message_id = ?",
                    (minspent, giveaway[3])
                )``` i have this
rugged shadow
#

calculate when that'll happen and put that into tasks.loop

#

cancel the task when it gets run

fiery girder
#

hmm

#

my way is easier

rugged shadow
#

what is the point of asking for help then

fiery girder
#

maybe there is a better way

#

and an easier way

rugged shadow
#

what i told you is the easiest way

#

load the giveaway time from the db

#

then schedule that in your bot

slate swan
#

What interrrp said is definitely the way to go

fiery girder
#

i dont understand the method @rugged shadow is suggesting

rugged shadow
fiery girder
#

howww

fiery girder
timber lotus
# fiery girder show like a code example or something please

DECLARATION--- IM NEW TO CODING - WHAT I TELL YOU MIGHT BE "WRONG" BUT THIS HOW I WAS TOLD TO DO IT BY SOME PEOPLE HERE AND SOME INDEPENDENT RESEARCH i just finished giveaway commands for my bot bro. i have my check giveaway function (which calls the end giveaway function) task to run every 1 second. and the key to getting to work between bot restarts is i call check_giveaway function when my giveaway commands cog loads. thats where i was told to put it in here when i asked. also i saved the end time when the giveaway was created. my check giveaway function just first looks for any giveaway that current time is not past end time, if none return the loop stops. if any return, the loop continues running and when the current time reaches the end time its calls my end giveaway function. oh also the check giveaway function is called and started when the start giveaway function.

#

only thing im still having issues with is getting my buttons to still work after bot restarts. i got it for the original message but i also have repost giveaway commands and that messages doesnt lol. i just need to do some debugging and figure out where the mistake is. other than that, this room helped tremendously getting my bot up adn running with giveaway commands

slate swan
#

resources usage goes brrrrr

fiery girder
#

every secound is just way to much]

slate swan
#

and that's why you start a task for x seconds until the giveaway ends on the bot's start

fiery girder
#

i am using 10 minutes cause that just giives my peace

timber lotus
fiery girder
fiery girder
timber lotus
slate swan
#

if it's not a multipurpose bot like 6472927 other bots but a giveaway bot then it's fine.

if it's multipurpose having a giveaway feature is pretty painful to have if you have lots of people that create a giveaway and other features which will use lots of resources in the end

timber lotus
#

lol exactly why only admin is setup to create and start giveaways

raven steeple
#

who can help me about code

timber lotus
#

weill only have 1 or 2 giveaways running at the same time. have our first giveaway running for the past 50some hours

slate swan
#

doesn't change a thing, i can create a server and create hundreds of giveaways in your multipurpose bot and then it may not have enough resources for other features for other users

timber lotus
slate swan
#

Just make it private in the dev portal, don't need to make it work only in your server if people can't invite it

timber lotus
#

ill be honest, i didnt do that on purpose. just thats how the setup video i watched did it haha didnt even realize i was doing it when i did it haha

slate swan
#

¯_(ツ)_/¯

timber lotus
#

but curious, how do you do it for the giveaway to end when its suppose to if you dont check every second?

slate swan
#

can someone help me?

raven steeple
#

hiring python developer 200$ weekly

timber lotus
#

lol

raven steeple
#

need help about code

fiery girder
fiery girder
#

in anyways i am in i was looking for a job anyway

slate swan
#

@fiery girder can you help me?

raven steeple
#

just need a simple error fix

#

ill just pay 20$ for that

#

that ll take ur 5 minutes max

unkempt canyonBOT
#

9. Do not offer or ask for paid work of any kind.

raven steeple
#

oh alr

#

i need hepl about code anyone can hlep_?

fiery girder
glad cradle
timber lotus
#

i guess i schedule the task to run for the last minute of the giveaway or something instead of the whole time?

glad cradle
#

the post task run logic is important because if your Bot shuts down exactly when running the tasks to end a giveaway it'll know in the next restart if it missed some giveaways, at least, it should (never happened on production)

raven steeple
#

why no one helping

#

i sent someone money and he disappeared

naive briar
#

Wha

timber lotus
blazing condor
#

well firstly, this ins't even related to discord bots.

raven steeple
blazing condor
#

is better and just wait patiently.

glad cradle
timber lotus
glad cradle
timber lotus
timber lotus
glad cradle
unkempt canyonBOT
#

add_done_callback(callback, *, context=None)```
Add a callback to be run when the Task is *done*.

This method should only be used in low-level callback-based code.

See the documentation of [`Future.add_done_callback()`](https://docs.python.org/3/library/asyncio-future.html#asyncio.Future.add_done_callback) for more details.
glad cradle
#

or you can just call a function at the end of the giveaway ending function ig

timber lotus
#

gotcha. thanks bro

glad cradle
#

!pypi aiosqlite

unkempt canyonBOT
glad cradle
#

Like this one

timber lotus
glad cradle
#

!blocking

unkempt canyonBOT
#
Asynchronous programming

Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries

  • The standard async library - asyncio
  • Asynchronous web requests - aiohttp
  • Talking to PostgreSQL asynchronously - asyncpg
  • MongoDB interactions asynchronously - motor
  • Check out this list for even more!
timber lotus
#

hmm

slate swan
#

@timber lotus can you help me?

scarlet aurora
gray mantle
#

Extension 'ext.antinuke' raised an error: TypeError: object NoneType can't be used in 'await' expression
TypeError: object NoneType can't be used in 'await' expression
pls fix it i will provide the required code

slate swan
#

We can explain what's wrong, we won't fix it for you

gray mantle
#

okay bro pls explain me where i am doing wrong

blazing condor
#

Could you provide the code where the issue is occuring.

gray mantle
#

okay wiat

#

!insert\

#

bruh how to get that code insertion link

#

!insert

slate swan
#

!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
#

@slate swan

blazing condor
#

and the error is occuring on which line @gray mantle

gray mantle
#
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("/", "."))

its last line

slate swan
#

can someone help me?

#

my bots commands dont show up

#

for some reason...

gray mantle
slate swan
gray mantle
slate swan
#

the commands just dont show up when trying to use them

gray mantle
#

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

slate swan
blazing condor
slate swan
blazing condor
#

why am i blanking on this issue, thinkmon

#

it's gotta be something stupid.

slate swan
#

@blazing condor could u try to help em aswell?

final iron
blazing condor
final iron
#

That’s not the full traceback

slate swan
slate swan
#

actually Id take that back

#

I belive they dont

final iron
#

sync returns a list of AppCommand objects, which have a name attribute

#

Loop through it and print the names

slate swan
#

@final iron print("Logged in as {0.user}".format(bot)) try: synced = await bot.tree.sync() print(f"Synced {len(synced)} command(s)") except Exception as e: print(e) this?

final iron
#

You didn’t change anything

#

That’s what you already had

slate swan
#

for some reason

final iron
#

Nothing is printing?

slate swan
#

yeah

final iron
#

Well yeah…

slate swan
#

maybe because of the statuses I added

final iron
#

You have a while loop

slate swan
#

@final iron so how do I make the sync do itself once and then let the while loop go on?

final iron
#

You shouldn’t be looping through presences.

slate swan
#

how could I separate the two?

final iron
#

You shouldn’t be looping through presences.

slate swan
#

@final iron so I updated the code and still doesnt update it

lofty nacelle
#

I am working no a project. But i cant figure out how can i work with my friends. How can we work together is a same project. Can anyone help me out. I am new to these all !

final iron
timber lotus
slate swan
#

Can make a PR on GitHub

#

Actually even Heroku doesn't provide free hosting, so the entire section can be removed

meager raven
#

hello i'm neew in python, acn you please explain me why it does that when i install discord with pip

slate swan
#

Python 3.12 is not supported yet, downgrade to 3.11

meager raven
#

thxs

#

the 2020 or 2022 version ?

#

@slate swan

slate swan
meager raven
#

thanks

desert kiln
#

Good afternoon my fellow friends, I'm looking to make buttons for my embeds, and was wondering how to do it?

final iron
desert kiln
final iron
desert kiln
final iron
#

You haven't said which library you're using, so it's literally impossible to give a link

final iron
#

In the repository there's an examples folder

desert kiln
#

what repository

final iron
desert kiln
final iron
#

Which part of the example didn't you understand?

desert kiln
final iron
#

Just try it and see

#

There's like 10 different examples, so you're not really being specific enough for me to be able to comment on any changes

desert kiln
final iron
#

Take it one at a time

#

Just create the two buttons at first

#

Then, implement the permissions check

robust fulcrum
#

Guys can we override the default help command in disnake like we do in discord.py?

sick birch
#

I assume it's the same way too - pass in the custom help command instance to the client or bot instance

drifting arrow
#

using text commands, is there a way to get just the message that was sent?
message = ctx.message.content
Partial of my function:

    @commands.command(name='m')
    @commands.guild_only()
    async def text_reply(self, ctx):
        author_roles = ctx.author.roles
        for role in author_roles:
            if role.id in self.roles:
                database_data = await database.search_for_channel(channel_id=ctx.channel.id)
                message = ctx.message.content
#

i havent used text commands in a while lol

#

I usually use slash commands.

#

nvm. i needed anoter paramater lol

#

async def text_reply(self, ctx, response_message): XD

vital glacier
#

is there a way to make ctx.reinvoke() not mess up the rest of my custom error handling? everything after await ctx.reinvoke() gets cancelled out in my on_command_error handler

drifting arrow
#

What is against terms of service

drifting arrow
sick birch
drifting arrow
#

chatgpt helped out. i really didnt want to have to google that issue lol

#

I rarely use text commands so it's not worth spending forever trying to figure out

robust fulcrum
#

Did chatgpt tell you whats "*" for?

acoustic kernel
#

Question:
Right now I have a Folder containing all my code, inside that folder I have a functions folder, containing several functions I use in the code. Now I want to make a cogs folder so I can store individual commands because my code is 1500 lines long. But I also want to use the functions in the Functions folder in my cogs, that I will import to my main.py code. Everytime I try to import a function from my functions folder it gives me a error. IDK why.

-Main Folder
-- Main.py (My Bot)
-- Functions Folder
---All my functions
-- Cogs Folder
---All my cogs

robust fulcrum
#

Show error pls?

acoustic kernel
#

Traceback (most recent call last):
File "c:\Users\djfau\OneDrive\Desktop\Beta UN Bot Version 0.1.5\0_1_6.py", line 50, in <module>
from Cogs_Folder.Donate_Cog import Donate_Cog
File "c:\Users\djfau\OneDrive\Desktop\Beta UN Bot Version 0.1.5\Cogs_Folder\Donate_Cog.py", line 5, in <module>
from Functions_Folder.Check_File_Exists import check_file_exists
ModuleNotFoundError: No module named 'Functions_Folder'

robust fulcrum
#

I mean image of the your file structure

acoustic kernel
#

The cog I am working in is in the Cogs_Folder

robust fulcrum
#

So how you importing the functions? Btw you should organise your files

acoustic kernel
#


import discord
import json
from discord.ext import commands
from discord import app_commands
from Functions_Folder.Check_File_Exists import check_file_exists
from Functions_Folder.Unformat_Number import unformat_number
from Functions_Folder.Check_Player_Budget import check_player_budget
from Functions_Folder.Format_number import format_number
from Functions_Folder.Check_Player_Resource_Quantity import check_player_resource_quantity


class Donate_Cog(commands.Cog):
    def __init__(self, bot: commands.Bot):
        self.bot = bot

...```
#

This is my cog

#

continues on but not important

robust fulcrum
#

Add a . before the Functions_Folder

acoustic kernel
#

Thats giving me a bunch of errors

robust fulcrum
#

Try organising your code in a folder called src and make it a module and use relative imports

#

Show errors?

acoustic kernel
#

PS C:\Users\djfau\OneDrive\Desktop\Beta UN Bot Version 0.1.5> & C:/Users/djfau/AppData/Local/Programs/Python/Python310/python.exe "c:/Users/djfau/OneDrive/Desktop/Beta UN Bot Version 0.1.5/Cogs_Folder/Donate_Cog.py"
Traceback (most recent call last):
File "c:\Users\djfau\OneDrive\Desktop\Beta UN Bot Version 0.1.5\Cogs_Folder\Donate_Cog.py", line 5, in <module>
from .Functions_Folder.Check_File_Exists import check_file_exists
ImportError: attempted relative import with no known parent package

robust fulcrum
#

Run file using -m

#

I recommend your structure your files properly

robust fulcrum
# acoustic kernel

Like do like this

src--|
Cogs
Functions
bot.py
init.py(makes it module)

so the your import the files like

from src.Functions import ...

#

Await it

acoustic kernel
robust fulcrum
#

Make it async function and run it

robust fulcrum
#

Try loading extensions in setup_hook which is called before starting bot

#

Like


async def setup_hook():
  load here

bot.setup_hook = setup_hook
#

!d discord.ext.commands.Bot.setup_hook

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/ext/commands/api.html#discord.ext.commands.Bot.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/ext/commands/api.html#discord.ext.commands.Bot.wait_for) and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_until_ready)...
robust fulcrum
#

can you show me yoru all code?

timber lotus
#

which intents do i need for a bot that only does giveaways, send messages in channels and dms?

#

intents = discord.Intents.default()
intents.message_content = True
intents.guilds = True
intents.guild_messages = True
intents.guild_reactions = True
intents.members = True

this is what i think i need after reading the documentation but i never understand teh documentatioon correctly

robust fulcrum
#

!paste can you send in text form?

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.

robust fulcrum
lofty nacelle
#

I want to code together with my friend.

#

How can i do that

sick birch
#

you most likely want git/github

lofty nacelle
#

HOw can i do with intellij IDE

#

i mean i have no idea about it

#

How can i get started

sick birch
#

There might be an extension but I doubt it's built in - it's not a feature most people would use

robust fulcrum
#

try this

import discord
from discord.ext import commands
import os
from keys import *

class Client(commands.Bot):
    def __init__(self, *args, **kwargs):
        intents = discord.Intents.default()
        intents.guilds = True
        intents.members = True
        intents.message_content = True
        super().__init__(command_prefix="()", intents=intents, *args, **kwargs)

    async def setup_hooks(self):
        initial_extensions = []
        for filename in os.listdir('Discord/cogs'):
            if filename.endswith('.py'):
                initial_extensions.append("cogs." + filename[:-3])
                print(initial_extensions)

        for extension in initial_extensions:
            try:
                await self.load_extension(extension)
            except Exception as e:
                print(f'Failed to load extension {extension}: {type(e).__name__} - {e}')

    async def on_ready(self):
        await self.change_presence(status=discord.Status.online, activity=discord.Game('Under-Development'))
        print('Active')
        print('-------------------------------')

client = Client()

client.run(BOTTOKEN)

this uses concepts of OOPS

timber lotus
#

thank you

robust fulcrum
#

kk

#

is hello command in cogs?

#

looks like cogs are not being loaded properly

#

show me your bot logs?

#

i mean logs

hushed galleon
robust fulcrum
#

logs are shown in terminal

timber lotus
robust fulcrum
#

oops, my bad

#

rename setup_hooks to setup_hook

#

sry for that

hushed galleon
unkempt canyonBOT
#
The `*args` and `**kwargs` parameters

These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.

Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.

Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.

Use cases

  • Decorators (see /tag decorators)
  • Inheritance (overriding methods)
  • Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
  • Flexibility (writing functions that behave like dict() or print())

See /tag positional-keyword for information about positional and keyword arguments

robust fulcrum
#

which line?

vital glacier
#

anyone here experienced with on_command_error handlers?

robust fulcrum
#

np

vital glacier
#
    async def on_command_error(self, ctx: commands.Context, error: commands.CommandError):
        self.logger.warning(f"{ctx.author} ({ctx.author.id}) in {ctx.guild.name} ({ctx.guild.id}) | {ctx.invoked_with}-{type(error).__name__}: {error}")
        if type(error) in (commands.NotOwner, commands.CheckFailure, commands.DisabledCommand, commands.UserInputError):
            return
        elif isinstance(error, commands.CommandNotFound):
            await ctx.warn(f"Command `{ctx.invoked_with}` doesn't exist")
        elif isinstance(error, commands.MissingRequiredArgument):
            await ctx.send_help(ctx.command)
        elif isinstance(error, commands.MissingPermissions):
            if ctx.author.id in self.owner_ids:
                await ctx.reinvoke()
            else:
                await ctx.warn(f"You're **missing** the `{', '.join(error.missing_permissions)}` permission")
        elif isinstance(error, commands.BotMissingPermissions):
            await ctx.warn(f"I'm **missing** the `{', '.join(error.missing_permissions)}` permission")

on_command_error handler isn't triggering elif isinstance(error, commands.CommandNotFound): triggers everything else properly tho.

naive briar
#

Is your ctx a custom context?

vital glacier
#

yeah it is

languid schooner
#

Hey, I've been working on a way to do permissions in a more custom way that allows me to add permissions to sub-commands. I want to be able to do:

class RacoonCommand(commands.Cog):
    def __init__(self, client: nextcord.Client):
        self.client = client

    @register_pizza_command(permission=Rank.MEMBER)
    @nextcord.slash_command(
        name="racoon",
        description="🦝"
    )
    async def racoon(self, interaction: Interaction):
        return


def setup(client: nextcord.Client):
    client.add_cog(RacoonCommand(client))

My issue is the @register_pizza_command decorator. I am using nextcord and whenever I load the cog, I get no error however, the command does not load client side. When I add the decorator, the command is no longer visible.

This is my current code for the decorator:

def register_pizza_command(permission: Rank):
    def decorator(func):

        async def wrapper(self, interaction, *args):
            print(interaction)

        return wrapper
    return decorator

Is anyone able to point me in the right direction with this? I'm not very experienced with decorators as you can probably tell.

robust fulcrum
vital glacier
robust fulcrum
naive briar
#

What

vital glacier
#

yeah but that's the whole problem, it's not doing that

robust fulcrum
#

did you try by running a command which is not present?

naive briar
#

I suggest that you should add a else block that raise possible uncatched errors

vital glacier
#

yeah...?

robust fulcrum
#

hmm weird

vital glacier
#

it's not triggering on none existing commands

robust fulcrum
#

try prinitng errors?

#

and debug

vital glacier
#

it's not triggering the whole commands.CommandsNotFound

#

so all i do is an try except

#

but not even sure if that would work

robust fulcrum
#

you are suppressing errors, add a else block too

vital glacier
#

how do u expect me to print errors when it's not being triggered.

#

if it isn't triggered, it's pretty difficult to print errors from it

robust fulcrum
#

bro i mean comment your if/else and debug by printing error

naive briar
#

Your handler is probably just not catching the error, so just try it

robust fulcrum
#

ye, you are right

vital glacier
#

oml..

#

i have that and it isn't catching any errors

robust fulcrum
#

wdym?

timber lotus
vital glacier
#

that is just part of my error handler, my whole error handler is mad long and i also have a part that it should catch an error and print it, but it isn't printing anything which means there aren't any errors

#

let me disable logging to see if it does ANYTHING at all

#

even with logging disabled it doesn't put anything in console

hushed galleon
# languid schooner Hey, I've been working on a way to do permissions in a more custom way that allo...

there are various nuances to decorators here that make it difficult to use correctly, but basically the command decorators in discord.py and its forks will turn the function into some Command object which has some incompatibilities with decorators one might typically write, so i would highly recommend using nextcord's check function which handles making it work correctly:
https://docs.nextcord.dev/en/stable/ext/application_checks/index.html#nextcord.ext.application_checks.check ```py
from nextcord.ext import application_checks

def is_me():
def predicate(interaction: Interaction):
return interaction.user.id == 85309593344815104
return application_checks.check(predicate)

@bot.slash_command()
@is_me()
async def only_me(interaction: Interaction):
await interaction.response.send_message('Only you!')```

vital glacier
#

You want to see the whole error handler?

#

@robust fulcrum

robust fulcrum
#

ok?

vital glacier
#

that's the entire on_command_error handler. it catches anything atp

#

I even changed it earlier to made it print any other errors but it doesn't, which means nothing is getting surpressed

robust fulcrum
#

tf its so big

#

you must organise it

vital glacier
#

That's what happens if you've got a proper bot and you need proper error handling for basically everything

#

It's organised lol

robust fulcrum
#

it isn't

#

it isn't recommend to nest if/else a lot

vital glacier
#

This is a global error handler bro, I need to do elif isinstance for those or else it won't catch shit

languid schooner
vital glacier
#

just my main file is almost 2k lines already, and i have 10 cog files, which are all files with commands and events

#

and then i have a whole folder with helpers

hushed galleon
#

wait so CommandNotFound isnt even being logged at the top?

vital glacier
#

it's not getting triggered anywhere, but everything else after that is getting triggered just fine

#

had to triple debug to make sure i wasn't tweaking

#

if you want you can test for urself, just dm me and i'll send you a invite to the cord and i'll let you debug it as much as u want

hushed galleon
#

if the error handler works with other errors, that would suggest the bot didn't actually raise a CommandNotFound error, perhaps from an early return in processing the command

vital glacier
hushed galleon
#

do you have an overridden on_message?

vital glacier
#

that's right above the error handler

#

wait fuck i see the problem

hushed galleon
#

if not ctx.command: is probably why

vital glacier
#

oml im fucking blind holy shit.

#

yeah ok that was the problem. jesus christ im fucking blind

languid schooner
# hushed galleon there are various nuances to decorators here that make it difficult to use corre...

Hmm, so I have this so far and it does print interaction but the command itself fails and just returns "The application did not respond"

def register_pizza_command(rank: Rank):
    def predicate(interaction: Interaction):
        print(interaction)
    
    return application_checks.check(predicate)
@nextcord.slash_command(
  name="racoon",
  description="🦝"
)
@register_pizza_command(rank=Rank.MEMBER)
async def racoon(self, interaction: Interaction):
  await interaction.response.send_message("🦝")
vital glacier
#

i been overlooking that code for the past 30mins and i missed that the whole time LOL

hushed galleon
languid schooner
#

oh I see

languid schooner
drifting arrow
#

Can I send a video as part of an embed?

naive briar
#

No (to my knowledge)

#

Not without a link anyway

drifting arrow
#

If I have a URL?

hollow osprey
#

!rule 7 | Don't post irrelevant polls or surveys

unkempt canyonBOT
#

7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.

faint dragon
#

Just gonna drop this cursed piece of art here for you guys KEKW

thin raft
#

average discord bot code id say

faint dragon
#

nobody seems to stray off the beaten path

thin raft
#

I love the comments

#

so useful

faint dragon
#

oh boy, youre gonna love this

thin raft
#

@commands.group("log")
Creates a log group

#

who would've guessed

#

and then the actions lol

faint dragon
thin raft
#

oh shit

faint dragon
#

thats the reason why it doesnt look like discord.py or pycord at all lol

thin raft
#

can you show the first method that appears on the pic