#discord-bots

1 messages · Page 326 of 1

young dagger
#

How do you prevent this?
[2023-11-30 23:28:00] [WARNING ] discord.http: We are being rate limited. POST https://discord.com/api/v10/channels/769452100786323457/messages responded with 429. Retrying in 0.30 seconds.

naive briar
young dagger
naive briar
final iron
robust fulcrum
#

guys how can i edit a button from another button though its custom_id?

shrewd apex
#

if subclassed view use self to acess it if not view.children

robust fulcrum
shrewd apex
#

yeah

robust fulcrum
shrewd apex
#

or index it if u already know

robust fulcrum
#

isn't their any other way?

shrewd apex
#

no

robust fulcrum
#

kk, ty

latent harness
#

Can anyone tell me how can I add multiple Items to my bot's database? Items as in stuff that can be added in 'inventory' of a game

slate swan
#

what lib is that?

grizzled yew
#

how tough is making api wrapper for discord api

unreal pilot
#

yo, in my discordpy bots ive never really had to utilize Cogs

#

in this example, they use the .listener attirbute as decorator instead of a bot.event

#

do they act the same?

#

i assume that when you load in the cogs, this decorator gets overwritten?

#

so i assume that listener, takes the passed bot instance in when creating custom Cogs

#

also, why are they adding parenthesis with listener when we dont pass any arguments? whats the point?

young dagger
#

Should I use a list or set() if I don't want duplicates?

unreal pilot
#

but remember, sets are unordered

sturdy dragon
#

hey guys Im having issues with my slash commands constantly disappearing, only to return later

#

no errors in the log

sturdy dragon
shrewd apex
unreal pilot
#

its massive, you will not be able to make one solo

grizzled yew
#

damn

unreal pilot
#

you need a very good understanding of low-level concurrency

#

and since its massive, you need very clear organization

grizzled yew
#

damn

#

how many years to master low level concurrency?

onyx lagoon
#

hey guy can i have a question

#

how to fix this

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

grizzled yew
#

intents = discord.Intents.all()

slate swan
#

dont set Intents to all unless you really need all intents enabled

onyx lagoon
#

but why doesn't it run?

unreal pilot
#

question regarding yielding code until a user has interacted with a selection menu:

young dagger
#

Is there any way to see how many times a user boosted the server?

unreal pilot
#

would asynchronously yielding the sequence with asyncio.Future's be good practice?

#

the selection menu would set the result of the Future object

#
 async def wait_for_button(self):
        self.interaction_future = asyncio.Future()

        try:
            return await asyncio.wait_for(self.interaction_future, timeout=60.0)
        except asyncio.TimeoutError:
            return None # timeout will return None, bot will handle the rest
        finally:
            self.interaction_future = None
#
self.interaction_future.set_result(interaction_result)
unreal pilot
onyx lagoon
#

hey guy how make a bot online

final iron
onyx lagoon
slate swan
onyx lagoon
slate swan
#

it tells you what to do

onyx lagoon
#

yah i okay intents now

slate swan
#

also

#

the error literally gives you a link to follow

onyx lagoon
#

but i have this error

#

yah ok let i find

onyx lagoon
onyx lagoon
#

how to stop

slate swan
#

ctrl c

onyx lagoon
slate swan
#

press ctrl c in terminal

#

to stop

onyx lagoon
#

thankkk you so much

acoustic kernel
#

Question, I have a command called /sell that allows players to sell resources to other players. The other players buy the resource by reacting to a checkmark on the original bot response. But right now when I wait for reaction if a player trys to run the sell command again itll automatically thing that the first message had a reaction on it.

vapid parcel
#

@slate swan are you active right now?

slate swan
#

?

vapid parcel
#

Okay so can you help me with something real quick?

slate swan
#

just put your question here any somebody will answer next time

#

instead of pinging

vapid parcel
#

Well, ive asked many times, no one has ever helped me with this issue lol

#

Ive even posted everything in here, an in discord.py... just no one helps me with the issue...

#

Thats why I pinged you, cuz maybe you were online..

slate swan
#

!d asyncio.to_thread

unkempt canyonBOT
#

coroutine asyncio.to_thread(func, /, *args, **kwargs)```
Asynchronously run function *func* in a separate thread.

Any \*args and \*\*kwargs supplied for this function are directly passed to *func*. Also, the current [`contextvars.Context`](https://docs.python.org/3/library/contextvars.html#contextvars.Context) is propagated, allowing context variables from the event loop thread to be accessed in the separate thread.

Return a coroutine that can be awaited to get the eventual result of *func*.

This coroutine function is primarily intended to be used for executing IO-bound functions/methods that would otherwise block the event loop if they were run in the main thread. For example:
slate swan
vapid parcel
#

hm

#

What do you recommend instead of PIL?

slate swan
#

im not saying to replace it

vapid parcel
#

Easy PIL, and PIL both just have issues XD

slate swan
#

im saying i dont know the answer since its the problem itself is not really related to discord bots

vapid parcel
#

Ah.. okay then

#

Welp sorry for pinging and wasting time.

slate swan
#

ask here

vapid parcel
#

Yeah imma post in there too

cloud dawn
pine patrol
#

Hey

#

i’m a js developer but i wanted to try py for fun

#

discord_slash import SlashCommand is supported or am i just bugging?

#

i keep on getting errors trying to use slash commands even though i installed it

sick birch
pine patrol
#

Aware, but replit forced me to install it

#

i’m just trying a simple bot lol

sick birch
#

Ok well, since you're having errors with it you don't need to use it or get it to work

slate swan
#
import discord

client = discord.Client()

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event 
async def on_message():
    if message.author == client.user:
        return

    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')

client.run(my token goes here)

when i run this it says theres a problem on the line 3 “client = discord.Client()” it says “missing 1 required keyword only argument. ‘intents’”

slate swan
#

can someone help me solving that

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

final iron
pine patrol
#

clueless, told me to install it saying “you need to install discord_slash_command” i was confused

final iron
#

Where

pine patrol
final iron
#

Where did it tell you that you need to install it

pine patrol
final iron
pine patrol
#

no module named ‘discord_slash’

#

( installed discord-py-interactions and discord_slash )

final iron
#

That’s extremely different from it telling you to install it lmao

pine patrol
#

no it’s told me that before

final iron
#

Anyway, as Robin already stated discord.py has slash command support

pine patrol
#

should i uninstall it rhen?

final iron
#

Yes

pine patrol
#

by the way, im a javascript developer it’s my first time using discord py so thank you pep

#

@final iron

cloud dawn
#

AI do be outdated.

#

What code do you have currently?

pine patrol
#

then continues, the error is in line 3

pine patrol
#

what do you mean

cloud dawn
#

discord_slash isn't really updated anymore.

pine patrol
#

oh yes

cloud dawn
#

I recommend running this script first, this will get rid of any forks or other libs and install discord.py ```py
import os
import sys

py_exec = sys.executable
uninstall_list = " -m pip uninstall nextcord py-cord interactions.py disnake dislash discord-py-slash-command discord.py-message-components enhanced-discord.py novus hata discord-interactions discord.py-self discord.py-self.embed discord2 python-discord reactionmenu discord_py_buttons discord_slash discord.py discord discord-ext-forms discord-ext-alternatives"

os.system(py_exec + uninstall_list)
os.system(py_exec + " -m pip install discord.py --no-cache-dir")

pine patrol
#

Okay one moment

final iron
unreal pilot
#

pov: type hinting

unreal pilot
#

?? why

#

its literally there

#

triple sss nvm jesus christ

unreal pilot
#

in case you've ever struggled with waiting for user responses but you dont want ugly while loops to check for instance variable updates

final iron
#

You kinda made an implementation Danny saw in other libraries and wanted to avoid creating

unreal pilot
#

it works horrendously with sequential code

#

If for instance, I had a shop that offered like currency for my Discord server which you can pay for with crypto or whatever payment methods

#

that requires a large ORM based sequence

#

using callbacks is yuck as this would require you to hop from callback to callback

#

