#discord-bots

1 messages ยท Page 344 of 1

slate plover
#

let me check their types rq

#

anyways

#

ill continue debugging after I come back from school. Adios!

vestal moss
#

coro ?

supple locust
vestal moss
#

how but

#

await bot.l.......?

upbeat otter
#

!d discord.Client.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/api.html#discord.Client.login), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready) event.

Warning

Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for) and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready)...
vestal moss
upbeat otter
#

yeah that's fine

#

now use asyncio to run it

vestal moss
#

ya did but its not starting

upbeat otter
#

oh you've gotta start the bot too

#

!d discord.ext.commands.Bot.start

unkempt canyonBOT
#

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

A shorthand coroutine for [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login) + [`connect()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.connect).
vestal moss
#

ya i started

#

just it had tokken so didnt put here

#
import discord
import asyncio
from keep_alive import keep_alive
from discord.ext import commands


intents = discord.Intents.all()
activity = discord.Activity(name='Knife HQ pre alpha 0.0.1 \n prefix = pls',
                            type=discord.ActivityType.watching)
bot = commands.Bot(
    command_prefix=["pls ", "Pls ", "PLS ", "PLs ", "PlS ", "pLs  ", "pLS "],
    case_insensitive=True,
    activity=activity,
    intents=intents)


async def main():
  async with bot:
    await bot.load_extension('cogs.auto_task')
    await bot.load_extension('cogs.Battle')
    keep_alive()
    bot.run(
        'tokken'
    )


asyncio.run(main())```
#

no error coming but bot isnt coming on

#

it was coming before setting aysnc

upbeat otter
#

also what is this keep_alive function

#

it seems to be blocking

#

ah, you're probably on replit trying to host your bot?

vestal moss
vestal moss
#

ok it was not awaited

#

start

upbeat otter
#

wow

safe stag
#

Dear Community,

I need your help! I want to ensure that only the ticket owner can click the buttons in my Discord server. Can someone explain to me how I can achieve this?

Thank you in advance for your support! ```py
class frageticket(discord.ui.View):
def init(self):
super().init(timeout=None)

async def check_user_permissions(self, interaction):
    ticket_opener_id = None
    channel = interaction.channel
    if channel.topic and channel.topic.startswith("Ticket opened by"):  
        ticket_opener_id_str = channel.topic.split(":")[-1].strip()
        if ticket_opener_id_str.isdigit():
            ticket_opener_id = int(ticket_opener_id_str)
    
    return interaction.user.id == ticket_opener_id

@discord.ui.button(label="Yes, I still have questions", style=discord.ButtonStyle.primary, row=1, emoji="๐ŸŽŸ๏ธ", custom_id="frage_ticket")
async def ask_back(self, button, interaction):
    has_permissions = await self.check_user_permissions(interaction)
    if not has_permissions:
        await interaction.response.send_message("Du bist nicht berechtigt, dieses Ticket zu bearbeiten.", ephemeral=True)
        return

    embed = discord.Embed(
        title="Weitere Fragen stellen",
        description=f"Alles klar {interaction.user.mention}, du kannst jetzt deine Fragen stellen.",
        color=discord.Color.green()
    )
    await interaction.response.send_message(embed=embed)

@discord.ui.button(label="Nein, alles erledigt", style=discord.ButtonStyle.green, row=1, emoji="โœ…", custom_id="no_ticket")
async def no_back(self, button, interaction):
    has_permissions = await self.check_user_permissions(interaction)
    if not has_permissions:
        await interaction.response.send_message("Du bist nicht berechtigt, dieses Ticket zu bearbeiten.", ephemeral=True)
        return

    server_id = interaction.guild.id
    await asyncio.sleep(1)
    await interaction.channel.delete()``` but he says I am not the owner of the ticket, I am the owner of the ticket
fathom wind
#

yea i did

#

can you fix it?

shrewd apex
unkempt canyonBOT
#

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

A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.

This is useful to override if, for example, you want to ensure that the interaction author is a given user.

The default implementation of this returns `True`.

Note

If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.on_error) is called.
north kiln
#

show your code

#

after doing the edit

frosty roost
#

This is my code to get a users info

#

This is the error I get

#

What am I missing?

slate swan
#

Can you please send me the code as an actual message (not image)?

frosty roost
#

@tree.command(name="info", description="Shows user info", guild=discord.Object(id=1130871795248005205))
async def info(ctx, user: discord.User=None):
if user is None:
user = ctx.user
date_format = "%a, %d %b %Y %I:%M %p"
user_id_str = str(user.id)
user_points = points.get(user_id_str, 0)

name = user.display_name
pfp = user.display_avatar

embed = discord.Embed(
title='User info',
color=discord.Colour.pink(),
)
members = sorted(ctx.guild.members, key=lambda m: m.joined_at)
embed.add_field(name="Join position", value=str(members.index(user)+1))
embed.add_field(name="Joined", value=user.joined_at.strftime(date_format))
embed.add_field(name="Registered", value=user.created_at.strftime(date_format))
if len(user.roles) > 1:
    role_string = ' '.join([r.mention for r in user.roles][1:])
    embed.add_field(name="Roles [{}]".format(len(user.roles)-1), value=role_string, inline=False)
perm_string = ', '.join([str(p[0]).replace("_", " ").title() for p in user.guild_permissions if p[1]])
embed.add_field(name="Guild permissions", value=perm_string, inline=False)
embed.set_footer(text='ID: ' + str(user.id))
embed.set_author(name=f'{name}', url=None, icon_url=f'{pfp}')
await ctx.response.send_message(embed=embed, delete_after=120)
slate swan
#

Thanks!

#
@tree.command(name="info", description="Shows user info", guild=discord.Object(id=1130871795248005205))
async def info(ctx, user: discord.User=None):
    if user is None:
        user = ctx.user
    date_format = "%a, %d %b %Y %I:%M %p"
    user_id_str = str(user.id)
    user_points = points.get(user_id_str, 0)
    
    name = user.display_name
    pfp = user.display_avatar
    
    embed = discord.Embed(
    title='User info',
    color=discord.Colour.pink(),
    )
    members = sorted(ctx.guild.members, key=lambda m: m.joined_at)
    embed.add_field(name="Join position", value=str(members.index(user)+1))
    embed.add_field(name="Joined", value=user.joined_at.strftime(date_format))
    embed.add_field(name="Registered", value=user.created_at.strftime(date_format))
    if len(user.roles) > 1:
        role_string = ' '.join([r.mention for r in user.roles][1:])
        embed.add_field(name="Roles [{}]".format(len(user.roles)-1), value=role_string, inline=False)
    perm_string = ', '.join([str(p[0]).replace("_", " ").title() for p in user.guild_permissions if p[1]])
    embed.add_field(name="Guild permissions", value=perm_string, inline=False)
    embed.set_footer(text='ID: ' + str(user.id))
    embed.set_author(name=f'{name}', url=None, icon_url=f'{pfp}')
    await ctx.response.send_message(embed=embed, delete_after=120)
#

@frosty roost It might be because of the Members intent

#

Go to the developer portal and try allow all of this

#

Then, when initializing your Discord bot, add the parameter intents=discord.Intents.all()

frosty roost
#

Okay I will try that cuz I've already enabled all of those

slate swan
#

Also try this

...
if user in ctx.guild.members:
    members = sorted(ctx.guild.members, key=lambda m: m.joined_at)
    join_position = members.index(user) + 1
    embed.add_field(name="Join position", value=str(join_position))
else:
    print("Member not found in the guild's member list.")
#

And let me know if the error message appears in the console.

#

Correct!

#

did this from my memory haha

north kiln
#

I don't think showing the member join position thing is important at all

frosty roost
#

Yeah intents.all did not work

#

But tbh yeah I don rly need join position XD

#

Ty very much for the help tho

slate swan
#

You're welcome!

frosty roost
#

Im trying to set it so only people iwth specific permission can use this command

#

@tree.command(name="empress", description="empress", guild=discord.Object(id=1130871795248005205), default_member_permissions=(discord.Permissions(CreateEvents=True)))
async def empress(interaction):
await interaction.response.send_message("ttps://media.tenor.com/VR9uQrFOTmsAAAAM/gavel-order-in-court.gi", delete_after=10)

#

This is the error i get

#

What are valid permisison names for the permissions?

frosty roost
#

just python

slate swan
#

alr so

#

I can't find CreateEvents in the docs

frosty roost
#

So create events is not a permission I can use for this?

slate swan
#

So from what I've seen is you can try to put @app_commands.checks.has_permissions(administrator=True) above @tree.command ...

#

(for example)

frosty roost
slate swan
#

take a peek into the docs bro

frosty roost
#

Thank ya

fathom wind
slate plover
slate swan
#

I hate black hats / skiddies (writing illegal code) ๐Ÿ˜ 

formal basin
#

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

formal basin
#

https://paste.pythondiscord.com/HMNQ

Hello, my discord bot keeps sending this every time I run it.

server leave server: `````` owner: ```None```

2 times

Now in my paste code, there is no code to do this every time it runs. It only should send the message if someone removes the bot from their server. Please help me

velvet compass
humble silo
#

I feel like this is basic stuff but I'm running into an issue with my code. The bot sends the messages but does not put the user in timeout and there is no error appearing. I'm new to all of this so sorry in advance!

pale zenith
# humble silo I feel like this is basic stuff but I'm running into an issue with my code. The ...

Discord has a feature called automod that handles this for you! You can set up a list of banned words in the server settings.

Anyway, the code you show should give you errors. I would worry if it does not, that may be a sign that you haven't set up logging, and no errors are coming through to your console. The error would be because Member.timed_out_until is an attribute which tells how long until the member's timeout expires. You're confusing with Member.timeout()

humble silo
#

I'll look into the automod. Thanks!

supple locust
#

Take a look at the docs, you just got two attributes of the class confused

slate plover
supple locust
#

Congrats on getting it working!

#

You definitely don't need it after hostDm because it's awaited

slate plover
#

or at the same moment.

slate swan
#

dont use time.sleep() in a discord bot

supple locust
#

you probably don't need the second one though

slate swan
#

use await asyncio.sleep() instead

slate plover
slate swan
#

yes, its blocking

#

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

Thank you in advance.

#

Alright, it works!

formal basin
#

https://paste.pythondiscord.com/HMNQ

Hello, my discord bot keeps sending this every time I run it.

server leave server: `````` owner: ```None```

2 times

Now in my paste code, there is no code to do this every time it runs. It only should send the message if someone removes the bot from their server. Please help me

fiery remnant
#

Hi, I want to do a command for my bot, which will be returning a bot response, but visible only for me as a user, who triggered. For the other users will be hidden. What is important - the replay have to be on a channel, not DM

velvet compass
fiery remnant
#

Hmm, can you send me some info about it? Like, i was browsing everywhere, even via chatgpt and i cannot find anything hah

slate swan
#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by sending a message.
slate swan
#

Set ephemeral to True

fiery remnant
#

Thanks a lot!

slate swan
#

Same for discord.ext.commands.Context (hybrid commands)- though there it only works if it's an interaction

young dagger
#

@vale wing Sorry for the ping. I got a question, should I run docker as root or not?

slate swan
#

I wouldn't

long pecan
#

Heya!! ๐Ÿ™‚
Im looking how to get a followup question to the user off a discord.py interaction (slash command)
So in short:

  • user does /command
  • bot sends embed
  • I then want the user to select something from the above embed. (For now I was thinking a number as they are listed, but another way to do it better is appreciated)

Iโ€™ve looked at followup and interactionresponse, but im not quite sure how to implement either.

long pecan
#

How to implement this?

glad cradle
glad cradle
#

!d discord.ui.Select

unkempt canyonBOT
#

class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu with a list of custom options. This is represented to the user as a dropdown menu.

New in version 2.0.
long pecan
#

Okay thanks.
Ill just send the embed and the dropdown in the appcommand?

pale zenith
#

you can also use the @discord.ui.select deco within a view itself

#

!d discord.ui.select

unkempt canyonBOT
#

@discord.ui.select(*, cls=discord.ui.select.Select[typing.Any], options=..., channel_types=..., placeholder=None, custom_id=..., min_values=1, max_values=1, disabled=False, default_values=..., row=None)```
A decorator that attaches a select menu 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 chosen select class.

To obtain the selected values inside the callback, you can use the `values` attribute of the chosen class in the callback. The list of values will depend on the type of select menu used. View the table below for more information.
unique geyser
#

I need help
I can't for the life of me figure out how bot voice stuff works
I'm using discord.py with discord.client

unique geyser
#

at this point, simply just make the bot join a voice channel

young dagger
#

!d discord.VoiceClient

unkempt canyonBOT
#

class discord.VoiceClient```
Represents a Discord voice connection.

You do not create these, you typically get them from e.g. [`VoiceChannel.connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.connect).

Warning

In order to use PCM based AudioSources, you must have the opus library installed on your system and loaded through [`opus.load_opus()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.opus.load_opus). Otherwise, your AudioSources must be opus encoded (e.g. using [`FFmpegOpusAudio`](https://discordpy.readthedocs.io/en/latest/api.html#discord.FFmpegOpusAudio)) or the library will not be able to transmit audio.
unique geyser
#

I tried reading through that, but I didn't understand what I needed to do

young dagger
unique geyser
#

ah

#

thank you

young dagger
young dagger
unique geyser
young dagger
#

!pypi pynacl

unkempt canyonBOT
#

Python binding to the Networking and Cryptography (NaCl) library

unique geyser
#

yup

young dagger
unique geyser
#
Traceback (most recent call last):
  File "/Users/[USER]/Repos/discord-bots/python-bots/squirrelbot.py/bot-env/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "/Users/[USER]/Repos/discord-bots/python-bots/squirrelbot.py/main.py", line 252, in on_message
    await channel.connect()
  File "/Users/[USER]/Repos/discord-bots/python-bots/squirrelbot.py/bot-env/lib/python3.11/site-packages/discord/abc.py", line 1898, in connect
    voice: T = cls(client, self)
               ^^^^^^^^^^^^^^^^^
  File "/Users/[USER]/Repos/discord-bots/python-bots/squirrelbot.py/bot-env/lib/python3.11/site-packages/discord/voice_client.py", line 238, in __init__
    raise RuntimeError("PyNaCl library needed in order to use voice")
RuntimeError: PyNaCl library needed in order to use voice
#

it says I need it

young dagger
#

Can you post the actual code?

unique geyser
#
if message.content == 'hey squirrelbot! join vc!':
            if message.author.voice:
                channel = message.author.voice.channel
                await channel.connect()
            else:
                await message.channel.send('You need to be in a voice channel to use this command.', reference=message)
young dagger
#

Is that the entire code?

unique geyser
#

for joining voice, yes

young dagger
#

I need the full code

unique geyser
#

of the bot?

golden portal
frigid estuary
#

!pastebin

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.

frigid estuary
#

https://paste.pythondiscord.com/52SA

Any1 available to help me with this help menu? For some reason its not organizing the commands into categories and its displaying them all on 1 page .-.

#

For reference im hosting it on railway.app from github

#

Pls dm me if u can because i dont want to miss any feedback in case im offline!

unique geyser
#

all good, found python3 -m pip install -U discord.py from the discord.py docs

golden portal
#

you need to include [voice]

unique geyser
#

I did

#

wait

#

no I didn't

#

ok so neither work if I add [voice], cool

golden portal
#

you're using the correct environment?

#

are you using venv

unique geyser
#

yeah

golden portal
#

did you activate the venv when you were installing the lib

golden portal
#

or did not activate it

unique geyser
#

it is active

golden portal
unique geyser
golden portal
#

now pip freeze

unique geyser
golden portal
#

then you didnt install it to your venv there

#

do pip install discord.py[voice] again

unique geyser
#

probably

golden portal
#

this is in linux right

unique geyser
#

macos

golden portal
#

oh nvm macos

golden portal
unique geyser
#

worked

#

thanks!

golden portal
#

can you connect now?

unique geyser
#

yeah

timid smelt
#

Hello.

#

Can anyone please tell me how to make all interaction commands not available via bot DM? I want my commands to only be used in servers

dense swallow
unkempt canyonBOT
#

@discord.ext.commands.dm_only()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that indicates this command must only be used in a DM context. Only private messages are allowed when using the command.

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

New in version 1.1.
brazen raft
#

I think they want guild_only actually

golden portal
#

!d discord.app_commands.guild_only

unkempt canyonBOT
#

@discord.app_commands.guild_only(func=None)```
A decorator that indicates this command can only be used in a guild context.

This is **not** implemented as a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check), and is instead verified by Discord server side. Therefore, there is no error handler called when a command is used within a private message.

This decorator can be called with or without parentheses.

Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.

Examples...
pine veldt
#

!f

#

!d

unkempt canyonBOT
pine veldt
#

!django

north kiln
#

#bot-commands for that

lime prism
north kiln
#

I mean you may attach a button to the message sent in the new channel

#

You should describe how the "system" is going to look like, what the user is expected to do

shrewd venture
#

Add a close ticket button to the embed on the start of ticket and make it so when user clicks it once it drops a confirm message

#

Id do it that way atleast

quiet kiln
#

is there anyone using some kind of ocr to extract item names & prices from receipts?

vast scroll
#

hello guys I have problem with my bot can anyone help me

slate swan
#

No, as you haven't asked any questions

vast scroll
#

how can I make my bot use reaction in .py

slate swan
#

what does that mean

vast scroll
#

like this

slate swan
#

!d discord.Message.add_reaction

unkempt canyonBOT
#

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

Adds a reaction to the message.

The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji).

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) to do this. If nobody else has reacted to the message using this emoji, [`add_reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.add_reactions) is required.

Changed in version 2.0: `emoji` parameter is now positional-only.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) instead of `InvalidArgument`.
vast scroll
#

thanks

dawn delta
#

how to make my bot send a message once every a fixated time?

glad cradle
dawn delta
#

yes

glad cradle
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, name=None)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop).
glad cradle
#

you can use this

frigid estuary
#

Boo ๐Ÿ‘ป

dawn delta
#

oh by any chance is it possible to inject the code into my alt account instead of my bot account ? or it would need a whole different code?

frigid estuary
glad cradle
dawn delta
lime prism
#

Hello ! I'm doing a ticket system with my discord bot. Here is my code : https://paste.pythondiscord.com/SOIQ
My code works but when a member creates a ticket, i want the name of the name of ticket with the reason. Exemple : if clyde opens a ticket by clicking "question" section, the name will be "ticket-clyde-question". And I want to add a message with the reason too. Please help me !

safe stag
#