which could (but certainly will) result in chaotic code

#

I 100% use callbacks where i can, but for large sequences i just cant

hushed galleon
# unreal pilot it works horrendously with sequential code

views have the .wait() method which is basically the same solution, waiting on a future that gets set by .stop() or timeout
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/ui/view.py#L526 ```py
class MyView(discord.ui.View):
@discord.ui.button(label="Continue")
async def on_continue(self, interaction, button):
self.interaction = interaction
self.stop()

for i in range(1, 4):
view = MyView()
await _ctx.send(f"Step {i}", view=view)

timed_out = await view.wait()
if timed_out:
    break

interaction = view.interaction
await interaction.response.edit_message(content=f"Step {i} completed!")```
unkempt canyonBOT
#

discord/ui/view.py line 526

return await self.__stopped```
unreal pilot
#

thats nice

#

tho ill keep using my own as its more universal for getting the result of a component interaction inside the view

unreal pilot
#

because i feel like im missing something

#

oh wait, maybe i dont even need a wait_for

#

what if i just have a Future.wait()?

#

i pass this Future to my View, and set the result of the Future inside the view

hushed galleon
unreal pilot
#

thanks for enlightening me on that, didnt know wait stop was a feature of View

#

but yea, 4am here. My brain is fried from coding from 11am to 4

unreal pilot
hushed galleon
#

er correction, only when you nest callbacks is when it's called callback hell, and async/await in python makes it easy to write the equivalent callback code as a sequence of await steps

unreal pilot
#

Still, the callbacks will cause chaos :d

hushed galleon
# unreal pilot Still, the callbacks will cause chaos :d

you can still write clean, callback-based code, for example if you have a bunch of different buttons to show for a tictactoe game at various points, you might write something like: ```py
@bot.tree.command()
async def tictactoe(interaction):
await interaction.response.send_message("Waiting for a player to join...", view=TicTacToeLobby(...))

class TicTacToeLobby(discord.ui.View):
@discord.ui.button(label="Join")
async def on_join(self, interaction, button):
await interaction.response.edit_message(
content=f"{x} is now playing against {y}!",
view=TicTacToeGame(...),
)

class TicTacToeCell(discord.ui.Button):
async def callback(self, interaction):
self.occupied_by = ...
await self.view.update(interaction)

class TicTacToeGame(discord.ui.View):
def init(self, ...): ... # add 3x3 grid or bigger

async def update(self, interaction):
    if player_won is not None:
        end_message = f"{x} won! Do you want to play again?"
    elif empty_slots < 1:
        end_message = f"It's a tie! Do you want to play again?"
    else:
        return

    view = TicTacToeRematch(...)
    await interaction.response.edit_message(end_message, view=view)

class TicTacToeRematch(discord.ui.View):
@discord.ui.button(label="Rematch")
async def on_vote(self, interaction, button):
if both_players_agreed:
await interaction.response.edit_message(
content=f"{x} is now rematching against {y}!",
view=TicTacToeGame(...),
)``` each view represents a specific phase/state of the game which makes it easy to transition between those views rather than having a single function deciding which view to send, especially when you have a lot of states to traverse through

of course not all commands need several views, but callbacks aren't necessarily unmaintainable if you can figure out how to organize them efficiently

tepid rivet
#

!

haughty dagger
#

nobody is helping me in d.py server can I post my question here?

haughty dagger
#

I'm getting failed to load options for my autocomplete command, even though the code is copied from a YT video

import discord
from discord import app_commands
from discord.ext import commands
import typing

class Test_Command(commands.Cog):

    def __init__(self, client: commands.Bot):
        self.client = client

    async def drink_autocompletion(self,
                                   interaction: discord.Interaction,
                                   current: str
                                   ) -> typing.List[app_commands.Choice[str]]:
        data = []
        for drink_choice in ['beer', 'milk', 'tea', 'coffee', 'juice']:
            if current.lower() in drink_choice.lower():
                data.append(app_commands.Choice(
                    name=drink_choice, value=drink_choice))
        return data

    @app_commands.command()
    @app_commands.autocomplete(item=drink_autocompletion)
    async def drink(self, interaction: discord.Interaction,
                    item: str
                    ):
        await interaction.response.send_message(f"{item}", ephemeral=True)

async def setup(client: commands.Bot):
    await client.add_cog(Test_Command(client))
#

it is not working what's wrong?

slate swan
slate swan
#

I wouldnt recommend learning coding bots on YouTube

haughty dagger
#

the thing is, Ik how it works because I already have a command with autocomplete that was working fine few days ago. But now, it doesn't work at all

slate swan
haughty dagger
#

so to confirm if everything is correct, I searched on yt and followed the tut, but it is also not working

slate swan
haughty dagger
slate swan
#

My bad there is not in discord py

#

Try this

haughty dagger
#
class Test_Command(commands.Cog):

    def __init__(self, client: commands.Bot):
        self.client = client

    @app_commands.command(name="echo")
    async def echo(self, inter: discord.Interaction, color: str):
        """
        Echoes a color

        Parameters
        ----------
        inter: discord.Interaction
            The interaction object
        color: str
            The color to echo
        """
        await inter.response.send_message(color)

    @echo.autocomplete("color")
    async def color_autocomplete(self, interaction: discord.Interaction, current: str) -> list[app_commands.Choice[str]]:
        options = ["Red", "Green", "Blue"]
        return [app_commands.Choice(name=option, value=option) for option in options if option.lower().startswith(current.lower())][:25]
#

as I said, something's really wrong it's not a coding fault

#

I realised that I have a custom tree for my bot

#

if I'm removing it, then the autocomplete is working fine

stark nexus
#

is it possible use PCMVolumeTransformer to get user’s vc volume and when pressed button 🔊 volume +5 🔉 volume -5?

#

(i already added buttons , but having problem on get user’s volume)

slate swan
slate swan
stark nexus
#

i discribe wrong

#

i want change my bot’s volume

slate swan
#

Then idk i never worked with audio

stark nexus
#

okay

left dew
#

so a user can add a specific time into a databse with a command, for example they input 2 days, how can i make it then send an alert when the 2 days have passed and it counts down?

slate swan
left dew
#

how would i update the db when the time expires?

shrewd apex
unreal pilot
#

so a local cache and a submission in your db, so when your program crashes or needs to restart, it can get a one-time cache again from the db

unreal pilot
#

so that you can use instance variables, easy to work with

unreal pilot
#

@haughty dagger what are you cooking up.

naive briar
#

That sounds expensive

unreal pilot
naive briar
#

Can't you do something like keep the futures in a dictionary and when you're closing the bot you keep the elapsed time?

unreal pilot
#

it is not adviced to work with Futures for long running code

#

like 2 days for instance here

naive briar
#

Why is that?

unreal pilot
#

potential resource constraints

#

hence why i was like

#

a single task per shard (which would be up to 1000 servers max around that)

#

seems better than having a Future object with a wait_for for each individual submission

naive briar
#

I wonder how @unkempt canyon's remind command is implemented

#

!source remind

unkempt canyonBOT
#
Command: remind

Commands for managing your reminders.

Source Code
unreal pilot
unreal pilot
unreal pilot
#

or thats just forl ogging

#

they also make use of a Scheduler

#
    def schedule_reminder(self, reminder: dict) -> None:
        """A coroutine which sends the reminder once the time is reached, and cancels the running task."""
        reminder_datetime = isoparse(reminder["expiration"])
        self.scheduler.schedule_at(reminder_datetime, reminder["id"], self.send_reminder(reminder))
unreal pilot
#

seems like this is the tool they use