I don't receive any direct messages and the channel isn't deleted ```py
@discord.ui.button(label="Close", style=discord.ButtonStyle.blurple, emoji="๐Ÿ”", row=1, custom_id="close_ticket")
async def close_ticket(self, button, interaction):
server_id = interaction.guild.id

    team_role_id = await db.get_teamrole(interaction.guild.id)
    if team_role_id in [role.id for role in interaction.user.roles]:
        server_name = await db.get_server_name(server_id)
        if server_name:
            channel_id = await db.get_log_channel(server_id)
            if channel_id:
                channel = await db.get_log_channel(interaction.guild.id)
                if channel:
                    ticket_opener = await db.get_ticket_opener(channel_id)
                    
                    embed = discord.Embed(
                        title="Close Ticket",
                        description="Deleting Ticket in less than `5 Seconds`... โณ\n\n"
                                    "_If not, you can do it manually!_",
                        color=discord.Color.dark_red()
                    )
                    await interaction.response.edit_message(view=self)
                    await interaction.followup.send(embed=embed)
                    
                    transcript = await chat_exporter.export(interaction.channel)

                    if transcript is None:
                        return

                    transcript_file = discord.File(
                        io.BytesIO(transcript.encode()),
                        filename=f"transcript-{interaction.channel.name}.html",
                    )

                    log_channel_id = await db.get_log_channel(server_id)
                    log_channel = interaction.client.get_channel(log_channel_id)

       
                    message = await log_channel.send(file=transcript_file)
                    link = await chat_exporter.link(message)

 
                    userembed = discord.Embed(
                        title="Your Ticket has been Closed",
                        description=f"Your ticket at {server_name} has been closed.\n"
                        f"```{interaction.channel.name}```\n"
                        f"You can find the transcript [here]({link}).",
                        color=discord.Color.blue(),
                    )
                    print("1")
                    if ticket_opener:
                        user = interaction.guild.get_member(ticket_opener)
                        if user:
                            try:
                                await interaction.user.send(embed=userembed)
                                await asyncio.sleep(5)
                                print("Deleting channel...")
                                await interaction.channel.delete()
                            except discord.errors.Forbidden:
                                print("Failed to send message to user (Forbidden)")
                            except discord.errors.HTTPException:
                                print("Failed to send message to user (HTTPException)")
                else:
                    await interaction.response.send_message("The ticket channel was not found.", ephemeral=True)
            else:
                await interaction.response.send_message("The channel ID was not found in the database.", ephemeral=True)
        else:
            await interaction.response.send_message("The server name was not found in the database.", ephemeral=True)
    else:
        await interaction.response.send_message("You do not have permission to close this ticket.", ephemeral=True)```
lime prism
#

my bot does not work?

slate swan
#

That doesn't look like a response to you, but rather a different issue the user is facing..

#

Error: AttributeError: module 'discord' has no attribute 'Intents'

My Code: ```
import discord

intents = discord.Intents.default()
intents.members = True

client = discord.Client(intents=intents)

Event handler for when the bot is ready

@client.event
async def on_ready():
print(f'Logged in as {client.user.name} ({client.user.id})')

client.run("my token is here")```

anything I do nothing seems to work literally

#

1.5.0

#

There's the issue

#

its way too low

unkempt canyonBOT
slate swan
#

I tried the newest version aswell

#

I just downgraded but I can retry

#

Install 2.3.2 and then it works

#

ok lemme see

slate swan
vapid parcel
#

okay so we have

@commands.has_guild_permissions
@commands.has_permissions

If they have the guild permission, is there a way to restrict the channel permission too? Because I might have to do a check for both possibly?

#

i don't really know how channel perms work, so thats why I am asking, even tho its a dumb question.

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
#

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

unkempt canyonBOT
#

@discord.ext.commands.has_guild_permissions(**perms)```
Similar to [`has_permissions()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_permissions), but operates on guild wide permissions instead of the current channel permissions.

If this check is called in a DM context, it will raise an exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage).

New in version 1.3.
slate swan
#

Similar to has_permissions(), but operates on guild wide permissions instead of the current channel permissions.

vapid parcel
#

You miss understood, or I explained bad.

what im asking is, in discord, if I have the guild permission to manage messages, aka delete messages, is there a way to restrict that perm from my role for a certain channel.

slate swan
#

Well yes, that's the overwrites?

vapid parcel
#

so then, its best to do a check for both correct?

slate swan
#

I would check both, unless you just care if they have a permission in that specific channel

#

e.g. users can create channels with the bot and then delete them as well, and your bot gives them the permission to manage channels only for that channel rather than the entire guild

vapid parcel
#

Well, im just wondering what would be best. Just checking if they have the perm in the guild, or if they have the perm in the guild + channel.

slate swan
#

Mostly depends on the use case

vapid parcel
#

alr. Just seeing how it should go.

#

But most bots just do the guild check correct?

slate swan
#

yep

vapid parcel
#

alr, thank you.

light night
#

For running a discord bot with docker

better as root, nonroot and then how do I keep file access and commands whatnot in there?

Except the webserver?

frigid estuary
#

Boo ๐Ÿ‘ป

safe stag
hushed galleon
# vapid parcel so then, its best to do a check for both correct?

if by checking both you mean applying both decorators you linked earlier, the @commands.has_permission() decorator automatically applies "guild permissions" (owner/administrator/roles) + overwrites for you, so mixing it with has_guild_permissions() is usually not necessary

vapid parcel
#

So its best to just use commands.has_permission?

hushed galleon
unkempt canyonBOT
#

discord/ext/commands/core.py line 2203

permissions = ctx.permissions```
`discord/ext/commands/context.py` line 479
```py
return self.channel.permissions_for(self.author)  # type: ignore```
`discord/abc.py` lines 672 to 677
```py
- Guild owner
- Guild roles
- Channel overrides
- Member overrides
- Implicit permissions
- Member timeout```
vapid parcel
hushed galleon
#

use the former if you want it to take into account the current channel they invoked the command from

vapid parcel
#

I think I will stick with guild, because idk many servers who use the channel perms. Maybe I am wrong.

#

Just confused on whats the best way of taking care of perms

hushed galleon
#

consider a purge command that deletes N messages in the current channel, should that command take into account overwrites or not? in other words, if someone is only allowed to manage messages in one channel but not in others, should they be allowed to use the command in that channel? (the reverse can also happen, i.e. someone whose roles allow them to manage messages except in one channel)

vapid parcel
#

Alr, I see what you mean

#

okay then

#

how can I improve my error handling to where it will handle if its a guild perm, or a channel perm.

I currently only have BotMissingPermissions and MissingPermissions, how can I make it to where the user knows where to change the permissions, because most people will think its just a role issue, instead of a channel issues in reality it was a channel issue.

hushed galleon
#

hmm, i guess you'd have to manually figure out why a permission isnt allowed, but its a bit complicated by has_guild_permissions() raising the same exception type as has_permissions(), plus the exception can contain multiple permissions that are missing

vapid parcel
#

well to make it easier, in the error, I should probably just tell them to check channel + guild permissions?

#

Because currently, this is how it would work, it just says the bot doesn't have permissions.

This is an example of only the bot not having permissions.

#

But I could enhance it by saying something like

Reminder, make sure to check the channel permissions and the server permissions or something along those lines, making sure the user checks both?

hushed galleon
#

though it would be inaccurate to bring up channel permissions if the decorator was has_guild_permissions()...

#

i would probably wrap has_guild_permissions to raise an inherited exception so its easier to tell them apart

vapid parcel
#

Hm, you would be right about that. I forgot to think abt that.

#

Error handling is complicated when you think about it, even tho its easy to do xD

hushed galleon
# hushed galleon i would probably wrap has_guild_permissions to raise an inherited exception so i...

for example: ```py
class MissingGuildPermissions(commands.MissingPermissions):
"""The user lacks guild-wide permissions to run a command."""

def has_guild_permissions(**perms):
predicate = commands.has_guild_permissions(**perms).predicate

async def wrapped(ctx):
    try:
        return await predicate(ctx)
    except commands.MissingPermissions as e:
        missing = e.missing_permissions
        raise MissingGuildPermissions(missing) from None

return commands.check(wrapped)``` references:

https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#checks
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.MissingPermissions

#

kinda feels like dpy should have had this exception type already, but i guess its not a frequent use case

vapid parcel
#

They should still have it imo

slate swan
dusk shadow
#

so... i need a tad bit of help...

if i get this result
<member 'user' of 'Interaction' objects> has requested to remove their Birthday from the server logs.
but i have this as the line of code...
optout_request_message = f"{discord.Interaction.user} has requested to remove their Birthday from the server logs. " \
my end function is to have the mention of the user that requested the command

dusk shadow
#

bro typing up a storm... 0_o

pale zenith
#

Heh

hushed galleon
#

ya im having a tough time writing a decent explanation for your question

hushed galleon
# dusk shadow so... i need a tad bit of help... if i get this result `<member 'user' of 'Inte...

it helps to learn more about object-oriented programming for this, but basically there's a difference between "classes" and "objects/instances" - Take petting cats for example: Cat would be called a class, and Walter would be an instance of that class. You can pet Walter because he is a physical being, but you can't pet Cat because it's merely a conceptual idea. The same goes for discord.Interaction, you can't write discord.Interaction.user because "Interaction" is merely a concept not associated with any command.

to clarify the distinction, here's a code snippet: py @bot.tree.command() async def greet(interaction: discord.Interaction): await interaction.response.send_message(f"Hello, {interaction.user.mention}!") discord.Interaction is a "class", and the variable interaction holds the actual interaction that has the user to be mentioned

dusk shadow
#

right, so If i wanted to use get the user mention, i had discord.Member, but had the same result.

hushed galleon
#

most of the things you see in dpy's documentation assume that you have an instance of that class

dusk shadow
#

cause i have this atm.
async def optout(ctx: discord.Member=None):
and im trying to use the discord.Member=None result as the member that used the command

pale zenith
#

You usually never access (or instantiate) the discord.Xxxxx classes that represent discord API models. But get them from discord.py by either means of command arguments, or methods that you call on the bot/client, or on other objects. like bot.get_guild, guild.get_role, etc

hushed galleon
pale zenith
#

(huh I can't react to this person's messages... Blocked I guess? Wasted effort typing sadge)

dusk shadow
#

yea, its an interaction.
well i did have it before, but removed it cause it was having troubles as well...

#

ooo, ok wait, i got somewhere

#

its just not an @ anymore

#

ctx.user
is what kinda fixed it, but i wonder if its ctx.user.mention?

hushed galleon
#

yeah, that should be valid

dusk shadow
#

AHHH

#

there we go, yep that did it...
so i was being funky in the head and dident do brain right

hushed galleon
#

if the variable ctx stores an Interaction object, that means it has a .user attribute containing a User/Member object, and both of those have a .mention attribute that gives you the string needed to mention that user, hence ctx.user.mention

dusk shadow
#

tyty!
sounds good :>

dawn delta
#

how do I add/enable discord.intents.message_content????

#

it still confuses me

golden portal
#

and then just pass this intents into the commands.Bot constructor, and enable message content in the developer page

dawn delta
golden portal
dawn delta
#

oh in there i thought in the check box, sorry. and thank you

safe stag
#

what is the plugin called?

dawn delta
#

working code

#

error code

#

what's different with it? i can't see anything wrong with it

#

and it doesn't even work??? ๐Ÿ˜ญ

#

can anyone help

#
@client.event
async def on_message(message):
     if message.content.startswith('+ping'):
        ping = message.content.replace("+ping ","")
        user_id = int(ping[2:-1]) # convert to int
        dm_member = await message.guild.get_member(user_id) # this function accepts an int
        pinger = message.author
        await dm_member.send('You got pinged by:')
        await dm_member.send(pinger)```
naive briar
#

Also, please send code as texts instead of screenshots

dawn delta
#

it doesn't have error code anymore

#

but

#

it doesn't work

#

is there anything different from

intents = discord.Intents.default()
intents.message_content = True```
and 
```python
intents = Intents.default()
intents.message_content = True```?
golden portal
dawn delta
#
from enum import member
import discord
from discord import Intents
from discord.ext import commands


# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = discord.Intents.default()
intents.message_content = True

client = commands.Bot(command_prefix="!", intents=intents)

@client.event
async def on_ready():
    print("Is logged in")

@client.command()
async def hello(ctx):
    await ctx.send("Hello!")

@client.command()
async def ping(ctx):
    await ctx.send("Pong")

@client.command()
async def shutdown(ctx):
    await ctx.send('Shutting Down The Bot')
    await client.close()

@client.event
async def on_message(message):
    if client.user.id != message.author.id:
        if 'burn' in message.content:
            await message.channel.send('them')

    await client.process_commands(message)

@client.event
async def on_message(message):
    if client.user.id != message.author.id:
        if 'who' in message.content:
            await message.channel.send('asked')

    await client.process_commands(message)

@client.event
async def on_message(message):
    if message.content.startswith('+ping'):
        mentioned_users = message.mentions

        if mentioned_users:
            user_id = mentioned_users[0].id
            dm_member = await message.guild.get_member(user_id)

            if dm_member:
                pinger = message.author
                await dm_member.send('You got pinged by:')
                await dm_member.send(pinger)
            else:
                await message.channel.send('User not found in the server.')
        else:
            await message.channel.send('Please mention a user to ping.')```
my bot broke after i add another `@client.event`, why?
naive briar
#

Consider using the command extension or listeners instead

naive briar
#

Which

dawn delta
#

both command extension and listeners

#

it's my first time heard of it

naive briar
#

And listeners are basically events, but you can have multiple of them

#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready)

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Example...
naive briar
#

Huh

#

Why is it exclusive to commands.Bot

slate swan
#

anyone know why this isnt letting me select my dir Ive tried using ai I tried looking for help on stack overflow nothing seems to help

@bot.tree.command(name="cd", description="Change directory.")
async def change_directory(interaction: discord.Interaction, directory: str = None):
    try:
        if directory is None:
            current_directory = os.getcwd()
            directories = [d for d in os.listdir() if os.path.isdir(d)]
            options = [discord.SelectOption(label=d, value=os.path.abspath(d)) for d in directories]

            print(options)

            select = discord.ui.Select(
                placeholder='Select a directory',
                options=options,
            )
            print("hi")
            view = discord.ui.View()
            view.add_item(select)
            print("hi2")
            await interaction.response.send_message("Please select a directory:", view=view)

        else:
            print("hi3")
            current_directory = os.getcwd()
            os.chdir(directory)
            new_directory = os.getcwd()

            files = os.listdir()
            file_list = "\n".join(files)

            response = f"Changed directory from '{current_directory}' to '{new_directory}'\n"
            response += f"Current directory files:\n{file_list}"
            print("hi4")
            await interaction.response.send_message(content=response)

    except FileNotFoundError:
        await interaction.response.send_message(content=f"Directory '{directory}' not found.")
    except Exception as e:
        await interaction.response.send_message(content=f"An error occurred: {e}")
north kiln
#

why would you ever want to do this?

#

anyone can use this command and do things to your machine

slate swan
north kiln
#

what does it look like after you used the command

north kiln
#

you can't see the options?

#

there isn't a callback so nothing happens after you select

wooden sail
#

Do you guys know how to recreate this

#

I meant the text that popped up when hovered

north kiln
#

it's probably a discord timestamp

golden portal
#

!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...
golden portal
#

it's just a string that discord recognize as a timestamp, so you can use this to convert your datetime

wooden sail
#

Oooh I have that I just can't figure out how can it have a hover popup

golden portal
#

it automatically have it

wooden sail
#

wait what lemme check my code

golden portal
#

<t:1709443285:F> = <t:1709443285:F>

wooden sail
#

Now my last question is how can I do a 5 years ago but still a timestamp

#

Do you guys have a documentation I can rwad on

#

I found a documentation thanks @golden portal

grand bobcat
#

how long does it take for slash commands to work properly?

naive briar
grand bobcat
naive briar
#

If you mean that only one of the two slash commands is showing, then it's because their function names are the exact same

grand bobcat
naive briar
#

That causes one to be overrided

grand bobcat
naive briar
#

!e

def func():
    print(1)

def func():
    print(2)

func()
unkempt canyonBOT
#

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

2
naive briar
#

The first function was overrided because the second one overrides its namespace

#

Idk how to explain more than that

grand bobcat
#

Okay thanks

hushed galleon
#

i think technically both might still be remembered by CommandTree, but either way if it did refresh properly, the second screenshot should have shown ciao2 in there...

#

assuming the commands were synced like normal, discord has recently been a bit slow with refreshing slash commands client-side, so restarting your discord app might fix it

drifting mantle
#

i have a scaling issue if anyone wants to be a gentleman and assist,

#

im at 18k servers and like 1.1m members, the bot main purpose is litening to presence event. i.e status updates, etc. so you could imagine the workload the bot is handling. i had a cache setup to cache data from DB on initial call for that server but it seems to be dogshit and after about 5-10 mins of bot being up everything gets blocked and it's impossible to figure out as when i test on a local server everything works fine but soon as i go to prod gg.

bleak summit
golden portal
bleak summit
#

but showing that only

golden portal
#

show the error again?

bleak summit
golden portal
#

you still have a file named discord.py there inside python codes folder

golden portal
drifting mantle
#

i've tried to use redis

drifting mantle
#

lmao

golden portal
#

did you use an async redis library?

drifting mantle
#

mhm

#

aiocache to be sepcific

golden portal
#

i see

#

i guess without code can't really suggest anythin

#

you're using sharding right

drifting mantle
#
async def on_presence_update(before: disnake.Member, after: disnake.Member):
    settings = await get_or_create_settings(after.guild)
    _embed = await get_or_create_embed(before.guild)


async def get_or_create_settings(guild: disnake.Guild):
    return await db_cache.get(f"guild_settings{guild.id}") or await guild_settings(guild)

async def get_or_create_embed(guild: disnake.Guild):
    return await db_cache.get(f"guild_embed{guild.id}") or await guild_embed(guild)
@cache(ttl=21600, key="guild_embed{guild.id}")
async def guild_embed(guild: disnake.Guild):
    data = await embed_model.get_or_none(guildid=str(guild.id))
    if not data:
        return
    return data

@cache(ttl=21600, key="guild_settings{guild.id}")
async def guild_settings(guild: disnake.Guild):
    data = await guild_model.get_or_none(id=guild.id)
    if not data:
        return
    return data

and yes

#

im sharding w clusters

#

now just imagine on_presence_update being spammed and ungodly amount of times

golden portal
#

do you get the "can't keep up" warning logged?

drifting mantle
#

nah and just to be safe incase logs were broke, cause they typically do break and not show shit. i've upped the shards/clusters multiple times

#

rn its at 10 shards a cluster with 7 clusters

#

and im pretty sure thats overkill tbh

#

i've had it at 7 clusters 5 shards for a while, then one day the main feature which adds a role to a user when they add a specific status stopped working

golden portal
#

hmm, since this is disnake i'm not entirely sure if they did an adequate performance test, maybe you can ask in their server or something

sick birch
#

also presence events are typically the most demanding besides typing events

#

especially at scale, cause there's just so much

#

imagine how many people are changing their profiles across 1m+ people per second

drifting mantle
#

yeah ik it's cancer, was doing good for awhile and i've finally hit a wall

ancient raven
#

I am using a webiste api and it worked for me fine till now. They added human verification to it so I cant scrape info using a VPS but it works on my local pc. Any solutions ? This is for my discord bot

slate swan
#

!rule 5

unkempt canyonBOT
#

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

slate swan
#

Scraping likely violates the terms of services of said website, like many others, and isn't an actual API for bots to be used, otherwise they wouldn't add a human verification to that "API", doesn't make sense.
We won't help

tiny coyote
#

is it possible to create a coundown on discord.py without using Datetime.now() or discord.utils

tiny coyote
golden portal
#

did you even use aware datetime ones? discord.utils.utcnow() because you're supposed to use this with format_dt to show it correctly, the whole point of discord timestamp is to show time according to user's locale timezone

tiny coyote
#

hmmm

tiny coyote
golden portal
#

!d discord.utils.utcnow

unkempt canyonBOT
#

discord.utils.utcnow()```
A helper function to return an aware UTC datetime representing the current time.