#
 async def _await_later(
        self,
        delay: int | float,
        task_id: abc.Hashable,
        coroutine: abc.Coroutine
    ) -> None:
        """Await ``coroutine`` after ``delay`` seconds."""
        try:
            self._log.trace(f"Waiting {delay} seconds before awaiting coroutine for #{task_id}.")
            await asyncio.sleep(delay)

            # Use asyncio.shield to prevent the coroutine from cancelling itself.
            self._log.trace(f"Done waiting for #{task_id}; now awaiting the coroutine.")
            await asyncio.shield(coroutine)
        finally:
            # Close it to prevent unawaited coroutine warnings,
            # which would happen if the task was cancelled during the sleep.
            # Only close it if it's not been awaited yet. This check is important because the
            # coroutine may cancel this task, which would also trigger the finally block.
            state = inspect.getcoroutinestate(coroutine)
            if state == "CORO_CREATED":
                self._log.debug(f"Explicitly closing the coroutine for #{task_id}.")
                coroutine.close()
            else:
                self._log.debug(f"Finally block reached for #{task_id}; {state=}")
#

seems like they use asyncio sleep... yuck

#

ill look into that interesting stuff

naive briar
#

I guess since it's private and not many people use it much anyway

unreal pilot
#

_await_later is the core of Scheduler's scheduler

#

it seems

naive briar
#

Already saw that

unreal pilot
naive briar
#

I mean exactly what I said

unreal pilot
#

its a private method yea because youre supposed to use schedule_at which uses _await_later

naive briar
#

Yes?

unreal pilot
naive briar
#

I wonder

unreal pilot
#

which seems ugly to me

#

but must be more efficient than iterating through a large dictionairy ig

#

issue with mine is that it requires a minute+ and you cant schedule for 30 seconds

unreal pilot
#

is there a reference online for all possible app_commands decorators that i could add

unreal pilot
fading marlin
#

yw :)

left dew
#

ive got this that works out when a message should send after the time has expired but idk how i would do that from my db

d = datetime.strftime(datetime.now(timezone(timedelta(hours=3))) + timedelta(t), '%d-%m-%Y').split("-")
date = datetime(day=int(d[0]), month=int(d[1]), year=int(d[2]), tzinfo=timezone(timedelta(hours=3))).strftime('%d/%m')```
leaden flint
#

anyone could help me with a discord.py discord bot? it really seems easy with sending embeds and deleting them

#

nothing more

#

but its been 3 days and im turning crazy

unreal pilot
#

why is discord seeing htis as invalid emoji:

ZELLE = '![zelle](https://cdn.discordapp.com/emojis/1180535612244234341.webp?size=128 "zelle")'
#

i do not see what is wrong with it

#
.add_field(name='Supported', value=f'{Emojis.ZELLE}}')
#

the bot and emojis are both in the same server

unreal pilot
leaden flint
unreal pilot
#

i have exactly the same shit on another bot and it works fine there

#

im literally copy pasting it

#

it works for me but my bot is erroring

leaden flint
#

the emoji exists in the server?

unreal pilot
#

yes

#

like it literally makes no sense

leaden flint
unreal pilot
# leaden flint try ```py .add_field(name='Supported', value=f'{ZELLE}') ```

?

class Emojis:
    ZELLE = '![zelle](https://cdn.discordapp.com/emojis/1180535612244234341.webp?size=128 "zelle")'
    CASHAPP = '![cashapp](https://cdn.discordapp.com/emojis/1180535608809099294.webp?size=128 "cashapp")'
    BTC = '![btc](https://cdn.discordapp.com/emojis/1180536077421920407.webp?size=128 "btc")'
    LTC = '![ltc](https://cdn.discordapp.com/emojis/1180535854100398140.webp?size=128 "ltc")'
left dew
#

why not just do
.add_field(name='Supported', value=f':zelle:')

#

oh wait

unreal pilot
#

yea

#

you cant

leaden flint
#

are they in embeds

left dew
#

huh

leaden flint
#

?

unreal pilot
#

class Emojis:
ZELLE = 'zelle'
CASHAPP = 'cashapp'
BTC = 'btc'
LTC = 'ltc'

leaden flint
#

delete the instance then

unreal pilot
#

it has no reason to not work, its literally here

unreal pilot
unreal pilot
unreal pilot
leaden flint
unreal pilot
#

its not about the instance bro

#

there is no instance

#

its a class var

leaden flint
unreal pilot
#

its literally not invalid

left dew
#

can an embeds field value be just an emoji?

leaden flint
unreal pilot
#

you can use emojis anywhere, doesnt matter

cloud dawn
#
.add_field(name='Supported', value=discord.PartialEmoji.from_str(Emojis.ZELLE))
unreal pilot
#

imma print all emojis in my guild rq

leaden flint
#

if you want show me how the embed is supposed to be i'll make one for you

unreal pilot
unreal pilot
cloud dawn
unreal pilot
#

imma just print the guild emojis rq

#

may be just an API issue rn who knows

leaden flint
#

yeah

#

it says bad request

#

so could be

unreal pilot
#

(<Emoji id=1172260354701668392 name='arrowemoji' animated=False managed=False>, <Emoji id=1173374162576879617 name='coding' animated=False managed=False>, <Emoji id=1180535608809099294 name='cashapp' animated=False managed=False>, <Emoji id=1180535612244234341 name='zelle' animated=False managed=False>, <Emoji id=1180535854100398140 name='ltc' animated=False managed=False>, <Emoji id=1180536077421920407 name='btc' animated=False managed=False>)

leaden flint
#

i use description for embeds

unreal pilot
#

discord issue then ig

leaden flint
unreal pilot
tacit prawn
#

What am I doing wrong 😭

unreal pilot
leaden flint
leaden flint
unreal pilot
tacit prawn
leaden flint
#

im not allowe to send long messages

#

allowed

#

i'll use pastebin

unreal pilot
#

i want to see its current location and whether u activated a venv

unreal pilot
tacit prawn
leaden flint
cloud dawn
#

!charinfo :zelle:

unkempt canyonBOT
leaden flint
#

the code works fine though

#

but i want to add a small thing to it

tacit prawn
#

Wait

shrewd fjord
#

Actually, try using zelle:id

#

Sec lemme grab the info

tacit prawn
leaden flint
#

@unreal pilot So basically there is an embed you'll find called "Deal Amount", that's its title, I want it to be deleted after the "Correct" & "Incorrect" buttons are pressed, it works for the other embeds, other embeds are getting deleted, but only the "Deal Amount" embed doesn't get deleted

cloud dawn
#

@unreal pilot Does it work on a normal message instead of an embed?

leaden flint
#

I can tell you what the code does exactly

unreal pilot
#

@leaden flint ill help u in like 4-5 mins ok?

leaden flint
unreal pilot
#

worked for a regular message @cloud dawn

#

super odd behaviour

#

using Emojis.ZELLE

#

its not working in an embed field as far as ive tested

cloud dawn
#

Discord doesn't render a lot in embeds.

shrewd fjord
glossy mauve
#

can someone help?

cloud dawn
shrewd fjord
shrewd fjord
#

!pip jishaku

unkempt canyonBOT
leaden flint
#

it's not implented

cloud dawn
#

Ah read it wrong

leaden flint
#

deal_amount_embed variable variable exists

unreal pilot
leaden flint
#

but, it doesnt get deleted, i tried to make it get deleted but to no avail

unreal pilot
#
        self._ZELLE = discord.utils.get(interaction.guild.emojis, name="zelle")
        self._CASHAPP = discord.utils.get(interaction.guild.emojis, name="cashapp")
        self._BTC = discord.utils.get(interaction.guild.emojis, name="btc")
        self._LTC = discord.utils.get(interaction.guild.emojis, name="ltc")

even did this, still 'invalid emoji' 💀

#

what the fuck is discord on man

cloud dawn
shrewd fjord
#

Is it happening on a component?

unreal pilot
#

no

#

unless an Embed is considered a component (i doubt it?)

shrewd fjord
#

Ah no, it isnt

#

Where are you trying to use a emoji in embed anyway?

unreal pilot
#

cant use emoji's in descriptions and the field's value

#

so it must be a discord api issue

shrewd fjord
#

Huh weird it shouldn't raise any error tho it should be a plain text

unreal pilot
#

exactly

shrewd fjord
#

Could you send full traceback?

unreal pilot
#

no because it contains my real name

#

raise HTTPException(response, data) discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In components.0.components.0.emoji.name: Invalid emoji

shrewd fjord
#

Um just remove those oarts?

unreal pilot
#

i got this for u haha :d

shrewd fjord
#

Need full dead

unreal pilot
#

File "C:\Users\\Desktop\Isaaa_TICKETHANDLER\cogs\tickethandler.py", line 84, in robuxAmount self._calc_robuxAmount: discord.Message = await self._ticket_channel.send(Embed(title='Estimated Costs', description=f'For gamepass, plugin or shirt purchases:\n> $ **-**\n\nFor in-game gifting:\n> $ **-** {self._ZELLE}', color=Config.CONST_EMBED_COLOR).add_field(name='Supported Payment Methods', value='hi'), view=self._ConfirmRobuxAmountView) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\\Desktop\Isaaa_TICKETHANDLER\venv\Lib\site-packages\discord\abc.py", line 1561, in send data = await state.http.send_message(channel.id, params=params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\\Desktop\Isaaa_TICKETHANDLER\venv\Lib\site-packages\discord\http.py", line 745, in request raise HTTPException(response, data) discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In components.0.components.0.emoji.name: Invalid emoji

shrewd fjord
shrewd fjord
unreal pilot
#

? this is an instance

shrewd fjord
#

view=self._....()

unreal pilot
#

i already have initialized it, dont worry

shrewd fjord
#

Put ()

unreal pilot
#

? i just told u

#

its an instance, its already intialized

shrewd fjord
#

Oh alr

unreal pilot
#

its not a class

#
self._ConfirmRobuxAmountView = ConfirmRobuxAmountView(Cog=self.bot)
#

bit of a hacky naming convention

shrewd fjord
#

This is a problem about the emoji in the first button in your view

unreal pilot
#

are you serious

#

emoji='✅'

#

\✅

#

jesus. stop

shrewd fjord
#

Could you share the first button decorator (and callback if u can)

shrewd fjord
unreal pilot
#
class ConfirmRobuxAmountView(discord.ui.View):
    def __init__(self, Cog):
        self.Cog = Cog
        super().__init__(timeout=None)

    @discord.ui.button(style=discord.ButtonStyle.green, label='confirm', emoji=':white_check_mark:', disabled=True)
    async def Continue(self, interaction: discord.Interaction, button: discord.ui.Button):
        self.Cog.interaction_future.set_result(True)

    @discord.ui.button(style=discord.ButtonStyle.green, label='change', emoji=':white_check_mark:', disabled=True)
    async def Continue(self, interaction: discord.Interaction, button: discord.ui.Button):
        self.Cog.interaction_future.set_result(False)
slate swan
#

Aren't you supposed to put the raw emojis

shrewd fjord
#

^^^

slate swan
#

As in

#

\✅

unreal pilot
#

taht would make a ton of sense

slate swan
#

Yeah whatever, doesn't work on mobile

unreal pilot
#

also i noticed i got a duplcation of function names, fixed that as wel lnow

shrewd fjord
#

!charinfo :white_check_mark:

#

Ok lmao

unreal pilot
#

ok so outcome: im gonna harm myself

#

because ive just wasted an hour for something that isnt even the error

shrewd fjord
#

!charinfo :white_check_mark:

slate swan
#

!charinfo ✅

unkempt canyonBOT
unreal pilot
#

\❌

shrewd fjord
#

Bro wtf is discord's prob, thanks krypton

unreal pilot
#

haha

slate swan
#

Can just send the emoji lulw

glad cradle
shrewd fjord
slate swan
#

No need to escape for the command

shrewd fjord
#

I didnt know i can just pass the emoji in charinfo

unreal pilot
#

works now

shrewd fjord
#

Gg bro

unreal pilot
glad cradle
shrewd fjord
#

Idk when i first did, it used to show the letters' unicode of the emoji name idk actually lol

left dew
#

a user can input a time in a db and i want it to send a message when the time is up, like they input 2 days etc, i have this so far

d = datetime.strftime(datetime.now(timezone(timedelta(hours=3))) + timedelta(t), '%d-%m-%Y').split("-")
date = datetime(day=int(d[0]), month=int(d[1]), year=int(d[2]), tzinfo=timezone(timedelta(hours=3))).strftime('%d/%m')```
glossy mauve
#
  File "/home/runner/LightMonumentalLoopfusion/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 941, in _load_from_module_spec
    setup = getattr(lib, 'setup')