This should be preferred to [`datetime.datetime.utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow) since it is an aware datetime, compared to the naive datetime in the standard library.

New in version 2.0.
tiny coyote
#

i realised Ive written discord.utils.format_dt.utc() and not discord.utils.utcnow()

quaint epoch
tiny coyote
#

it still says 4 hrs for others but i see 1m

civic sparrow
#

how can i have an argument in an app command have a list that will change to show results based on whatever i type in?

#

its a very large dataset

#

and i want to perform the lookups on disk with my sqldatabase which holds all the info

grand bobcat
#
@commands.is_owner()
    @bot.tree.command(name="give", description="Gives roles")
    
    async def add_role(interaction:discord.Interaction,ctx: commands.Context, role:discord.Role, member: discord.Member):
        await member.add_roles(role)
        embed = discord.Embed
        embed(title="Success!",
              description=f"Added {role} to {member}.",
              color=GREEN_COLOR_Sucess)
        await ctx.send(embed=embed)```
is this correct?
slate swan
grand bobcat
#

oh fr?

slate swan
#

Nevermind, doesn't seem to

#

Just know it checks if the user is the owner of bot, not server

dapper cobalt
#

What does TypeError: issubclass() arg 1 must be a class mean in slash subcommands?

@parent_roles.sub_command(name="add-parent-role", description="Add a new parent role")
@guild_exists()
async def add_parent_role(self, inter, role: disnake.Role, *, roles: list[disnake.Role]):
    await new_parent_role(inter.guild.id, role, roles)
    await inter.send(f"**{role.name}** has been set as a parent role to roles:\n{', '.join(role.name for role in roles)}")
pale zenith
#

(aka, include the traceback, not only the error text)

#

if you're not using issubclass yourself, this may be a problem with the library you're using, 'disnake', but I am unfamiliar with it.

dapper cobalt
#
cogs.ranks is failed to load:
Ignoring exception in on_ready
Traceback (most recent call last):
...
  File "D:\dbots\rankmaster\cogs\ranks.py", line 7, in <module>
    class Ranks(commands.Cog):
  File "D:\dbots\rankmaster\cogs\ranks.py", line 32, in Ranks
    async def add_parent_role(self, inter, role: disnake.Role, *, roles: list[disnake.Role]):
...
TypeError: issubclass() arg 1 must be a class
#

That's pretty much the only useful info from the traceback, the other is just the roots of the error

dapper cobalt
pale zenith
dapper cobalt
#

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

pale zenith
#

thanks

dapper cobalt
#

np

#

it appears that only the subcommand add_parent_role is the only one raising that error. I have other subcommands, however, they don't raise it.

#

Probably cuz it's a subcommand group?

pale zenith
# dapper cobalt it appears that only the subcommand `add_parent_role` is the only one raising th...

the error appears to be that disnake is failing to parse the annotation of the parameters of the function, and internally, it is passing an instance to issubclass rather than a type. (?)

I'm not sure if it has to do with this annotation: https://leo.might-be.gay/ZXRA6X.png discord.py's slash commands do not support it, and maybe the bug is from the handling of that? I am honestly unsure because this codebase varies wildly from the discord.py one which I am familiar with

dapper cobalt
#

I found the issue. I tried removing roles: list[disnake.Role] from the function's parameters, and it doesn't raise the error anymore.

pale zenith
#

oh yup figures

#

funny how we sent that like at the same time

dapper cobalt
#

lol, well what's a way to give multiple values to the same parameter in slash commands?

dapper cobalt
#

maybe i can make it as one argument, but provide instructions for the user to separate them with a comma, and in the code I'd just use split()?

pale zenith
#

that would probably be the only way. variadic arguments are not a thing that discord supports

#

though I guess *, usually means single varying-length parameter, not multiple.

dapper cobalt
#

ddev is just testing my patience at this point lmao

pale zenith
#

also, lol, that's one hell of an error to give out when passing an unsupported annotation lol

pale zenith
pale zenith
frigid estuary
#

I feel like its a symple fix but idk

#

.-.

pale zenith
frigid estuary
#

yes

pale zenith
#

possible reasons,

  • you have two instances of the bot running
  • you are calling Bot.process_commands more than once
#

does this occur with all commands, perchance?

frigid estuary
#

no just that one

#
intents = discord.Intents().all()
bot = commands.Bot(command_prefix="Echo_", intents=intents, case_insensitive=True) 
status = variables = [
discord.Game(name='StarMade'),
discord.Activity(type=discord.ActivityType.listening, name='Spotify'),
]


@bot.event
async def on_ready():
    create_database()
    print('Successfully logged in as {0.user}'.format(bot))
    bot.add_cog(messageModule(bot))
    bot.add_cog(memberModule(bot))
    bot.add_cog(weatherModule(bot))
    bot.add_cog(channelModule(bot))
    bot.add_cog(HelpModule(bot))
    bot.add_cog(ModerationModule(bot))
    bot.add_cog(reminderModule(bot))
    await bot.change_presence(status=discord.Status.online, activity=discord.Game('Starting...'))
    await asyncio.sleep(5)
    status_cycle = cycle(variables)
    while True:
      current_status = next(status_cycle)
      await bot.change_presence(status=discord.Status.online, activity=current_status)
      random_delay = random.uniform(30, 600)  
      await asyncio.sleep(random_delay)
      
bot_token = os.environ.get('TOKEN')
bot.run(bot_token)
#

thats the main file

pale zenith
#

oh my god

frigid estuary
#

how come it works for every other command

pale zenith
#

honestly, I couldn't tell you

#

I assume you have two instances of the bot (two scripts running at the same time)

frigid estuary
#

no i dont

#

so what could i use instead of on_ready (while still suing async)

pale zenith
#

a while true will not work in the setup hook, you could use a task for that instead, though. For the rest, you use setup_hook.

#

for your issue, can you try resetting your bot token from the panel, and using the new token when running the bot?

frigid estuary
#

sure

#

๐Ÿ˜ฎ

#

now its working!!!

frigid estuary
#

but why did it do that

pale zenith
#

unsure why it only bugged for that one

frigid estuary
pale zenith
#

consider implementing the rest of the above things that were pointed out, (extensions, using setup_hook)

frigid estuary
#

i will... now i just have to get the menu to display the command briefs and names under the categories...

pale zenith
#

good thing about extensions is that you can use bot.(load/reload/unload)_extension to not have to restart the whole script every time you modify a Cog

frigid estuary
#

๐Ÿ™‚

pale zenith
pale zenith
frigid estuary
#

i will be implementing that in the next major bot update tysm

pale zenith
#

(yes my brain is just a conglomerate of random URLs of helpful(ish) things depressed_fumino)

frigid estuary
#

๐Ÿ™‚

rotund wagon
#

How do I hosted my bot 24/7

pale zenith
#

you will need knowledge of the linux command line but yeah

frigid estuary
#

its free ๐Ÿ™‚

rotund wagon
#

Hmm

frigid estuary
#

(im using it rn)

rotund wagon
#

And I only need the code?

frigid estuary
#

yes

#

have your code in a repository on github and then connect it ๐Ÿ™‚

rotund wagon
#

If the repository on github is private will it still work?

frigid estuary
#

i think so, you might just need a security key

rotund wagon
#

Okay, since the token is in the code it can't be public

frigid estuary
#

also, there are variables enabled to put sensitive information like tokens etc

#

i have mine public but the token is in a variable that only i can access

#

btw if your bot uses imports you'll need to make a requirements.txt file

rotund wagon
#

Idk how to do that, yes it does

rotund wagon
#

It's 5 per month

frigid estuary
#

no

#

im using it for free

pale zenith
latent jay
#
async def extract(interaction: discord.Interaction, channel: discord.TextChannel) -> None:
    if channel is not None:
        history = [message.content async for message in channel.history(limit=None)]
        print(len(history))
    else:
        await interaction.response.send_message("**Ensure you specify a channel!**")

Only returning 100 messages, anyone know the issue?

young dagger
latent jay
pale zenith
#

That does not seem right

#

Should give you all messages

#

Have you saved the file?

latent jay
#

yes

golden portal
#

unless you redacted some code, i also can't repro that

latent jay
#

is there some sort of limitation from when the message was sent?

#

LIke how you can't delete messages older then 14 days? I thought you'd still be able to read them

golden portal
#

there isnt a limit tbh, i've gathered up to 14mil messages on a textchannel that goes back to 2018

latent jay
#

soo am I doing it wrong or

#

Ok LOL wtf

#

discord must've been broken the last time I wrote that code

#

Cause now it's working fine ๐Ÿ˜ญ

grand bobcat
#

!e

unkempt canyonBOT
#
Missing required argument

code

#
Command Help

!eval [python_version] <code, ...>
Can also use: e

Run Python code and get the results.

This command supports multiple lines of code, including formatted code blocks. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.

The starting working directory /home, is a writeable temporary file system. Files created, excluding names with leading underscores, will be uploaded in the response.

If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside them.

Currently only 3.12 version is supported.

We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!

lyric solar
#

!e print("")

unkempt canyonBOT
#

@lyric solar :warning: Your 3.12 eval job has completed with return code 0.

[No output]
lyric solar
#

!e
import requests
e = requests.get("google.com")
print(e.text)

unkempt canyonBOT
#

@lyric solar :x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     import requests
004 | ModuleNotFoundError: No module named 'requests'
lyric solar
#

๐Ÿ˜ก

#

!e
import subprocess
subprocess.check_call("python3 -m pip install requests")

unkempt canyonBOT
#

@lyric solar :x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 2, in <module>
003 |     subprocess.check_call("python3 -m pip install requests")
004 |   File "/lang/python/default/lib/python3.12/subprocess.py", line 408, in check_call
005 |     retcode = call(*popenargs, **kwargs)
006 |               ^^^^^^^^^^^^^^^^^^^^^^^^^^
007 |   File "/lang/python/default/lib/python3.12/subprocess.py", line 389, in call
008 |     with Popen(*popenargs, **kwargs) as p:
009 |          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
010 |   File "/lang/python/default/lib/python3.12/subprocess.py", line 1026, in __init__
011 |     self._execute_child(args, executable, preexec_fn, close_fds,
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/I6PR23BF2ELK4MCO4FAA2MBJ5A

lyric solar
#

๐Ÿ˜”

shut lagoon
#

Ive a query regarding my discord bot, It works as follows

  1. Gets a message with image
  2. Sends it to my tensorflow api and recognizes it
  3. Sends the name to the channel

Now the issue comes when various channels spam it at the same time, I would like it so it goes

Processes 1 image, sends the name
waits 0.3 seconds
Processes 2nd Image, sends the name
waits 0.4 seconds

But it goes

Processes all 20 images, sends all 20 names at once. Which results in ratelimit. Can someone help?

vale wing
shut lagoon
vale wing
#

Yeah queue then

#

You didn't mention channels are different at first

shut lagoon
#

yep thankyou

vale wing
#

Could someone link that gist guide on slash commands in dpy

pale zenith
upbeat otter
pine veldt
#

I want to create a hidden secrets command that will not shows to anyone and only for owner command. That CMDs shows the list of all server that is bot currently is

pine veldt
#

@pale zenith

vestal acorn
vale wing
slate swan
pine veldt
vale wing
#

Idk the decorators for hybrid commands

#

!d discord.ext.commands.is_owner defo works for message commands, no idea whether it works for hybrids

unkempt canyonBOT
#

@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that checks if the person invoking this command is the owner of the bot.

This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.is_owner).

This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NotOwner) that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).
vale wing
#

Dpy is bad โ˜บ๏ธ

north kiln
#

no way to actually hide it from the commands list

#

if it is a slash command

vale wing
north kiln
#

permissions can still be changed

pale zenith
#

yeah that's the unfortunate reality

#

The is_owner check pointed above should work for hybrid commands, but this will only make it raise an error in-code, and not hide it in the discord UI. Unfortunately due to how discord slash commands work, you can only restrtict slash commands through permissions (or through NSFW/[guild/dm]_only). If you want a command that can only be seen by a person you will need to

  • make it a guild command
  • go into server settings and change the permissions from within the integrations tab
    And even then, people with administrator permissions will bypass those permission restrictions
#

having an owner-only command globally does not make sense in the context of a slash command. It's better to stick with prefix commands for those

#

@pine veldt ^

pine veldt
#

Hmm

young dagger
#

I switched back to Ubuntu since I wanted to try out Docker. So now all my Discord bots have been running on Docker for a couple of days with no issues whatsoever, everything is running just fine. Thanks for the help!

sick birch
#

Docker based

split vessel
#

yeah I have been hosting 2 Bots on the same VPS (Vultr) on Debian for over a month and they did not face any issues

split vessel
nova hawk
#

How do i fix that i want it to @ a user

slate swan
#

Remove the &

cloud pulsar
#

^

split vessel
worthy comet
#

what am i doing wrong here?

#

following a tutorial and it went south

shrewd vapor
#

Hello guys, i need help with permission overwrite for a voice channel

#
overwrite.view_channel = True
overwrite.connect = False
await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)```
#

Idk why everyone can connect to the channel

sick birch
sick birch
shrewd vapor
#

Its fixed now, i have just put the overwrite in the create_voice_channel

#

I just need to rewrite all my bot for try to understand and use the await database

twilit grotto
#

!intents

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

shrewd vapor
#
overwrite = discord.PermissionOverwrite()
overwrite.view_channel = True
overwrite.connect = False
channel = await ctx.guild.create_voice_channel(name = f"๐Ÿ‘ฅ Member Total : {len(ctx.guild.members)}", position = 0)
await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)```
uneven granite
#

Im currently running my own dedicated minecraft server, would it be too much of a resource hog to also run a discord bot on the same machine?

sick birch
#

probably not

#

discord bots are light

supple locust
#

How come I have to reinvite my discord bot to my server each time I add a new slash command?

naive briar
#

No?

hard kite
#

Someone can help me a bit?

shrewd apex
#

ask away

turbid condor
#

@slate swan i think u can edit it

#

!d discord.VoiceChannel.edit

unkempt canyonBOT
#

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

Edits the channel.

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

Changed in version 1.3: The `overwrites` keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.

Changed in version 2.0: The `region` parameter now accepts [`str`](https://docs.python.org/3/library/stdtypes.html#str) instead of an enum...
slate swan
#

ah interesting ill try thanks

vale wing
hard kite
#

Uhm why I got error when I try adding Boolean annotation as params??

naive briar
#

!traceback show the error

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

nocturne hedge
#

https://paste.pythondiscord.com/KQ2A

Prior to this code being excuted it players use !q to que for a lobby, once the lobby reaches 4 people it will create a Lobby voice channel with there que id matching. (THIS IS WORKING)

However the code I am showing you is not, it should

  • Once all 4 members join the lobby VC
  • Annouce the random reason Team 1 & Team 2
  • Create team 1 and team 2 voice channels
  • Move the players to their teams voice channel
  • Delete the lobby voice channel

any ideas?

north kiln
#

what actually happens then

ocean thistle
#

hi who can help me to type this code is so urgencly please

golden portal
upbeat otter
ivory viper
#

Hi is there anyone that knows good python i need help in my bot

#

Dm if u know

river plank
#

can you have buttons in an ephemeral message?

#

if so how?

ivory viper
#

Yo

#

Are u good in python?

#

@river plank

slate swan
unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send) for non-interaction contexts.

For interaction based contexts this does one of the following...
slate swan
#

to the send method just add your view as a kwarg
and also make ephemeral kwarg True

river plank
#

oh

river plank
slate swan
#
class YourView(discord.ui.View):
    def __init__(self):
        super().__init__()

    # Create your buttons there


@commands.command()
async def foo(context: commands.Context):
    await context.send("hello!", view=YourView(), ephemeral=True)
#

but you should really use slash commands
if you want the message to be visible only
for the author

river plank
#

oh

#

right thanks

river plank
slate swan
#

I don't think it will be visible only for
the author in this case but you might
ask someone more experienced

turbid condor
river plank
#

ah crap

turbid condor
slate swan
turbid condor
#

Context.send doesn't have ephemeral param

river plank
#

oh darn

vestal acorn
#

it has, but only in specific cases

#

for security, it is better to use it only with app_commands

slate swan
#

It shouldn't error anyways afaik pithink

#

It would send the message but visible to everyone

turbid condor
slate swan
#

I'd have to try that later

turbid condor
#

Yeah do tell me what happens

slate swan
#

I tried it and it doesn't error

#

But the message is shown to everyone so yeah

turbid condor
#

Ah thx for telling

#

I'm gonna try when i get online

formal valve
#

Hi, gotta start my discord bot for automatic1111.
Where do I start? Any leads?

shy haven
#

how do i invite my bot to the server? under oauth2 when i select bot > administrator it then states that i require a redriect url - how od i do this?

#

i solved it, i just created a new application

shy haven
#

to make a bot?

#

go to like discord.com/developers or something like that and create a new application, then go to the bots section

#

enable the required intents and stuff

#

then go to oAuth2 and select bot and then the permissions before adding it to ur server

#

from there you can go back to bot and copy the token id

#

from here start coding using that to do "stuff" with your code

turbid condor
shrewd vapor
#

Hi, sorry to bother you but i try to use mysql async on my bot but i'm really lost in the doc of mysql with that

#

I don't understand how to do it, and the white website burns my eyes lol

sick birch
#

it won't ask for redirect URL if the only thing you have selected is "bot"

slate swan
#

why is line 3 and 10 red

sick birch
dusk shadow
# slate swan why is line 3 and 10 red

line 3
you dont have the envrioment module being used, and line 10 is telling you that that value is invalid.
SERVER_ID is where you put your guild ID. (how you have it right now, the brackets are trying to take an Int numerical value, instead of a string value. for a string value, do debug_guilds=["MYGUILD"] and that would be a string value instead.)
you also dont specify a .env file to load on start. so it would be pointless to have those lines in there :>