AttributeError: module 'cogs' has no attribute 'setup'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/runner/LightMonumentalLoopfusion/.pythonlibs/lib/python3.10/site-packages/jishaku/features/management.py", line 61, in jsk_load
    await discord.utils.maybe_coroutine(method, extension)
discord.ext.commands.errors.NoEntryPointError: Extension 'cogs' has no 'setup' function.```
#

help?

slate swan
#

Error says it all

#

Your cog has no setup function krShrug

leaden flint
glossy mauve
#

so im getting confused

slate swan
leaden flint
#

matter

slate swan
leaden flint
#

i want an embed to be deleted when I click on a button

#

this is the code, the button is "Correct" when both people choose "Correct" for the 2nd one

#

im paying 10$ paypal whoever helps me

slate swan
hushed galleon
unkempt canyonBOT
#

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

slate swan
#

me when !rule pay

leaden flint
#

is paying illegal now

#

or hiring is considered trafficking now

slate swan
#

its against rules of this server which you accepted upon joining here

#

😊

leaden flint
slate swan
#

it doesnt make any sense to complain about rules you accepted

leaden flint
#

😎

final iron
leaden flint
#

tbh i included money because no one would help without money

#

why would someone offer their time for me for free

#

everyone is on their own after all

hushed galleon
#

i imagine it wouldn't foster a good community if we had people wanting bounties for help, but perhaps the admins have other reasons for its existence

regardless, you want the confirmation to also delete your deal amount message? have you tried passing the deal message to your AmountConfirmationView?

final iron
leaden flint
leaden flint
#

If you don't mind

hushed galleon
leaden flint
#

okay here what the code basically do

#

I can record a video of the process

glossy mauve
#
  File "/home/runner/LightMonumentalLoopfusion/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 941, in _load_from_module_spec
    setup = getattr(lib, 'setup')
AttributeError: module 'cogs' has no attribute 'setup'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/runner/LightMonumentalLoopfusion/.pythonlibs/lib/python3.10/site-packages/jishaku/features/management.py", line 61, in jsk_load
    await discord.utils.maybe_coroutine(method, extension)
discord.ext.commands.errors.NoEntryPointError: Extension 'cogs' has no 'setup' function.```
graceful ermine
#

Hey, how can I make it where if a user joined a server called "A" it sends the welcome message in guild "A"? I tried making this but it keeps on sending it to the main server.

leaden flint
#

as you can see the "Deal Amount" doesnt get deleted

#

anyone could help me with this?

glossy mauve
#

can someone pls help?

faint echo
#

Sup yall, I have a command /ticket setup, a hybrid_command that creates a modal with some options.
Docs reference: https://discordpy.readthedocs.io/en/stable/interactions/api.html?highlight=modal#channelselect

Tried ✅ :

  • Using TextInput instead of ChannelSelect

Error:

Command 'setup' raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.1.components.0: Value of field "type" must be one of (4,).

Code for TicketSetupModal:

class TicketSetupModal(discord.ui.Modal):
    """A class that represents a ticket setup modal.
    """

    def __init__(self):
        """Initializes the modal."""
        super().__init__(title="Ticket system", timeout=60.0)

        # Ticket options
        print("Ticket options selection 1/2")
        self.ticket_options = discord.ui.TextInput(
            label="Ticket options",
            style=discord.TextStyle.paragraph,
            placeholder="type in the ticket options separated by **,**",
            required=True,
        )
        self.add_item(self.ticket_options)
        print("Ticket options selection 2/2")

        # Channel selection
        print("Channel selection 1/2")
        self.channel_select = discord.ui.ChannelSelect(
            placeholder="Select ticket channels",
            channel_types=[discord.ChannelType.text],
            min_values=1,
            max_values=2,
        )
        self.add_item(self.channel_select)
        print("Channel selection 2/2")

        # Default embed name
        print("Embed name selection 1/2")
        self.default_embed = discord.ui.TextInput(
            label="Main embed name",
            placeholder="Type in the name of the main embed utilized here",
            required=False,
            style = discord.TextStyle.paragraph,
        )
        self.add_item(self.default_embed)
        print("Embed name selection 2/2")

    async def on_submit(self, interaction: discord.Interaction):
        pass