#

you need a line before or after any events called
load_dotenv()
i would put that around line 7 or so

#

so it would look a little like

load_dotenv()
TOKEN = os.getenv('token')

You also need a file in the same directory called ".env" and have it formatted correctly for your bot to see it

#

The .env file would include the following line

token= "YOUR_BOT_TOKEN"

and thats about it.

hard kite
#

Why error when I use param name with caps?

#

Like "doDm" = bad ,"dodm" = good

upbeat otter
#

what's the error otherwise?

hard kite
#

I don't get what it wanna say

upbeat otter
#

just screenshot it?

copper quartz
#

good morning

copper quartz
hard kite
#

I am saying why I got error when I use parameter name with caps

#

And why it's a thing

copper quartz
#

'word' and 'Word' are two different strings, the same rules for strings are in place for keyword argument names

hard kite
#

"parameter name"

copper quartz
#

yes, those are strings

hard kite
#

Eh

hard kite
copper quartz
#

under the hood yes

hard kite
#

Also I talk here cus it's about discord bot

#

I am saying why I can't use parameter name with caps on it

copper quartz
#

arg and ARG would be two different arguments

hard kite
hard kite
#

What argument with cap will mean?

#

I mean what's the difference of parameter with cal and without

copper quartz
#

means nothing, its just a different name.

hard kite
#

Bru

hard kite
copper quartz
# hard kite Ofc n != N

well im glad we understand each other, if you wonder about something else i do not understand you, maybe you could explain it more clear

hard kite
#

I am saying when I use parameter without caps it works good but it didn't when I use with caps@copper quartz

copper quartz
#

i dont know the function signarture your using

#

but you must follow the signature

#

maybe you could share what your doing so it is more clear to me

hard kite
#
def a(arg):
  pass
```this works

```py
def a(Arg):
  pass
``` this didn't work
hard kite
#

I am using treecommand

#

But using argument with caps don't like to register

#

I want something like sendDm

#

But the error faulting that

copper quartz
#

did you change the case_insensitive part first?

upbeat otter
copper quartz
upbeat otter
#

pretty sure it doesn't

hard kite
#

Am too confused to this as I know logically param with caps on its var name has no difference with one without

hard kite
copper quartz
#

without it you have to use lowercase

upbeat otter
#

idts that discord provides upper case params anyways

hard kite
#

What feature ๐Ÿฅฒ

copper quartz
#

case insensitive

hard kite
#

What it does?

copper quartz
#
Whether the commands should be case insensitive. Defaults to False. This attribute does not carry over to groups. You must set it to every group if you require group commands to be case insensitive as well.
hard kite
#

So am stuck on lowercase huh ? ๐Ÿฅฒ

copper quartz
#

yes, discord.py overwrites a lot of python behaviour with their framework, without this feature you are stuck

hushed galleon
# copper quartz https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.com...

awkwardly this does not apply to slash commands but its not clear what the error was, if anything i would assume that it was from the discord API telling them uppercase characters aren't allowed:
https://discord.com/developers/docs/interactions/application-commands#application-command-object

CHAT_INPUT command names and command option names must match the following regex ^[-_\p{L}\p{N}\p{sc=Deva}\p{sc=Thai}]{1,32}$ with the unicode flag set. If there is a lowercase variant of any letters used, you must use those. Characters with no lowercase variants and/or uncased letters are still allowed. USER and MESSAGE commands may be mixed case and can include spaces.

copper quartz
#

thanks for the clearification, was not aware it was on the API side, thought it was handled by inspecting the co varnames with a regex

hushed galleon
unkempt canyonBOT
#

discord/app_commands/commands.py lines 190 to 194

match = VALID_SLASH_COMMAND_NAME.match(name)
if match is None:
    raise ValueError(
        f'{name!r} must be between 1-32 characters and contain only lower-case letters, numbers, hyphens, or underscores.'
    )```
shrewd apex
#

discord.py validates it client side before sending it to discord

#

yeah

hard kite
#

๐Ÿ˜ญ

formal valve
#

So I'm creating a text to image bot.
So far it works.
I want these height width field to be optional and model to be selected from a drop down. How do I do that?

naive briar
# formal valve So I'm creating a text to image bot. So far it works. I want these height width...

For the optional options, you can give them their default values in the parameters, and Discord will make them optional, like so:

@tree.command()
async def command(inter, height: int = 720, width: int = 720):
ย  ย  ...

And for the model drop-down, a simple way is to use the typing.Literal, like so:


from typing import Literal


@tree.command()
async def command(inter, model: Literal["Model-One", "Model-Two"]):
ย  ย  ...

You can see other ways in the example file

GitHub

An API wrapper for Discord written in Python. Contribute to Rapptz/discord.py development by creating an account on GitHub.

turbid condor
naive briar
#

Probably, never tried it

formal valve
#

Thanks. I will try it today.
Also,How do I learn this stuff?
I come from a non CS background.

turbid condor
#

learning OOPs will make the journey on dbots a lot easier

#

otherwise you will get stuck when you venture deep into it

hard kite
#

How I'll add premade options?? Like I want the user to only use those options for treecommand?

hard kite
#

What literal and optional does?

#

Wait I remember them from the documentation of the discord.ext

formal valve
silent nest
#

i am facing unknown interaction error, what are the possible reasons
i checked and the command is synced and it was working fine yesterday

#

the only thing i can think of is
maybe the code in command is taking a while to execute so the interaction expires or something? idk if something like that exists

silent nest
silent nest
#

okay sure

#

okay thanks

#

this should work ||(worked fine)||

turbid condor
#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

turbid condor
river dawn
#

I had a quick question! Could I add micro-transactions into my discord bot?

#

I have a server with a currency and I want to sell it for real money, but is there a way to make a page where users can buy it and when the money comes trough the bot gives them the currency?

golden portal
#

find a payment gateway service, like RazorPay, etc and then find a wrapper lib for it so you can use it with your bot

turbid condor
#

or work with raw api if you can

red blade
#

When using the discord.py slash commands how can you add a description for a parameter?

vestal acorn
#

!d discord.app_commands.describe

unkempt canyonBOT
#

@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.

Example:

```py
@app_commands.command(description='Bans a member')
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
    await interaction.response.send_message(f'Banned {member}')
```  Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings...
river dawn
turbid condor
#

API = Application Programming Interface

red blade
shrewd vapor
#

Hi, sorry to bother you but i try to use mysql async on my bot but i'm really lost in the doc of mysql with that
I don't understand how to do it, and the white website burns my eyes lol

supple locust
#
@tree.command(description="Send a dm to a member")
async def say(interaction: discord.Interaction, recipient: discord.Member, content: str) -> None:
    await recipient.send(content)
    await interaction.response.send_message("Command succeeded!", ephemeral=True)


@say.error
async def say_err(interaction: discord.Interaction, error: discord.app_commands.AppCommandError) -> None:
    ...
    )```
Hey, I was curious if there was a better way to handle errors than using the `command_name.error` decorator. It just seems like a really verbose way of doing it. Also curious while I'm here if I can do something similar to `commands.Cogs` while just using `discord.Client`? I want to separate my bot into multiple files to make it easier to organize
#

Oh wait, could I just use multiple ComandTrees?

#

One for each file, but then import them and then sync them all in my on_ready?

slate swan
#

pithink why would you need multiple CommandTree's

supple locust
#

Well, I'm asking if I could modularize the bot

#

Specifically discord.Client

#

seeing as cogs are apart of discord.ext.commands

slate swan
#

About the cogs with discord.Client, im pretty sure that you can't do that

supple locust
#

That's what I said

slate swan
#

thats why most people consider using commands.Bot

supple locust
#

It feels like you're avoiding answering my question, and just telling me to use something different

#

I'm going to try the approach with multiple command trees and get back to you

sick birch
#

the best option you'd have is to import a single client tree around

sick birch
slate swan
#

Also syncing in on_ready is not the best way
as it can be called multiple times

supple locust
#

In this case, it'd be a couple commands. I have a few that could potentially raise discord.Forbidden because of a user's private messages settings @sick birch

sick birch
slate swan
#

I suppose it would be making a normal command
for syncing just like This One

sick birch
supple locust
#

Should I be using commands.Bot instead? I was trying to avoid using prefix commands

supple locust
sick birch
supple locust
#

Gotcha, well thank you guys

#

Very informative

sick birch
#

also if you don't use any prefix commands at all you can just disable the messages intents

#

so that way you don't have to process messages at all

#

as far as discord.py is concerned nobody is sending any messages

supple locust
#

Ah, but I'd still need the messages intent if I wanted to do anything with reactions though I'd assume

sick birch
#

good question. not entirely sure, i haven't tested it

supple locust
#

One more question actually

#

If I need to create a command to sync, but I need to sync have access to all my commands, how does that work?

#

I must be misunderstanding something about that

sick birch
#

for a sync command you just need to sync it once initially

#

sync commands don't change all that much

#

or a prefix command

supple locust
#

Ah okay thank you very much

polar mural
#

Anyone is willing to begin a new discord bot project (I don't have anything in my mind we can create anything)

pale zenith
#

lol

#

<3

supple locust
#

nah you saved me like

#

so much suffering

pale zenith
#

good on you for actually using the search feature pats most people don't

slate swift
#
async def serverinfo(ctx, interaction: discord.Interaction):
    server = ctx.guild
    embed = discord.Embed(title=f"Server Information - {server.name}", color=0x3498db)
    embed.set_thumbnail(url=server.icon_url)
    embed.add_field(name="Server ID", value=server.id, inline=False)
    embed.add_field(name="Owner", value=server.owner.mention, inline=False)
    embed.add_field(name="Member Count", value=server.member_count, inline=False)
    embed.add_field(name="Text Channels", value=len(server.text_channels), inline=True)
    embed.add_field(name="Voice Channels", value=len(server.voice_channels), inline=True)
    await interaction.send(embed=embed)```