fading marlin
#

You can't add selects to modals

faint echo
#

that's very sad, anyways thx.

fading marlin
#

That's for future proofing, I guess

#

And probably not to have a huge Union

unreal pilot
#

Read. The. Docs. 👏

faint echo
unreal pilot
#

I am not internet-wise enough for those terms haha

cloud dawn
unreal pilot
unreal pilot
#

how do i keep the item selected in dropdown menus after disabling it

#

is this even a thing?

#

or should i just add a field that gives visual feedback that a certain type was selected

cloud dawn
#

To the chosen option ofc

unreal pilot
#

i should commit an edit right?

#

yea i should

#

that worked nicely, thanks thumbs_up

#

custom emojis dont work

slate swan
#

Considering you have the custom emoji for Litecoin, should be easy to know how to fix

unreal pilot
#
discord.SelectOption(label="Litecoin", emoji=Emojis.LTC, description="Complete the order with Litecoin `LTC`.", value="LTC"),

vs

Select.placeholder = f'{option.emoji} {option.label}'

;)

slate swan
#

Well, you got your answer

unreal pilot
#

it wasnt a question, just more of a heads up for people who are also working with Selects

unreal pilot
slate swan
#

Lazy to fix it

#

But thanks

unreal pilot
#

the rest is cool tho

spring kelp
#

hey guys

#

what course could i use to learn about discord bot development

#

and how can i make a news bot?

#

what api and code would i use?

smoky patrol
#

await user.send(embeds=embedList)

what can i do if not both of the images are sended

#

if im doing like this:

await user.send(embeds=[original_embed, embed])

only the first embed is sended

leaden flint
#

can somebody helps me on how i can make a bot delete a certain message he sent after something happens? really as simple as that

leaden flint
#

?

#

i mean it works on other messages

#

there is a specific message tht doesnt want to be deleted

#

its because i didnt implent a deletion process for it, but idk how to anymore, can i show you in dms?

gray gyro
#

Hi

#

You have discord bot - Instagram account ban unban bot

#

???

uneven perch
#

why is message.embeds printing as [] when the message has an embed

naive briar
unkempt canyonBOT
naive briar
#

If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.

final iron
#

What even is an unban bot

trail maple
#

i am looking to track the "amount" or "progress" of a discord.File object being sent into a channel, is this possible?

#

i know that discord.File objects have a fp attribute but its method tell() doesnt update even while sending

shrewd fjord
#

!pip humanize

unkempt canyonBOT
shrewd fjord
#

Fk wrong channel, ignore me ;-;

final iron
#

banned

trail maple
final iron
trail maple
#

100mb

#

i want to be able to display a "progress" or "amount sent"/"total" count

final iron
trail maple
#

i am reading the file before hand so i know how large it is

final iron
#

the total amount of "bytes" that have been sent
when you say bytes that have been sent, do you mean from the bot overall?

trail maple
#

no

final iron
#

What you're asking isn't very clear

final iron
#

!d discord.File

unkempt canyonBOT
#

class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send) for sending file objects.

Note

File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send)s.
shrewd fjord
#

Well lemme say whats he asking

#

He asking if its possible to show the progress bar of a file being sent

final iron
#

Oh, like uploading the file

trail maple
shrewd fjord
#

Yup

final iron
#

No that's not possible

shrewd fjord
#

Yeah xd

trail maple
#

i mean when i call

await channel.send(file = discord.File(buffer, "test.txt"))

i want to check how much of the file has been uploaded

golden portal
#

well, built in it's not, but there is a hacky iffy way

final iron
#

How would you even see

final iron
#

When the API is called it's out of your hands

shrewd fjord
#

We can maybe just make own progress bar with current net speed and total size

trail maple
#

all i was asking is if it was possible

shrewd fjord
#

But it really depends on discord servers

final iron
#

Yeah that's what I was thinking as well, but it would depend on a ton of factors

#

Wouldn't be reliable at all

shrewd fjord
#

Hmm

trail maple
#

the discord.FIle object has a bytesio buffer and that has a "tell" method but it doesnt seem to update atall

final iron
#

When the API call is made it's out of your hands

trail maple
#

very sure

golden portal
shrewd fjord
#

!d

trail maple
shrewd fjord
#

Oh

trail maple
#

i want to track it from the bots code

shrewd fjord
#

You should've elaborated more then

golden portal
final iron
#

Personally I wouldn't really go for it as it's not really reliable, but if you want to do it the hacky way that's up to you

trail maple
#

lemme reset

when i am uploading a discord.File object to discord, i want to print to the console the percentage that the file is uploaded

#

surely there is someway to track the amount of bytes read from a io.BytesIO object

#

!d io.BytesIO

unkempt canyonBOT
#

class io.BytesIO(initial_bytes=b'')```
A binary stream using an in-memory bytes buffer. It inherits [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase). The buffer is discarded when the [`close()`](https://docs.python.org/3/library/io.html#io.IOBase.close) method is called.

The optional argument *initial\_bytes* is a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) that contains initial data.

[`BytesIO`](https://docs.python.org/3/library/io.html#io.BytesIO) provides or overrides these methods in addition to those from [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase) and [`IOBase`](https://docs.python.org/3/library/io.html#io.IOBase):
trail maple
#

how

#

omg nvm

final iron
#

Just keep in mind there are upload limits

#

25MB by default, and it goes up to 50/100 depending on the servers boost tier

golden portal
# trail maple surely there is someway to track the amount of bytes read from a io.BytesIO obje...

pretty hacky, you can only get to update everytime read is called, without tapping into the internal ```py
class TestIO(io.BytesIO):
def init(self, initial_bytes, length):
super().init(initial_bytes=initial_bytes)
self.length = length

def read(self, size=None):
    print(f"uploading {self.tell()}/{self.length}")
    return super().read(size)

_bytes = await _ctx.author.display_avatar.read()
size_of_file = len(_bytes)
a = TestIO(_bytes, size_of_file)
await _ctx.send(file=discord.File(a, filename="test.png"))

final iron
#

Oh that's actually a very good solution

#

Nice

glossy mauve
#
Traceback (most recent call last):
  File "/home/runner/LightMonumentalLoopfusion/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 941, in _load_from_module_spec
    setup = getattr(lib, 'setup')
AttributeError: module 'cogs' has no attribute 'setup'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/runner/LightMonumentalLoopfusion/.pythonlibs/lib/python3.10/site-packages/jishaku/features/management.py", line 61, in jsk_load
    await discord.utils.maybe_coroutine(method, extension)
discord.ext.commands.errors.NoEntryPointError: Extension 'cogs' has no 'setup' function.

#

help

sturdy dragon
#

where is your setup function?

glossy mauve
#

nor where to put it

sturdy dragon
#

in the same directory as the cog

#

put it in init.py

#

__init__.py

glossy mauve
#

the init.py file is in my modules folder

#

do i have to move it into cogs?

sturdy dragon
#

every cog should have a setup function, with in the module/extension itself or you can put it in init.py in the same folder

#

and python will look for it there first

glossy mauve
#

so i put the setup function in init.oh that's inside the module folder then it should be fixed?

sturdy dragon
#

where are you running the bot from

glossy mauve
sturdy dragon
glossy mauve
#

it's by itself not in a folder

sturdy dragon
#

did you write your cogs as their own class ?

glossy mauve
#

yeah

sturdy dragon
#

as a subclass of commands.Cog

#

ok, then you can put the setup in the cog

glossy mauve
#

at the bottom?

sturdy dragon
#

you need to pass the instance of the bot to the cog

#

first in the class attributes

#

you have an init function for the cog right