Why doesnt this work
supple locust
#

because interaction doesn't have a send() method

#

so interaction.send() isn't gonna work

#

sorry if i sound a bit gross, I'm super sick and I'm on the verge of coughing after every word

#

@slate swift

slate swift
# supple locust
@app_commands.describe(thing_to_say = "What will you suggest?")
async def suggest(interaction: discord.Interaction):
    if ctx.channel_id != allowed_channel_id:
        embed = discord.Embed(title=f"{interaction.user.name} Suggested!", description="They suggested {thing_to_say}")
        await interaction.response.send_message(embed=embed)``` 

i have this code now but you said i shouldnt use ctx now my `if ctx.channel_id` is a error
supple locust
#

interaction.channel_id

slate swift
# supple locust `interaction.channel_id`
    @bot.tree.command(name='suggest', description='test some')
     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\dynam\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\app_commands\tree.py", line 887, in decorator
    command = Command(
              ^^^^^^^^
  File "C:\Users\dynam\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\app_commands\commands.py", line 666, in __init__
    self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
                                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\dynam\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\app_commands\commands.py", line 389, in _extract_parameters_from_callback
    _populate_descriptions(result, descriptions)
  File "C:\Users\dynam\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\app_commands\commands.py", line 277, in _populate_descriptions
    raise TypeError(f'unknown parameter given: {first}')
TypeError: unknown parameter given: thing_to_say```
supple locust
#

the error is this

slate swift
supple locust
#

What app_commands.describe do?

supple locust
slate swan
#

ah sorry

slate swan
slate swan
pale zenith
#

holy it is my number two fan

formal valve
#

So how do you guys add time out for discord functions?
I am making a txt2img bot now and will add more functions to it. That may take about a minute to respond.

turbid condor
#

!d discord.ext.commands.cooldown

unkempt canyonBOT
#

@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command)

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType).

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown) is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error) and the local error handler.

A command can only have a single cooldown.
formal valve
#

Isn't cooldown for limiting users to send messages?
That's great too.
But I guess it has to be something about time-out. No?

formal valve
#

This is something I found

turbid condor
#

That's deferring

#

It's type of response

formal valve
#

Alright. Let me read up the documentation

turbid condor
#

Using this is just to avoid an error that occurs during command that take long time to complete

formal valve
#

Here's my function

turbid condor
#

There is a 3 sec time window in which u have to respond to a interaction and defer is a response so that solves the issue and then within the next 15 min u can send your actual output using interaction.followup.send()

turbid condor
#

Since image gen takes more than 3 sec

formal valve
turbid condor
#

And I'd say also implement a cooldown so that not too many prompts are given to be generated at same time

formal valve
#

Does discord bot handle concurrent requests and queue them? Or should I be coding it myself?

formal valve
turbid condor
#

It handles them concurrently

#

That's the whole point of being asynchronous

formal valve
#

Perfect. Thanks man. You have been a great help

turbid condor
#

Then it won't need defer

formal valve
#

@turbid condor what do you mean prefix command?

turbid condor
#

Opposite of slash?

#

That uses a prefix like !help

#

If yes then u can't defer it

formal valve
#

No, it's a slash command

turbid condor
#

Deferring is for hybrid or slash only

turbid condor
formal valve
#

Pycord

turbid condor
#

Ahh i see

formal valve
turbid condor
#

It's just ctx is confusing as it's mostly thought of as context instead of interaction

turbid condor
#

Or you can do it by sending an initial response with a message like "Generating Image. Please wait..."

#

And then send followup or edit the original response when image is completed

formal valve
#

That's a cool idea.
Let me try it.

#

So it's fixed. Thank you man.
Can I DM you if I need any further help?

turbid condor
fringe pine
#

Hi, I've been using pycord's ApplicationContext for my bot. Is it possible to migrate to discord.py without much changes? Also i would like to know if there are major performance deficits between these libs. or if there is another alternative

naive briar
#

They have different ways to create app commands, so you'll need to rewrite a considerable amount

#

Don't know about performance difference though

pale zenith
#

The easiest way to migrate is to use discord.py's hybrid_commands (docs), which take a commands.Context and register an app command and a message command at the same time

#

if you don't want the message commands part, you'd simply not enable the message content intent.

#

the one disadvantage of this, though, is that since they are hybrid, some interaction-only features are not to be found in the Context class. Like interaction.response.send_modal, or interaction.response.edit_messages, there is only ctx.defer

#

else, yeah, completely migrate to app commands. (here's a guide)

fringe pine
#

thank you for the answers

tired pine
upbeat otter
fallow python
#

Is discordpy still how most bots are made today? I've been out of the loop for making discord bots for a bit, so just wanted to ask.

tired pine
tired pine
#

It shouldn't matter tho

cyan jolt
#

why do i get this error with embed color?

naive briar
#

0000FF is an invalid decimal literal (๐Ÿคฏ)

cyan jolt
#

and what do i need to put sorry

#

isnt it the hex code for blue?

naive briar
#

You're probably looking for 0x0000FF

#

Just add the 0x in front of the hex colour

cyan jolt
#

thx, what did it change?

naive briar
#

It corrects the syntax

#

!e

print(0x0000ff)
unkempt canyonBOT
#

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

255
fallow python
#

I'm playing around with @tree commands. Haven't tried those before but seem super nifty.

@tree.command(
    name="hello",
    description="will make the bot send a greeting",
    guild=discord.Object(id=<guild id>)
)
async def _hello(interaction):
    await interaction.response.send_message("Hello!")

Is there a way to remove this part of a bot's response though?

sick birch
#

Or you can simply do a normal channel.send

fallow python
#

I would like to show a response, just don't care to have the "user used" part

sick birch
#

if you don't care about it I'd say just leave it

fallow python
#

I do care that it's there. I don't want that part to be there.

slate swan
#

thats just how slash commands work

fallow python
#

Given this code, if I only do the first line, then the command hangs in Discord until it tells me the application fails, despite the message being sent to my channel.
If I do both or the second line then it seems to finish and does not tell me that the Application failed. Why is that?

async def _test(interaction):
    await interaction.channel.send("test")
    await interaction.response.send_message("test")
sick birch
fallow python
#

I see. Defer what exactly? The interaction object?

sick birch
fallow python
#

Yes. Doing that makes the bot seem stuck on "thinking".

sick birch
#

You might have to pass thinking=False into the method

fallow python
#

Ah. Right.

#

Huh. That didn't do it. It's still stuck on thinking. Strange.

ancient raven
#

This error is always cause of the internet right ?

ancient raven
fallow python
#

I tried to add optional values, but now the command doesn't work at all.
It just tries to submit and then fails.

async def _alarm(interaction, hour: int = -1, min: int = -1):

I wanna be able to give the user the ability to call /alarm and /alarm hour: min:

hushed galleon
fallow python
hushed galleon
#

afaik nope, you'll probably just have to send an ephemeral message saying your command was successful or something

ancient raven
fallow python
#

There is none in the terminal

ancient raven
fallow python
#

It is.

#

Otherwise I wouldn't have gotten the message I show you in the picture

ancient raven
#

Or when it takes more that 3 seconds to respond but in your case thereis no error in the terminal

fallow python
#

When I add this to the top of my function call, the bot stops working.
print(f'{interaction.message.created_at}')

ancient raven
#

Can you send the entire code of that function if its not that big

fallow python
#
async def _alarm(interaction, hour: int = -1, min: int = -1):
    print(f'{interaction.message.created_at}')
ancient raven
#

its not running cause there is no output im guessing

fallow python
#

No output? What do you mean?

ancient raven
#

are you not getting the output for that print one as well on the terminal ?

fallow python
#

It's not printing to terminal, no

#

Which is odd, because this:

@client.event
async def on_ready():
    await tree.sync(guild=discord.Object(id=<guild id>))
    print(f'We have logged in as {client.user}')
#

Does print to terminal

#

Okay. Found the issue.

#

The "message" object is "None"

ancient raven
ancient raven
fallow python
#

Yeah I see that now. I thought the message was needed but the interaction gives the time as well.

#

Thank you for the help.

ancient raven
#

wlcm : )

dense swallow
#

does anyone know why my reaction remove event is not working as expected?
https://paste.pythondiscord.com/D54Q
basically a starboard reaction remove event, so when it gets to a number lower than the set star count, it should edit the msg, and if the count goes to 0, bot should delete the posted star embed

formal valve
#

Perfect.

dense swallow
#

to do this, im storing these values:
star config table
guild_id | channel_id | self star | star count

star info table
guild_id | bot msg id | user msg id

hushed galleon
#

oh wait, message.reactions is going to be empty if the reaction count is 0

hushed galleon
#

well empty if there aren't other reactions, but for robustness i would only check the star reaction's count, i.e. discord.utils.get(message.reactions, emoji="โญ")

dense swallow
#

so like if message.reactions edit it, else delete msg?

hushed galleon
#

well, either the reaction object won't exist, or it will exist and will have some count of 1 or higher