glossy mauve
#

yeah

sturdy dragon
#

ok, add bot attribute self.bot = bot

glossy mauve
#

it's already below the init function

sturdy dragon
#

now at the bottom of the cog code

#
    """ Add the cog to the bot."""
    await bot.add_cog(CogName(bot))```
glossy mauve
#

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

#

alright

#

so like this?

    await bot.add_cog(afk(bot))```
sturdy dragon
#

yep

glossy mauve
#

now i just add that but the class name different in all the files i have in cogs?

#

if that makes sense

sturdy dragon
#

how are you loading the cog

#

make a function to load your cogs in your main file

#

and you will need to await bot.load_extension(path_to_cog)

#

oh also

#

in the same location as the cog file

glossy mauve
#
                print(f"{extension}.py has been loaded")```
sturdy dragon
#

where you just added the setup function, create a blank __init__.py

#

that lets python know that it is a module to be loaded

#

@glossy mauve thats correct if the cogs are in a subfolder one level deeper like mybot/cogs/cog.py

#

as long as {extension} is called 'cog'

glossy mauve
sturdy dragon
#

yep if thats the name of your cog

glossy mauve
sturdy dragon
#

is jishaku your cog

glossy mauve
#

wym

sturdy dragon
shrewd apex
unkempt canyonBOT
smoky patrol
#

await user.send(embeds=[embed, original_embed]) # Create a direct message channel with the user

#

why aint both embeds send

blazing condor
#

does disnake feature slash command checks?

can't seem to find any documentation for it, and commands.check appears to be only for message commands.

buoyant quail
#

it does work on slash commands

slate swan
#

yall

#

my bot doesnt works on servers, like when i type !hello my bot doesnt responds, but in pm it works why?, can yall help me with this problem.

unkempt canyonBOT
#
Discord Message Content Intent

The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."

The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.

Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:

intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents

bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor

For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.

slate swan
#

!rule 6

unkempt canyonBOT
#

6. Do not post unapproved advertising.

slate swan
#

<@&831776746206265384> does that count as an advert?

craggy cloak
#

How can you make this?

slate swan
craggy cloak
slate swan
#

you want to know how to make a slash command?

craggy cloak
#

no how to show a command like that

slate swan
#

ah

#

</tag:1079848585027399791>

#

this you mean

craggy cloak
#

yes

slate swan
#

so this is how the message looks

#

and the number after :

#

is the command id

craggy cloak
#

How can you get the command id

slate swan
#

via bot or one time by user

#

!d discord.app_commands.AppCommand.id

unkempt canyonBOT
slate swan
#

app command has an id attribute

#

but if you are using a bot you can also already get full mention message

#

!d discord.app_commands.AppCommand.mention

unkempt canyonBOT
compact plank
#

How to make help pannel like this

slate swan
unkempt canyonBOT
#
Custom help commands in discord.py

To learn more about how to create custom help commands in discord.py by subclassing the help command, please see this tutorial by Stella#2000

uneven perch
#

#bot-commands

arctic briar
#

'''@slash1.autocomplete('iskola_neve')
async def slash1_autocomp(interaction:discord.Interaction,courent:str)->list[app_commands.Choice[str]]:
await interaction.response.defer()
options=[]
global KLIK_OPTIONS
if 'kliks' not in globals():
KLIK_OPTIONS=get_kliks()
for name, value in KLIK_OPTIONS.items():
if courent.lower() in name.lower():
options.append(app_commands.Choice(name=name,value=value))

    if len(options)>=7:
        break
print(options)
return options'''

why does this not work randomly for some str 's?

restive talon
#

Whats the best library. Discord.py is really outdated according to a number of people.

hushed galleon
slate swan
restive talon
#

See thats what i thought. Looking at almost any other lib means losing a lot of feaures. Like i dont believe modals are even supported on most things at this stage.

hushed galleon
#

err the popular dpy forks like disnake, nextcord, and py-cord all support it

hushed galleon
arctic briar
#

if is good for szil but not for szilá, szilág ... all the way to szilágyi e and even returns valid list[Choice] objs i know it bc i print it in terminal but discord says failed loading options also no errors in console

slate swan
#

ofc there are worse ones like py-cord

#

but yeah

glad cradle
slate swan
#

nextcord is a really good one and the best

hushed galleon
glad cradle
slate swan
#

nextcord 🚀 🔥🔥 🚀

#

best one out there

glad cradle
#

no

vapid venture
#

best py version to create discord bots?

shrewd apex
slate swan
#

I am trying to check if a message is sent but I forgot what the code was. I remember it had to with with wait_for

sick birch
slate swan
sick birch
slate swan
#

whitelist_ch is the channel the code is running

sick birch
sick birch
#

Should be fine then

slate swan
#

asyncio.sleep was working with ms or seconds?

brazen raft
#

It takes in seconds just like time.sleep

true vector
#

Is there any Library that is still being actively maintained ?

brazen raft
#

Resumed and maintained by the same repository maintainer

arctic briar
slate swan
final iron
cloud dawn
#

Where is Interaction defined?

#

Also regen your token.

cloud dawn
#

You're syncing globally, that takes up to an hour.

#

For dev purposes you'd sync it to one debug guild. Then it's instant but only available for that guild.

#

If you waited for an hour or so yeah or they already existed.

#

Why not?

final iron
#

!d discord.app_commands.CommandTree.command

unkempt canyonBOT
#

@command(*, name=..., description=..., nsfw=False, guild=..., guilds=..., auto_locale_strings=True, extras=...)```
A decorator that creates an application command from a regular function directly under this tree.
final iron
#

guild kwarg

#

Takes a snowflake, which you can create with discord.Object

faint stone
#

I have a need to run discord_client.run("my_token") inside my async main function, but doing so seems to cause it to try and spin up it's own event loop to run inside.

#

Is there a way to tell discord.py/disnake to use the currently running event loop, or to specify which loop it should run in?

hushed galleon
#

!d discord.Client.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/api.html#discord.Client.login) + [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.connect).
faint stone
final iron
#

This is a Python discord server

gray gyro
#

Give me bot Instagram ban unban

final iron
cold oyster
cold oyster
#

after I catch the pokemon it still says it fled

naive briar
#

Very specific

cold oyster
#

The markdown file didnt upload Idk why

cold oyster
#

The main.py file. When I use the catch command, To catch the pokemon. It should not say it has fled, While it does for some reason

#

@vocal snow @naive briar ^

vocal snow
#

But you are writing the spawned Pokemon to a json file

#

And updating the json file in the catch command

#

I wouldn't really recommend loading the entire json file each time the command is used, not sure why the spawned Pokemon would need to be saved to disk either

#

I think it would be better if you just used the self.spawned_pokemon dict throughout

vocal snow
# vocal snow You're checking self.spawned_pokemon in your tasks loop
# this is checking if the pokemon is in self.spawned_pokemon[server_id]
if {'name': pokemon_name, 'message_id': message.id} in self.spawned_pokemon[server_id]:

# but your catch command only changes the JSON file, not the self.spawned_pokemon dict
spawned_pokemons[server_id] = [pokemon for pokemon in spawned_pokemons[server_id] if pokemon['name'].lower() != pokemon_name.lower()]
with open('spawned_pokemons.json', 'w') as file:
    json.dump(spawned_pokemons, file, indent=4)

vale wing
faint stone
#

Did they change how adding slash commands to servers works?

#

Every method I've tried under the sun does not work

#

All functions just silently fail, and they only get added to whatever internal representation of state the bot is keeping track off

#

I can see in my Integrations the bot doesn't have a slash commands icon next to it like the other bots with one, but the bot was invited with the permission to create them?

vale wing
#

Also make sure you have applications.commands scope

faint stone
faint stone
vale wing
# faint stone disnake

Disnake should sync automatically. Please show your code and version of disnake you are using

faint stone
#

you can see my latest attempts here

vale wing
#

Too many CONSTANTS so hard to read 😞

blazing condor
#

way to many

vale wing
faint stone
vale wing
#

If twitch_user is not None, you never respond to interaction

vale wing
#

Also there's shortcut for responding in disnake, just inter.send instead of inter.response.send_message

faint stone
#

made these changes and it still can't use the commands in the server

vale wing
#

Make sure you have permissions and try restarting your client

faint stone
#

i've also tried manually passing in the guild_id on test_guilds and this also hasn't made a difference

faint stone
#

are there specific permissions or intents it needs for slash commands to be registered?

vale wing
#

Oh yeah that might be intents issue

#

Lemme see

#

!d disnake.Intents

unkempt canyonBOT
#

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

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

To construct an object you can pass keyword arguments denoting the flags to enable or disable. Arguments are applied in order, similar to [`Permissions`](https://docs.disnake.dev/en/latest/api/permissions.html#disnake.Permissions).

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

New in version 1.5.
vale wing
#

Nvm you don't need any intents for interactions

faint stone
#

i'm going to be real

#

never had this much problem registering slash commands on a different bot i built in rust

#

compared to that, this is completely opaque, and i can't believe there's no way to get better logging feed back in the terminal or something

#

setting the sync_commands_debug flag promises to actually display more logging when trying to sync slash commands, but it appears to do actually nothing at all

vale wing
#

You have some weird constructions there and it might be cause of the way you are starting the bot

#

Try enabling advanced logging as they say in docs

rain harness
#

Hey! I'm new, alright that's obvious and I really wanna do my own Discord bot, what is the best way to learn Phyton for beginner? Not even sure if I'm right here 😂 I googled Python and ended up here in this server 😅

faint stone
#

0 results

#

kinda crazy

vale wing
#

You haven't enabled logging

faint stone
vale wing
#

Have you

faint stone
#

I turned it all the way up to debug

vale wing
#

Try rg "disnake"

#

I am not familiar with OS level

faint stone
#
DEBUG:disnake.http:A rate limit bucket has been exhausted (bucket: None:None:/users/@me, retry: 0.001).```
#

only possible relevant lines

#

everything else is about the heartbeat after that

vale wing
#

Oh, you are ratelimited?

faint stone
#

I shouldn't be

#

just for starting the bot a bunch of times?

vale wing
#

There's limit to daily connections but it's 1000 iirc

faint stone
#
WARNING:disnake.gateway:Shard ID None heartbeat blocked for more than 60 seconds.```
this keeps happening to where it disconnects me from the gateway, so i have to just auto-reconnect instead
vale wing
#

Ok got it

#

You just have blocking code somewhere

faint stone
#

everything is async, and the twitch specific stuff is ran on it's own thread, on it's own event loop

#

which isn't even having it's code paths executed anyway, because i can't access them without the slash command

#

the fact that the slash command isn't even showing up in the LOGS, sorta tells me something is wrong with disnake's sync process

#

what I can see if I iterate through the bot's slash command state

for cmd in DISCORD_BOT.slash_commands:
        LOGGER.info(cmd.name)

I can see that it's added internally, but no way to query it's sync status

#

similarly, it's not even getting outputted to logs as if it were attempting to anyway, because it probably isn't

vale wing
#

Still your way of running it is kinda weird

faint stone
#

The wrapping the coroutine in a task, or something else?

vale wing
#

For example

t = create_task(start(...))
await t

You can just await start(...)

faint stone
#

Running it in my own event loop should be supported, according to how the .start() method exists.

vale wing
#

Since you don't need the task anywhere further

glad cradle
#

the what, iirc there's a loop argument if you want to pass it

#

!d disnake.ext.commands.Bot

unkempt canyonBOT
#

class disnake.ext.commands.Bot(command_prefix=None, help_command=<default-help-command>, description=None, *, strip_after_prefix=False, **options)```
Represents a discord bot.

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

This class also subclasses [`GroupMixin`](https://docs.disnake.dev/en/latest/ext/commands/api/prefix_commands.html#disnake.ext.commands.GroupMixin) to provide the functionality to manage commands.
vale wing
#

I rarely work with parallel stuff in asyncio but I once made a thing like async chess player

#

And I remember structuring it very differently

glad cradle
#

disnake.Client is accepting it and Bot is a subclass of Client

faint stone
#

I could just chalk this up to being on a VPN, but running this on a production VPS, it has the same issue and would eventually just permanently disconnect.

#

what I'd like to know is why none of the logging even seems to mention slash commands in the slightest?

#

I can deal with the gateway being flakey by just restarting it every 45 seconds, not a great solution, but it works around the garbage

#

why doesn't disnake even try syncing my commands

naive briar
#

Disnake things?

vale wing
#

Cause it blocks somewhere

#

Tracemalloc or debug to find out where

faint stone
#

if I have to tracemalloc, I'm sorry but I'll just go back to prefix commands

#

this isn't even a complex setup, if it can't handle this, then i guess i built the project on the wrong foundations

faint stone
#

nothing in my code is blocking, so are you referring to some portion of disnake has blocking code?

#

or are you referring to something else

vale wing
#

Probably twitch

#

Disnake doesn't have anything blocking inside

final iron
#

Average disnake slash command experience

faint stone
#

removing twitch calls from the code does not fix anything either

#

which is what you're saying is implying

vale wing
#

Ok I will get home and see this on PC

#

Cause this is more complex than I thought at first

vale wing
brazen raft
#

@faint stone What's the problem?

faint stone
brazen raft
faint stone
#

Made some more changes, but I haven't pushed them since they don't change the outcome currently

vale wing
#

@faint stone you tried snipy's solution?

#

Passing EVLOOP to loop kwarg of InteractionBot and then starting via await bot.start(...) in main

faint stone
#

slash commands still broke tho

vale wing
#

Also ik I already mentioned it, but your naming convention of constants makes it harder to read. You'd typically name variables in UPPER_SNAKE_CASE if they are primitives, ie don't have any non-static methods. Maybe not correct formulation but uh

MY_SERVER_ID = 12345678901234567  # constant
bot = InteractionBot(...)  # not a constant
vale wing
#

From disnake

blazing condor
#

im reading documentation on slash commands for disnake, and this looks correct doesn't it.

or is their something I'm missing or could do better.

@bot.slash_command(description="get a userr's avatar")
async def avatar(inter: disnake.AppCommandInteraction, user: disnake.User) -> None:
    avatar_url = user.display_avatar.url

    await inter.response.send_message(f"{user.name}'s avatar: {avatar_url}")

vale wing
blazing condor
#

interesting, any differences or just a simple shortcut

vale wing
#

Your code is correct though and if you like this way of sending messages you can keep it this way

vale wing
#

!d disnake.Interaction.send

unkempt canyonBOT
#

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

Sends a message using either [`response.send_message`](https://docs.disnake.dev/en/latest/api/interactions.html#disnake.InteractionResponse.send_message) or [`followup.send`](https://docs.disnake.dev/en/latest/api/webhooks.html#disnake.Webhook.send).

If the interaction hasn’t been responded to yet, this method will call [`response.send_message`](https://docs.disnake.dev/en/latest/api/interactions.html#disnake.InteractionResponse.send_message). Otherwise, it will call [`followup.send`](https://docs.disnake.dev/en/latest/api/webhooks.html#disnake.Webhook.send).

Note

This method does not return a [`Message`](https://docs.disnake.dev/en/latest/api/messages.html#disnake.Message) object. If you need a message object, use [`original_response()`](https://docs.disnake.dev/en/latest/api/interactions.html#disnake.Interaction.original_response) to fetch it, or use [`followup.send`](https://docs.disnake.dev/en/latest/api/webhooks.html#disnake.Webhook.send) directly instead of this method if you’re sending a followup message.
faint stone
vale wing
#

Better do

faint stone
#

after assigning an event loop, the error i was looking for appeared at the top

vale wing
#

That will give me clear understanding

faint stone
blazing condor
#

ah i see, so inter.send just sends the avatar itself without the link to it.

faint stone
#

if i could get it on the same loop, then it looks like it should be fine?

vale wing
#

I actually think you should not create loop manually at all

#

Just asyncio.run the main

#

Libraries typically get the active loop and work with it

compact plank
#

what should i use to build my bot ?? python.py ??

blazing condor
#

there's alot of libs to use, I'd suggest looking them up and see what you prefer.

blazing condor
#

looking them up and see what you prefer.

did u miss this part.

dawn lion
#

How create a simple discord button, me need this for button2role, how to reate it?

blazing condor
dawn lion
blazing condor
#

that tells me nothing.

#

without code, and example. It's hard to help someone.

dawn lion
#

Sigma face

#
# ИМПОРТЫ
import discord
from discord.ext import commands
from settigns import session, select_server
from discord.ui import View, Button

# НАСТРОЙКИ
intn = None #discord.Intents.all()
suntale = commands.Bot(command_prefix=session['prefix'], intents=intn)

@suntale.event
async def on_ready():

    # Успешный запуск!
    print('')
    print(f' ✅ SunTale Bot succesfuly connected with:')
    print()
    print(f" | ID: {suntale.user.id}")
    print(f" | Name: {suntale.user.name}#0")
    print("")

    # Задаем боту статус
    #await suntale.change_presence(activity=discord.Streaming(name="SunTale Network", url=url))

async def button_callback(interaction: discord.Interaction):
    await interaction.message.edit(content=f'Последним на кнопку нажал: {interaction.user.name}')

@suntale.command()
async def button(ctx):
    try:
        view = View(timeout=None)
        button = Button(label='Кнопка', style=discord.ButtonStyle.red, emoji="🥑")
        button.callback = button_callback
        view.add_item(button)

        await ctx.send(view=view)
    except Exception as e:
        print(e)
suntale.run(session['token'])
#

@blazing condor error

#

without error

blazing condor
#

i see no error provided. what is the error.

dawn lion
blazing condor
#

🤦🏽‍♂️

dawn lion
blazing condor
#

you still have yet to show me an error.

#

what's happening vs what're you trying to do exactly.

dawn lion
#

@blazing condor

dawn lion
#

@blazing condor

blazing condor
#

can u not ping me multiple times.

#

that would make me not wanna respond.

dawn lion
#

you bru

void mauve
#

How to dynamically change the name of a button? Seems like button.label aint doing a thing

class InformationView(discord.ui.View):

    def __init__(self, lang: str = ''):
        super().__init__(timeout=None)
        self.lang = lang

    @discord.ui.button(
        label='Optimize', style=discord.ButtonStyle.blurple,
        custom_id='persistent_view:optimize'
    )
    async def optimization(self, button: discord.ui.Button, interaction: discord.Interaction):
        button.label = messages[self.lang]['buttons']['optimize']

        await interaction.response.edit_message(embed=create_embed(messages[self.lang]['info']['optimize_title'],
                                                                   messages[self.lang]['info']['optimize_desc']),
                                                view=BackInformationView(self.lang))

    @discord.ui.button(
        label='Time', style=discord.ButtonStyle.blurple,
        custom_id='persistent_view:time'
    )
    async def time(self, button: discord.ui.Button, interaction: discord.Interaction):
        button.label = messages[self.lang]['buttons']['time']

        await interaction.response.edit_message(embed=create_embed(messages[self.lang]['info']['time_title'],
                                                                   messages[self.lang]['info']['time_desc']),
                                                view=BackInformationView(self.lang))
fading marlin
#

Set view in edit_message to the current instance of InformationView instead of creating a new one

faint stone
#

it literally runs in it's own thread and event loop

#

you can check the source code to see it doing that

#

also why bring this up when the gateway issue is fixed now

vale wing
faint stone
#

but this error doesn't stop the bot from running properly, just stops the application from setting slash commands

blazing condor
#

I've never worked with disnake and i just read over the documentation, setup something real quick and no issue.

faint stone
#

good for you

#

I'm wondering if you used .run()?

faint stone
blazing condor
faint stone
#

hold on

blazing condor
#

And that’s not the current one is it

faint stone
#

it pretty much is, i haven't done anything major

#

okay, i figured something out

#

I did this in a blank project with the same token, but used it to create my slash commands with client.run()

#

once I was done, I could just turn my actual bot back on and it would respond to the commands as if it registered them

#

which is enough for me

#

it turns out, creating a event loop of any kind causes disnake startup futures to get bound to the wrong event loop, regardless of if you pass the right one in

#

going to report this because it pretty much seems like a bug

lethal hemlock
#

Does anybody know a good vps for hosting your own bots

final iron
#

!d discord.app_commands.has_permissions

unkempt canyonBOT
#
NEGATORY.

No documentation found for the requested symbol.

final iron
#

One moment

#

!d discord.app_commands.checks.has_permissions

unkempt canyonBOT
#

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

Note that this check operates on the permissions given by [`discord.Interaction.permissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.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/interactions/api.html#discord.app_commands.MissingPermissions) that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure).

New in version 2.0...
final iron
#

It’ll raise a MissingPermissions error which you can handle

#

I’m heading to sleep but there’s an example somewhere in the GitHub on how to create a command specific error handler

#

It’ll raise an error as well

dense mesa
#

Anyone here wanna collaborate?

spark patio
dense mesa
#

Ok take a look at this and give me your thoughts or questions.

#

... Minus the grammatical errors lol I'm designing this on a smartphone

drifting arrow
#

we still discussing discordbots?

#

am i in the correct discord?

#

How does one go from level 1 to level 2?

#

and from level 2 to 3 etc?

#

also it requires arrows to dictate the flow.

#

between migrant and citizen, you definitely need something to indicate that they applied, and if they succeed go to citizen if fail, go back to migrant.

sick coyote
#

is it possible to get a user about me?

final iron
drowsy walrus
#

How can I save a channels overwrites and apply them to a new channel? Any well known methods about it?

thorn vapor
#

can anyone help me with this im getting this error everytime i try to install discord library on my new pc it ran without any issue in my old pc

thorn vapor
slate swan
#

most libraries dont support 3.12 yet

#

so this might be the case

thorn vapor
#

ok imma try installing 3.11 then

dawn lion
#

i have this code:

class MyView(discord.ui.View): # Create a class called MyView that subclasses discord.ui.View
    @discord.ui.button(label="Click me!", style=discord.ButtonStyle.primary, emoji=":sunglasses:") # Create a button with the label ":sunglasses: Click me!" with color Blurple
    async def button_callback(self, button, interaction):
        await interaction.response.send_message("You clicked the button!") # Send a message when the button is clicked

@suntale.command() # Create a slash command
async def button(ctx):
    await ctx.send("This is a button!", view=MyView()) # Send a message with our View class that contains the button

And him return this (when i click on button):

discord.ui.view: Ignoring exception in view <MyView timeout=180.0 children=1> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Click me!' emoji=<PartialEmoji animated=False name='😎' id=None> row=None>
Traceback (most recent call last):
  File "C:\Users\Frusi\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "mine_bot.py", line 28, in button_callback
    await interaction.response.send_message("You clicked the button!") # Send a message when the button is clicked
AttributeError: 'Button' object has no attribute 'response'
Traceback (most recent call last):
  File "C:\Users\Frusi\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "mine_bot.py", line 28, in button_callback
    await interaction.response.send_message("You clicked the button!") # Send a message when the button is clicked
AttributeError: 'Button' object has no attribute 'response'
robust fulcrum
swift pumice
#

hi

lone hare
#
ne 3, in <module>
    from discord_slash import SlashCommand
ModuleNotFoundError: No module named 'discord_slash'```
#

what's up with this ? i can't find the library name

#

anyone pls help ?

hushed galleon
lone hare
hushed galleon
#

eh, even if it had the latest information, there aren't a lot of online resources explaining this anyway

haughty dagger
#

I am using autocomplete for my help command and I am passing name of the command and class of the command as a value. But it seems like d.py is forcing me to use str type for my app_command argument.

Is there any way to access the value of app_commands.Choice in autocomplete?

final iron
#

value is a kwarg

haughty dagger
#

str

#

when using autocomplete we cannot set parameter type as app_commands.Choice