#discord-bots

1 messages · Page 385 of 1

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.

shadow vigil
#

depending on the discord library

hard kite
#

uhm i wanna get a user object with a user

#

i meani have a user ID

#

and i wanna get its data

#

how...

fast osprey
#

!d discord.Client.fetch_user

hard kite
#

hmmm

unkempt canyonBOT
#

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

Retrieves a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User) based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.

Note

This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_user) instead.

Changed in version 2\.0: `user_id` parameter is now positional\-only.
hard kite
#

oh

#

thanks

#

uhm... onother thing

so we know the id of a channel now we wanna get its webhook....

#

i wanna make something like amoji function to it

fast osprey
#

A channel could have several webhooks

hard kite
#

yeah

#

i wanna make one

#

or to se if theres a existing one and get that

fast osprey
#

What if there are multiple?

hard kite
#

!d discord.Client.fetch_webhook

unkempt canyonBOT
#

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

Retrieves a [`Webhook`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook) with the specified ID.

Changed in version 2\.0: `webhook_id` parameter is now positional\-only.
fast osprey
#

What you probably want is to make and remember one for your application specifically

#

Not just pull for any webhook that exists

hard kite
#

well what if my application forget that it creates one

fast osprey
#

Then it should remember it?

hard kite
#

well i mean am using json

fast osprey
#

You should be using a database

#

Then you only need to make the webhook once and store its url

hard kite
#

my pc is a potato

#

ill use that ones i get better pc

#

i mean how can i get list of available webhook? if thats posible

hard kite
fast osprey
#

That's something worth learning

hard kite
#

yeah i know

#

i also heard that its like a server

fast osprey
#

You are risking your application data if you're writing to a flat file

#

It's not

fast osprey
#

It doesn't have to be at least. SQLite is literally just a file format + driver libraries

#

A bad write to a flat file will corrupt all of your data irreversibly

hard kite
#

yeah that makes sence

#

ill learn that soon

#

is there a way to get a list of existing webhook?

#

that will make it super easy

fast osprey
#

It won't

#

Because again, a channel can have several. If you want one for your use, you should make it and remember it

hard kite
#

i dont want my code to always create one everytime i messed with my json file 🥲

#

most of the time i dont know what am doing and i just run the code to se if it will work or what

fast osprey
#

"Mess with"? If you don't trust your data storage why are you storing data to begin with

#

Data your application relies on to function shouldn't just randomly get invalidated lol

hard kite
#

welp i am just year on programing and python 🥲

fast osprey
#

So let's say you have the list of webhooks on a channel. How do you pick which one is the one you want, if any?

hard kite
fast osprey
#

Which might be a webhook someone else made for some other purpose?

hard kite
#

wait the bot can delete a webhook?

#

i can just create webhook and delete after using....

fast osprey
#

You shouldn't be constantly spinning these up and down

#

What are you trying to use it for?

hard kite
#

uhm.... i dont know tbh i just wanna play with webhooks

fast osprey
#

You could just make one manually and hardcode the url in and go nuts

#

It's just a different way to send messages. It really only serves a purpose if you want a spot where you don't need a connected gateway bot

#

If you already have a connected bot it doesn't really give you anything you couldn't do by just sending a message normally

hard kite
#

maybe i can make it a emoji bot ._. where it will detect the user if he cant use that emoji and the bot will try to make webhook and send the same message with emoji on

fast osprey
#

If you just want to send a message, you don't need to create a webhook to just send that one message

hard kite
#

so webhook on each channel ._.

fast osprey
#

Just send the message directly...?

hard kite
#

how that helps

fast osprey
#

Because you don't need the overhead of creating a webhook

#

You just make one api call: send message

hard kite
#

well you will have a list of all channels then

fast osprey
#

Yeah

#

I mean your bot can access the list of channels it can see sure

hard kite
#

i ment is "list of webhooks for all channels"

fast osprey
#

Why do you care about webhooks still? You can just send messages normally

hard kite
#

ig to clean the webhook menu on discord?

hard kite
fast osprey
#

The library lets you send messages directly to channels

#

You don't need a webhook

#

!d discord.TextChannel.send

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.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
hard kite
fast osprey
#

If that's the goal, no

hard kite
#

welp thats the goal here

#

something like this

#

wait

fast osprey
#

Then I strongly recommend you do what I said initially, which is make a webhook once and remember that webhook

#

!d discord.TextChannel.webhooks

unkempt canyonBOT
#

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

Gets the list of webhooks from this channel.

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

This is the list of webhooks on a channel if you want it though

hard kite
#

like this

#

they hardcoded thier webhooks tho...

fast osprey
#

You would need a webhook on every channel you want this done on

#

Not sure what the limits are tbh

hard kite
#

i want it to be clean as posible...

fast osprey
#

This is kind of a bastardization of what webhooks were made for tbh

hard kite
#

eh whats the "bastardization"?

fast osprey
#

They were made for specific external systems to post updates into a specific place in discord

#

Not for one bot to make a ton of them in every channel just for the sole purpose of mimicking users

#

You might be able to get this to work, but again I don't know the limits on how many and how often you can make new webhooks

hard kite
#

wait its will also get rate limited?

fast osprey
#

Maybe shrug . This is using webhooks in an unintended scale

hard kite
#

well ill just dont do that then...

fast osprey
#

Try it and see I guess

hard kite
#

its just fun to se the bot allowing me to use emoji that i cant use

fast osprey
#

Docs I'm seeing say 10 webhooks per server

hard kite
#

thats too limited ._.

#

how about the rate????

fast osprey
#

Rate limit of creating webhooks is unpublished like all endpoints

#

Rate limit of sending messages through the webhook is well documented but I don't remember off top of head

hard kite
#

i forgot what will happen if you got rate limited ....

#

welp ill go back into another coding session

fast osprey
#

If you're using the library, it just slows down and stops doing the thing until it's allowed to

#

Like if discord says "you can only make 5 webhooks an hour", the library will make 5 and then sleep for an hour on creating the 6th (while still operating everything else normally)

stark ingot
#

It will eventually give up right?

fast osprey
#

It doesn't keep trying

#

discord tells you what the limit is and when it will reset

#

the library just sleeps to respect that

slate swan
#

Hi! I’m using next cord and I’m wondering if there is any way to load new slash commands in a server without having to invite the bot again?

#

(Ping me or dm me when responding I might be asleep)

scarlet tiger
slate swan
#

FR?

#

nahhhhhh I’m dumb dumb big dumb

scarlet tiger
mild token
#

how i can print server all emoji with their id id:name in this format? i think i got it

viscid gazelle
#

is there an api function to screenshare?

viscid gazelle
#

how fast could yo update a message with a new image

#

without getting rate limited?

slate swan
#

Can bots Screenshare?

#

I have seen before

late gate
#

fuck you

#

bitch

fast osprey
slim bloom
#
from discord.ext import commands

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

    @commands.Cog.listener()
    async def on_ready(self):
        print(f'Cog {self.__class__.__name__} is ready')

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

Why doesn't it print that the cog is ready but it does load correctly?

opaque knot
#

if someone rejoins when the bot is offline, it would not know and still tag them as NOT rejoined?

fast osprey
#

Member flags are stored by discord, not your bot

opaque knot
#

lemme force a rejoin

#

aight nvm it works

woven blade
#

hello peeps

slate swan
#

how do i sync slash commands to a single guild instead of all of discord with discord.ext?

#

because it takes forever when im trying to test

fast osprey
#

It doesn't, it's instant

#

What's probably happening is you need to refresh your client

slate swan
#

I need help setting this bot up

#

@slate swan I can’t talk

#

Won’t let me

slim bloom
#

I have a question, what is the correct place to load cogs, in the setup_hook?

wanton current
#

load_extensions? either setup_hook or your own runner function

fast osprey
#

There is no strictly correct place

#

You put it where you want it to happen

wanton current
#

except on_ready

slim bloom
wanton current
#

!d discord.on_ready

unkempt canyonBOT
#

discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.guilds) and co. are filled up.

Warning

This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
wanton current
#

there's a warning

slim bloom
slim bloom
# wanton current there's a warning
    if not os.path.exists('src/cogs'):
        print('Cog folder does not exist')
        return
    
    for filename in os.listdir('src/cogs'):
        if filename.endswith('.py') and filename != '__init__.py':
            try:
                cog_name = f'src.cogs.{filename[:-3]}'
                await bot.load_extension(cog_name)
                print(f'Loaded cog: {cog_name}')
            except Exception:
                print(f'Failed to load cog: {filename[:-3]}')
                traceback.print_exc()

async def main():
    await setup_hook()
    await bot.start(os.getenv('BOT_TOKEN'))

if __name__ == "__main__":
    asyncio.run(main())
``` this is correct?
fast osprey
#

You calling the method setup_hook in that scenario doesn't do anything

#

Also consider using pkgutil to look for modules rather than looping over a directory's files yourself

slim bloom
# fast osprey You calling the method setup_hook in that scenario doesn't do anything
    if not os.path.exists('src/cogs'):
        print(f'Cog folder does not exist')
        return
    
    for filename in os.listdir('src/cogs'):
        if filename.endswith('.py') and filename != '__init__.py':
            try:
                await bot.load_extension(f'src.cogs.{filename[:-3]}')
                print(f'Loaded cog: {filename[:-3]}')
            except Exception:
                print(f'Failed cog: {filename[:-3]}')
                traceback.print_exc()


async def main():
    await load_cogs()
    await bot.start(os.getenv('BOT_TOKEN'))

if __name__ == "__main__":
    asyncio.run(main())```?
fast osprey
#

This currently turns off logging from the library (and doesn't fix the other things I said) but otherwise sure

slim bloom
# fast osprey This currently turns off logging from the library (and doesn't fix the other thi...
import pkgutil
async def load_cogs():
    if not os.path.exists(os.path.join('src', 'cogs')):
        print(f'Cog folder does not exist')
        return
    
    for _, filename, _ in pkgutil.iter_modules([os.path.join('src', 'cogs')]):
            if filename == '__init__':
                pass
            try:
                await bot.load_extension(f'src.cogs.{filename}')
                print(f'Loaded cog: {filename}')
            except Exception:
                print(f'Failed cog: {filename}')
                traceback.print_exc()


async def main():
    await load_cogs()
    await bot.start(os.getenv('BOT_TOKEN'))

if __name__ == '__main__':
    asyncio.run(main())```
slim bloom
fast osprey
#

If used properly, it sets up logging for you by default and you don't need to spin up an event loop yourself

slim bloom
# fast osprey *If* used properly, it sets up logging for you by default and you don't need to ...

for example this:? ```py
async def load_cogs():
if not os.path.exists('src/cogs'):
print('Cog folder does not exist')
return

for _, filename, _ in iter_modules(['src/cogs']):
        if filename == '__init__':
            pass
        try:
            await bot.load_extension(f'src.cogs.{filename}')
            print(f'Loaded cog: {filename}')
        except Exception:
            print(f'Failed cog: {filename}')
            traceback.print_exc()

async def setup_hook():
await load_cogs()

if name == 'main':
bot.setup_hook = setup_hook
bot.run(os.getenv('BOT_TOKEN'))

fast osprey
#

You shouldn't be stapling methods onto objects directly. This is what subclassing is for

#

It's also a bit odd that you have one line in your setup_hook which is just calling another method, it's an unnecessary layer of indirection. But otherwise the approach is sound

crude remnant
#
    ^
IndentationError: expected an indented block after function definition on line 219``` anyone know what it means?
solar bone
solar bone
crude remnant
solar bone
#

cold

#
  async def on_ready():
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
  File "/home/container/bot.py", line 566, in <module>
    @bot.command(name='av', help='Get the avatar of a user.')
     ^^^^^^^^^^^
AttributeError: 'Command' object has no attribute 'command'```
#

anyone help?

golden portal
#

You have a command named bot that overshadowed your bot's var

slim bloom
#

I have a question, why since I implemented cogs to my bot now it no longer throws errors in the console and only "NoneType: none" appears, could it be because of using bot.start?

#

I tried with the traceback library and logging exc_info=True and nothing

shrewd apex
#

did u run discord.utils.setup_logging()

#

!d discord.utils.setup_logging

unkempt canyonBOT
#

discord.utils.setup_logging(*, handler=..., formatter=..., level=..., root=True)```
A helper function to setup logging.

This is superficially similar to [`logging.basicConfig()`](https://docs.python.org/3/library/logging.html#logging.basicConfig) but uses different defaults and a colour formatter if the stream can display colour.

This is used by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) to set up logging if `log_handler` is not `None`.

New in version 2\.0\.
mint pecan
#

is there a similar method to commands.command but for events? so that i can add the events to the bot later

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.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
hard kite
#

Uhm guys

#

Member.send will do what?

fast osprey
#

What the docs says. Sends a message to the destination (that member)

hard kite
#

Why I don't understand it 😭

hard kite
fast osprey
#

To that member. In a dm

hard kite
#

To first channel posible???

hard kite
#

Okay

fast osprey
#

You can also just declare a normal ass function and add it as a listener directly without needing a cog

finite salmon
#

I personally prefer having a separate cog just for listeners

fast osprey
#

Yeah to each their own, just putting the options out there. There are cases where you'd want either

slim bloom
fast osprey
#

I suggest you group things by functional groupings, i.e. all the things required for a particular feature or module

#

There's really not a case where you'd want to load/unload all listeners across all features (but not the other things related to those features), which is the whole purpose of cogs to have atomic loading/unloading

slate swan
#

hey guys

#

who know make a discord bot that can auto message a disocrd user

#

in channels

hearty basalt
#

"auto message a user in channels"?

fast osprey
#

Yeah you'll have to describe what it is you want to do, and when you want to do it

unreal moss
#

guys i need some coding help ill pay robux just dm me its not a scam or anything

fast osprey
unkempt canyonBOT
#

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

stiff gorge
#

.

slate swan
#

What should be included in a on command error handler for a multipurpose bot

fast osprey
#

"Multipurpose" isn't particularly descriptive tbf

#

The error handler is for centralizing logic you want to happen when different errors occur, so I guess catalogue what kinds of errors you expect to happen and what you want to do when they happen

#

At minimum this should include putting as much detail about the error somewhere (reliably) that you can review it

slate swan
#

how do I make a command that will enlarges emojis like 🔥 (normal emojis) and SP_shrug (custom emojis) both

#

not asking to be spoonfeed btw ;3

fast osprey
#

Define "enlarge"

#

Like produce a zoomed image?

finite salmon
#

For default emojis you could place it as a text and size up it's font maybe

#

And you can get the image of custom emoji and scale it up

fast osprey
#

Those discord just sends you the Unicode. You will need to store/look up an image for them

slate swan
finite salmon
#

You can download a font package which have emojis in iy

slate swan
#

or how they would do that

finite salmon
#

You can download the tff from here

#

The one discord and twitter use

solar bone
#

@bot.command(name='activate')async def activate(ctx):
   await ctv.send('activated dev badge')

#

why no work

fast osprey
#

This should cause an error

solar bone
#

but it doesnt oH

#

I WROTE CTV

#

MB MB

fast osprey
solar bone
fast osprey
#

Should be the first thing you look for

dire timber
#

I seem to still be failing at interactions even though I'm following the documentation that was recommended to me earlier this week

Not exactly sure what I'm missing here as this is inside a cog instead of on the main file

    @commands.command()
    async def memorylist(self, ctx:commands.Context) -> None:
        # print(dir(ctx))
        view = BaseView("User")
                  view.add_item(discord.ui.Button(label="Test", style=discord.ButtonStyle.blurple))
        view.message = await ctx.send("Testing", view=view)
#

this is the view that I created

class BaseView(discord.ui.View):
    interaction: discord.Interaction | None = None
    message: discord.Message | None = None

    def __init__(self, user: discord.User | discord.Member, timeout: float = 60.0):
        super().__init__(timeout=timeout)
        self.user = user


    async def interaction_check(self, interaction: discord.Interaction) -> bool:
        # if interaction.user.id != self.user.id:
        #     await interaction.response.send_message(
        #         "You cannot interact with this view.", ephemeral=True
        #     )
        #     return False
        await interaction.response.send_message("Hi", ephemeral=True)
        self.interaction = interaction
        
        return True
#

basically just copy pasted from the docs

scarlet tiger
#

view = BaseView("User")

dire timber
#

oh I forgot to change it to this

BaseView(ctx.author)
#

just altered it on my IDE

scarlet tiger
dire timber
#

no 😦

scarlet tiger
dire timber
#
from __future__ import annotations

import typing
import traceback
import discord
import os
from discord.ext import commands
from discord.ext.commands import BucketType, cog, BadArgument, command, cooldown
from embedconfig import EmbedClass
# from pagination import BaseView

from discord.ui.select import BaseSelect
scarlet tiger
dire timber
#

oh there's a difference?

scarlet tiger
dire timber
#
Package           Version
----------------- -------
...
discord.py        2.4.0
...
scarlet tiger
#

I'm not really sure how the interactions work in discord.py. Why don't you use a callback?

dire timber
#

this is also inside the view class

    async def on_error(self, interaction: discord.Interaction, error: Exception, item: discord.ui.Item[BaseView]) -> None:
        tb = "".join(traceback.format_exception(type(error), error, error.__traceback__))
        message = f"An error occurred while processing the interaction for {str(item)}:\n
py\n{tb}\n"
        self._disable_all()
        await self._edit(content=message, view=self)
        self.stop()
scarlet tiger
#

I think it is better to add the button to its own class

dire timber
#

would I need to call interaction.response.send_message directly?

#

smth like this

def calller():
  await interaction.response.send_message()
  return True
scarlet tiger
# dire timber smth like this ``` def calller(): await interaction.response.send_message() ...

You can follow this example, but you must adapt it to your needs:

from discord.ui import Button, View
from discord import Interaction

class MyButtton(Button):
    def __init__(self, ...):
        super().__init__(...)
    
    async def callback(self, interaction: Interaction):
        # ...
        pass

class MyView(View):
    def __init__(self):
        super().__init__(...)
    
    async def interaction_check(self, interaction: Interaction)
        # ...
        pass

view = MyView()
view.add_item(MyButtton(...))
dire timber
#

ok thanks

shrewd apex
shrewd apex
#

so while the interaction check passes it has nothing to do

scarlet tiger
shrewd apex
#

i see

dire timber
#

I did try to follow one of Rappitz's examples though and I still got an interactions error even with a callback

#

This is the code I used

#

so I'm not sure if I missed a config setting on my bot or smth

scarlet tiger
dire timber
scarlet tiger
#

No, I mean how you have created the bot instance in your code

dire timber
#

should be in the pastebin

#
bot = TicTacToeBot()


@bot.command()
async def tic(ctx: commands.Context):
    """Starts a tic-tac-toe game with yourself."""
    await ctx.send('Tic Tac Toe: X goes first', view=TicTacToe())

bot.run(TOKEN)
#

or here

#
class TicTacToeBot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.default()
        intents.message_content = True

        super().__init__(command_prefix=commands.when_mentioned_or('$'), intents=intents)

    async def on_ready(self):
        print(f'Logged in as {self.user} (ID: {self.user.id})')
        print('------')
shrewd apex
#

is ur discord client updated to latest version

#

and are u using some proxy or vpn

scarlet tiger
#

It's very strange

#

Try using defer()

shrewd apex
#

another possibility if ur network latency is too bad

scarlet tiger
#

Yeah

shrewd apex
#

you should respond to all interactions within 3s

dire timber
#

alright one sec

shrewd apex
#

if u are not able to make interaction.response.defer() your first instruction and then at the end do interaction.edit_original_response()

dire timber
#

ok let me restart my discord client

dire timber
#

just normal network connection

#

put the defer to my callback like this?

async def callback(self, interaction: discord.Interaction):
        await interaction.response.defer()
scarlet tiger
#

Yes

dire timber
#

hmm strange

#
class TicTacToeButton(discord.ui.Button['TicTacToe']):
    def __init__(self, x: int, y: int):
        super().__init__(style=discord.ButtonStyle.secondary, label='\u200b', row=y)
        self.x = x
        self.y = y

    async def callback(self, interaction: discord.Interaction):
        await interaction.response.defer()
        assert self.view is not None
        view: TicTacToe = self.view
        state = view.board[self.y][self.x]
        if state in (view.X, view.O):
            return

        if view.current_player == view.X:
            self.style = discord.ButtonStyle.danger
            self.label = 'X'
            self.disabled = True
            view.board[self.y][self.x] = view.X
            view.current_player = view.O
            content = "It is now O's turn"
        else:
            self.style = discord.ButtonStyle.success
            self.label = 'O'
            self.disabled = True
            view.board[self.y][self.x] = view.O
            view.current_player = view.X
            content = "It is now X's turn"

        winner = view.check_board_winner()
        if winner is not None:
            if winner == view.X:
                content = 'X won!'
            elif winner == view.O:
                content = 'O won!'
            else:
                content = "It's a tie!"

            for child in view.children:
                child.disabled = True

            view.stop()

        await interaction.response.edit_message(content=content, view=view)
#

I put the defer function call at the very top

finite salmon
dire timber
#

At the bottom?

finite salmon
#

You use followup when you defer the interaction or when u need to send a second interaction

finite salmon
#

And also do you get any errors

dire timber
#

👍

#

no 😔

finite salmon
#

Weird

dire timber
#

sigh no dice

#
    async def callback(self, interaction: discord.Interaction):
        await interaction.response.defer(ephemeral=True)
        assert self.view is not None
        view: TicTacToe = self.view
        state = view.board[self.y][self.x]
        if state in (view.X, view.O):
            return

        if view.current_player == view.X:
            self.style = discord.ButtonStyle.danger
            self.label = 'X'
            self.disabled = True
            view.board[self.y][self.x] = view.X
            view.current_player = view.O
            content = "It is now O's turn"
        else:
            self.style = discord.ButtonStyle.success
            self.label = 'O'
            self.disabled = True
            view.board[self.y][self.x] = view.O
            view.current_player = view.X
            content = "It is now X's turn"

        winner = view.check_board_winner()
        if winner is not None:
            if winner == view.X:
                content = 'X won!'
            elif winner == view.O:
                content = 'O won!'
            else:
                content = "It's a tie!"

            for child in view.children:
                child.disabled = True

            view.stop()

        await interaction.followup.edit_message(content=content, view=view)
#

this is all I see on my CLI

$ python main.py
2024-08-17 17:10:25 INFO     discord.client logging in using static token
2024-08-17 17:10:27 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: 8b5dfb9b76dcb7ea5f5b4133b9b97b65).
Logged in as Test Bot#5987 (ID: 517689574579896341)
------
finite salmon
#

Do you have logging enabled

dire timber
#

Like this?

import logging
logger = logging.getLogger(__name__)
...
@bot.command()
async def tic(ctx: commands.Context):
    logging.basicConfig(filename='myapp.log', level=logging.DEBUG)
    logger.info('Started')
    """Starts a tic-tac-toe game with yourself."""
    await ctx.send('Tic Tac Toe: X goes first', view=TicTacToe())

bot.run(TOKEN)
viscid hornet
viscid hornet
#

is it a latency issue then?

dire timber
#

i dont know

viscid hornet
#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

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

Defers the interaction response.

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

This is only supported with the following interaction types...
viscid hornet
#

!d discord.ext.commands.Bot.latency

unkempt canyonBOT
#

property latency```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.

This could be referred to as the Discord WebSocket protocol latency.
viscid hornet
#
@bot.command()
async def ping(ctx):
    await ctx.reply(f"Bot latency: {bot.latency}")
dire timber
#
@bot.command()
async def ping(ctx):
    message = f'⏱|** {round(bot.latency * 1000)} ms** Latency!'
    title = "Ping"
    embed = EmbedClass(message, title)
    await ctx.send(embed=embed.embed)
#

I used this

grizzled onyx
#

why does role.members literally return nothing

slate swan
#

Hello

#

can anyone help me fix this problem pls

grizzled onyx
slate swan
grizzled onyx
slate swan
slate swan
grizzled onyx
#

response_data['txId']

slate swan
#

ok

#

without the ()

grizzled onyx
slate swan
#

ok i do rn

grizzled onyx
grizzled onyx
slate swan
grizzled onyx
grizzled onyx
slate swan
#

im sorry if i dont undestand well im frensh so my english is a lil bad

#

i will try rn

#

can u edit this part and told me what to paste

grizzled onyx
grizzled onyx
slate swan
grizzled onyx
#

yea

slate swan
grizzled onyx
#

brackets are required

ruby cairn
#

Hello, can anyone explain me async def {command_name}(ctx) ? i mean we type ctx for context but we can use others things, but when ?

#

i think it's easy but i don't know about it

slate swan
grizzled onyx
slate swan
#

mean here ?

#

ok wait

grizzled onyx
#

you should learn the basic python syntax before writing anything in it.

slate swan
grizzled onyx
#

NO

slate swan
grizzled onyx
#

edit(content="")

slate swan
grizzled onyx
slate swan
#

yeah i did

grizzled onyx
#

I don't want to write the link, but you understand

#

@slate swannobody will write code for you here, it's better to study the syntax

slate swan
#

yep

slate swan
#

rn should work ?

#

@grizzled onyx

grizzled onyx
#

CHECK

slate swan
#

whats the problem ?

grizzled onyx
grizzled onyx
slate swan
#

it say me this

slate swan
#

i will replace them like the otheer ones

grizzled onyx
#

@slate swancomparer les deux variables et leurs clés response_data

fast osprey
#

SELF-BOT

#

Not really subtle there

slate swan
grizzled onyx
slate swan
fast osprey
#

Yeah you're trying to run a self bot here. This is against TOS

grizzled onyx
fast osprey
#

wym wym

#

Pretty straightforward

grizzled onyx
slate swan
#

why its against tos

#

i just wanna use it to check received payement from ltc

fast osprey
#

Because discord said don't do it

slate swan
#

.ltc

fast osprey
#

If you want to do automation, put it behind a bot account

slate swan
fast osprey
#

What does that have to do with this breaking tos lol

slate swan
#

lmao g i dont wanna break anything

fast osprey
#

Any code you write must act on a bot account, not a personal user one

slate swan
#

ok i understand

#

but at least can i know why i had error inside error ? @grizzled onyx

grizzled onyx
slate swan
#

so whats this exactly

fast osprey
#

It doesn't like the token you gave it

grizzled onyx
#

error on error, I meant that there are a lot of errors, at least that's what they say in Russian

slate swan
fast osprey
#

Yeah don't do that

slate swan
fast osprey
#

Make a real bot, and get a real bot token

scarlet tiger
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
#

ok guys sorry for that

#

and thanks to @grizzled onyx for his help !

slate swan
dire timber
# finite salmon Do you have logging enabled

I managed to get the logging

DEBUG:discord.http:POST https://discord.com/api/v10/channels/512594875284455424/messages with {"content":"Tic Tac Toe: X goes first","components":[{"type":1,"components":[{"type":2,"style":2,"disabled":false,"label":"\u200b","custom_id":"95611f1b3aceed0159da7a1be2e2c21c"},{"type":2,"style":2,"disabled":false,"label":"\u200b","custom_id":"71bae4157972b4f387aa31f798937881"},{"type":2,"style":2,"disabled":false,"label":"\u200b","custom_id":"8d11bdbb055dc770c4053fbf69631170"}]},{"type":1,"components":[{"type":2,"style":2,"disabled":false,"label":"\u200b","custom_id":"4bf9e70c520ebc88641f4b1c39db1a8f"},{"type":2,"style":2,"disabled":false,"label":"\u200b","custom_id":"7a8037802917c46b27f435bad505e61e"},{"type":2,"style":2,"disabled":false,"label":"\u200b","custom_id":"dced0d3cddbd759cd49ef2982ee455fc"}]},{"type":1,"components":[{"type":2,"style":2,"disabled":false,"label":"\u200b","custom_id":"262f9e58c530b36d6d8029cd039c40d3"},{"type":2,"style":2,"disabled":false,"label":"\u200b","custom_id":"a1f24e4ea61fd33065afd4f5b0b1dac3"},{"type":2,"style":2,"disabled":false,"label":"\u200b","custom_id":"d69bc2f7ef0a359f9cc4b24e50ff9e1e"}]}],"tts":false} has returned 200
fast osprey
#

200 is a success

dire timber
#

hmm

#

I'm still getting this though

#

I've been having issues with my interactions

#

I just spun up a VPS in canada because my local PC is in Australia and I think all of the discord servers are hosted over there

#

now my ping is at 36ms but I can't quite figure out what's going on with this

#

the people that attempted to help were unsure as to why i was getting interaction failures even though my code was fine

fast osprey
#

There's not an issue with sending the message

#

There's an issue with responding to the interaction

#

Either you are trying to respond and there's an error, or you never try to respond. You should do some debugging to narrow down between the two

dire timber
#

I just took one of the examples from the discord.py repo

async def callback(self, interaction: discord.Interaction):
        # await interaction.response.defer(ephemeral=True)
        assert self.view is not None
        view: TicTacToe = self.view
        state = view.board[self.y][self.x]
        if state in (view.X, view.O):
            return

        ...

        await interaction.followup.edit_message(content=content, view=view)

this is the callback function from that

fast osprey
#

Do you know if that's being called at all?

dire timber
#

let's see...

#

ok so no it isn't

#

I added a print statement just to test

#

i do not know why it's not being called

fast osprey
#

Well what's the full context here? Just there existing a method named callback doesn't mean the library is going to try to call it

dire timber
#

one moment

#
from typing import List
from discord.ext import commands
import discord
import os
import logging
logger = logging.getLogger(__name__)
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
from embedconfig import EmbedClass
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
#
class TicTacToeButton(discord.ui.Button['TicTacToe']):
    def __init__(self, x: int, y: int):
        super().__init__(style=discord.ButtonStyle.secondary, label='\u200b', row=y)
        self.x = x
        self.y = y

    async def callback(self, interaction: discord.Interaction):
        # await interaction.response.defer(ephemeral=True)
        print("Calling callback function")
        assert self.view is not None
        view: TicTacToe = self.view
        state = view.board[self.y][self.x]
        if state in (view.X, view.O):
            return

        if view.current_player == view.X:
            self.style = discord.ButtonStyle.danger
            self.label = 'X'
            self.disabled = True
            view.board[self.y][self.x] = view.X
            view.current_player = view.O
            content = "It is now O's turn"
        else:
            self.style = discord.ButtonStyle.success
            self.label = 'O'
            self.disabled = True
            view.board[self.y][self.x] = view.O
            view.current_player = view.X
            content = "It is now X's turn"

        winner = view.check_board_winner()
        if winner is not None:
            if winner == view.X:
                content = 'X won!'
            elif winner == view.O:
                content = 'O won!'
            else:
                content = "It's a tie!"

            for child in view.children:
                child.disabled = True

            view.stop()

        await interaction.followup.edit_message(content=content, view=view)
#
class TicTacToe(discord.ui.View):
    # This tells the IDE or linter that all our children will be TicTacToeButtons
    # This is not required
    children: List[TicTacToeButton]
    X = -1
    O = 1
    Tie = 2

    def __init__(self):
        super().__init__()
        ...

        for x in range(3):
            for y in range(3):
                self.add_item(TicTacToeButton(x, y))

    # This method checks for the board winner -- it is used by the TicTacToeButton
    def check_board_winner(self):
            ...
            return self.Tie

        return None
#
class TicTacToeBot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.default()
        intents.message_content = True

        super().__init__(command_prefix=commands.when_mentioned_or('$'), intents=intents)

    async def on_ready(self):
        print(f'Logged in as {self.user} (ID: {self.user.id})')
        print('------')


bot = TicTacToeBot()


@bot.command()
async def tic(ctx: commands.Context):
    logging.basicConfig(filename='discord.log', level=logging.DEBUG)
    logger.info('Started')
    """Starts a tic-tac-toe game with yourself."""
    await ctx.send('Tic Tac Toe: X goes first', view=TicTacToe())

@bot.command()
async def ping(ctx):
    message = f'⏱|** {round(bot.latency * 1000)} ms** Latency!'
    title = "Ping"
    embed = EmbedClass(message, title)
    await ctx.send(embed=embed.embed)

bot.run(TOKEN, log_handler=handler, log_level=logging.DEBUG)
#

sorry that it's long but this is what I'm trying to run

#

this was mostly from the example on Rappitz's repo for discord.py

fast osprey
#

Can you implement an on_interaction event and log from there, then see if that fires when you click the button?

dire timber
#

what's the prefix to check docs here?

fast osprey
#

!d

dire timber
#

!d discord.on_interaction

unkempt canyonBOT
#

discord.on_interaction(interaction)```
Called when an interaction happened.

This currently happens due to slash command invocations or components being used.

Warning

This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View) instead as it provides a nicer user experience.

New in version 2\.0\.
dire timber
#

do I call the on_interaction function like this?

async def callback(self, interaction: discord.Interaction):
        discord.on_interaction(interaction)
#

Or does this need to be in the command function block?

fast osprey
#

No like register it as an event

#

Have you done that?

dire timber
#

No I have not

#

Sorry but I'm not sure how to do that

fast osprey
#

Er

#

!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...
dire timber
#

oh so like on_ready

#

Understood. Will give that a shot

fast osprey
#

Yes, but on_interaction. Checking to see if your bot is getting this interaction at all since the code looks fine

dire timber
#
@bot.listen()
async def on_interaction():
    print('Heard')

Like this?

fast osprey
#

Looks right

dire timber
#
@bot.command()
async def tic(ctx: commands.Context):
    logging.basicConfig(filename='discord.log', level=logging.DEBUG)
    logger.info('Started')
    """Starts a tic-tac-toe game with yourself."""
    await ctx.send('Tic Tac Toe: X goes first', view=TicTacToe())

@bot.command()
async def ping(ctx):
    message = f'⏱|** {round(bot.latency * 1000)} ms** Latency!'
    title = "Ping"
    embed = EmbedClass(message, title)
    await ctx.send(embed=embed.embed)

@bot.listen()
async def on_interaction():
    print('Heard')

bot.run(TOKEN, log_handler=handler, log_level=logging.DEBUG)
#

Just to add context

fast osprey
#

Cool let us know if that log fires when you hit the button

dire timber
#

Nope

[2024-08-17 14:27:12] [DEBUG   ] discord.client: Dispatching event command_completion
es has received {'type': 0, 'content': 'Tic Tac Toe: X goes first', 'mentions': [], 'mention_roles': [], 'attachments': [], 'embeds': [], 'timestamp': '2024-08-17T14:27:12.792000+00:00', 'edited_timestamp': None, 'flags': 0, 'components': [{'type': 1, 'id': 1, 'components': [{'type': 2, 'id': 2, 'custom_id': 'b559d6616bd64a61490407f83f53a8ad', 'style': 2, 'label': '\u200b'}, {'type': 2, 'id': 3, 'custom_id': 'd1453a6ebf3af111d118a34ceaef523b', 'style': 2, 'label': '\u200b'}, {'type': 2, 'id': 4, 'custom_id': 'c92cea923bb119c6d76dace0f765eeea', 'style': 2, 'label': '\u200b'}]}, {'type': 1, 'id': 5, 'components': [{'type': 2, 'id': 6, 'custom_id': '14b3f330cb7cc41ecb75ad9b0724ea91', 'style': 2, 'label': '\u200b'}, {'type': 2, 'id': 7, 'custom_id': '4373babfe047e4e786147820f7f4e92f', 'style': 2, 'label': '\u200b'}, {'type': 2, 'id': 8, 'custom_id': 'a051265dbe3131aa5e0b772c7fc3799c', 'style': 2, 'label': '\u200b'}]}, {'type': 1, 'id': 9, 'components': [{'type': 2, 'id': 10, 'custom_id': '44a903519b0867676f8a7e6301c2608b', 'style': 2, 'label': '\u200b'}, {'type': 2, 'id': 11, 'custom_id': 'f29e58e09d7e1e95a6aa73abeef26c4b', 'style': 2, 'label': '\u200b'}, {'type': 2, 'id': 12, 'custom_id': 'a649d1f4d5d56b1237b71b2c1a149764', 'style': 2, 'label': '\u200b'}]}], 'resolved': {'users': {}, 'members': {}, 'channels': {}, 'roles': {}}, 'id': '1274373976797216800', 'channel_id': '512594875284455424', 'author': {'id': '517689574579896341', 'username': 'Test Bot', 'avatar': None, 'discriminator': '5987', 'public_flags': 524288, 'flags': 524288, 'bot': True, 'banner': None, 'accent_color': None, 'global_name': None, 'avatar_decoration_data': None, 'banner_color': None, 'clan': None}, 'pinned': False, 'mention_everyone': False, 'tts': False}
DEBUG:discord.client:Dispatching event command_completion
#

I don't think this is relevant

#

But that's the last message that got sent

#

And the interaction wasn't detected 😔

fast osprey
#

In the developer panel for your app, there should be a setting like interaction url. Is that filled?

dire timber
#

on discord?

#

Or on the browser?

fast osprey
#

In the discord dev panel yeah

#

Where you got your token from

dire timber
#

Am I supposed to copy and paste that in my code?

fast osprey
#

No you should remove it

#

And hit save

#

Where did that even come from?

dire timber
#

I think I tried something before when I was testing before

#

Like when I created the bot at first

fast osprey
#

Ah. That is sending all of your interactions to that url, rather than through the websocket that your bot is connected on

dire timber
#

Ok no wonder it didn't go through

Logged in as Test Bot#5987 (ID: 517689574579896341)
------
Calling callback function
#

Ok that's the first problem solved

#

But the issue is still present

fast osprey
#

Then you're hitting an error

#

You also have at least one code path that never responds

#

Some more debugging to see how far in you get would be useful

dire timber
slate swan
#

how to make a transcribe command without using openai-whisper?

fast osprey
#

What does a transcribe command do?

glad cradle
#

Hi I have this bot structure

inhousequeue
│   ├── cogs
│   │   └── utils
│   ├── constants
│   ├── core
│   │   ├── actions
│   │   └── utils
│   │       ├── readyup
│   │       └── start
│   ├── database
│   ├── enums
│   ├── helpers
│   └── utils
├── migrations
├── scripts

and for example i'm doing imports in this way from inhousequeue.utils.etc..... import Something now why this is raising an error saying ModuleNotFoundError: No module named 'utils' i tried loading the extensions by passing package="inhousequeue" but it's not working

#

turns out i forgot to refactor some imports

grizzled onyx
fast osprey
#

Gonna need more code than that

#

Do you have the members intent?

slate swan
grizzled onyx
fast osprey
#

We'll need more code then

fast osprey
#

speech to text ain't a discord problem shrug . You need to either run a model locally, or get instruction from your users that they're okay sharing data with whatever third party you choose (and that they aren't training AI on it)

grizzled onyx
# fast osprey We'll need more code then
@tasks.loop(seconds=50)
    async def mod_stats(self):
        await self.bot.wait_until_ready()

        nowdatetime = str(datetime.now().time().strftime("%H:%M"))
        nowdate = (datetime.today()).strftime("%d.%m.%Y")
        nowweekday = datetime.today().weekday()

        if nowdate not in self.staff:
            self.staff.add(nowdate)
            guild = await self.bot.fetch_guild(GUILD_ID)
            staff = guild.get_role(HELPER_ID)
            manager = guild.get_role(MANAGER_ID)

            async with aiosqlite.connect(f"{FOLDER}/data/leafcity.db") as cur:
                members = staff.members + manager.members
                print(staff.members, manager.members)```
#

could this be due to the fact that I'm fetching a guild and getting roles for it?

dire timber
#

@fast osprey many many many thanks
you found the root cause of my issue

#

it was that setting on the discord portal

#

I can't express how happy I am to have finally found what the issue was

fast osprey
#

If you have a connected bot, there's very, very few reasons you'd legimitately need to use fetch

#

Basically only a) you need info on another shard b) you need a user's banner (which isn't sent with the user object by default) or c) you need a message that isn't in the cache

fast osprey
midnight oracle
grizzled onyx
fast osprey
#

Cool cool, yeah in general you should avoid fetching anyways unless you have a specific reason why the cache won't work

glad cradle
midnight oracle
#

okay

slate swan
#

hi, im trying to create a new bot for discord and im having problems with this command. im not sure if its the right one or what. ill send exception

#

`PS C:\Users\Solaris\Desktop\flirtykins> \venv\flirtykins\Activate.ps1
\venv\flirtykins\Activate.ps1 : The term '\venv\flirtykins\Activate.ps1' is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1

  • \venv\flirtykins\Activate.ps1
  •   + CategoryInfo          : ObjectNotFound: (\venv\flirtykins\Activate.ps1:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException`
fast osprey
#

.ps1's are powershell?

slate swan
#

I really couldn't tell you, I am very new to this

#

i assume the command isn't right

#

but im just not sure which i should be using

fast osprey
#

Well, what is leading you to think this is what you should be doing? What is your objective?

slate swan
#

trying to make a venv, ive already created it, trying to activate it now

fast osprey
#

What is telling you that this is what you should be doing?

slate swan
#

¯_(ツ)_/¯

#

let me reiterate

#

I started learning python yesterday

fast osprey
#

You just came up with that line entirely on your own?

slate swan
#

I'm doing what I was told, so I have no idea, a friend is helping me however they are using a mac

#

so they arent familiar with windows cmd or powershell

fast osprey
#

I'd recommend starting with this, no idea why powershell is in the picture

slate swan
#

bcuz its the default terminal im using ig idk

#

ive also already tried the command there and it didnt work, though i probably entered it wrong

fast osprey
#

You could specify that you want to use powershell to run this file, whatever you're running in doesn't seem to know that .ps1's are run using it

slate swan
#

I think you're underestimating how new I am to this, because this is still quite alien to me. If you are unable to simplify it, I'll look elsewhere. I understand you're trying to help, but I feel like I've gotten nowhere. Thanks.

fast osprey
#

Part of helping is specifying what it is you don't understand

#

I can't mind read what you don't know, this isn't hostile lol

#

This also has nothing to do with discord bots so is probably out of the purview of this channel, at face value this is an issue just running powershell

young dagger
#

Any easier way to do this?

    now = datetime.datetime.now()
    # Calculate the next quarter hour
    next_quarter = (now.minute // 15 + 1) * 15
    if next_quarter == 60:
        next_quarter = 0
        hour = now.hour + 1
    else:
        hour = now.hour
    
    next_run_time = now.replace(minute=next_quarter, second=0, microsecond=0)
    if next_quarter == 0:
        next_run_time = next_run_time.replace(hour=hour)

    delay = (next_run_time - now).total_seconds()
    await asyncio.sleep(delay)
fast osprey
#

Could just use a timedelta + discord.utils.sleep_until

#

As far as finding the next interval, could probably evenly divide the minutes by 15 and then add 15

young dagger
snow coral
#

My bot keeps responding with duplicate messages but I only have 1 instance open

vocal laurel
#

send over the code please

#

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

snow coral
#

This is my main file

#

Oh oops

blissful crane
finite salmon
#

It's most probably cuz of that

slate swan
#

How can I make it so that after a bot restart all of the buttons and stuff will still work

slate swan
#

:c

scarlet tiger
#

It's different for each library, if you use discord.py I think it has an example in its repository

scarlet tiger
#

Look for an example on google, I don't use that library ducky_concerned

slate swan
#

Alright

#

tysm

#

views(*, persistent=True)

#

An error occurred: Command raised an exception: TypeError: View.init() got an unexpected keyword argument 'persistent' :(

fast osprey
#

You probably want the add_view

#

"Persistent" isn't a property of the view itself

#

It's just a method of you adding a view to the bot directly without sending it

slate swan
#

Okie

amber thorn
#

Guys do y'all know what bot I can use that can help me with python?

fast osprey
#

What help do you need?

livid hare
#

anyone help me pls

#

but still vs said no module named discord

#

BURN IN HELL VS

#

HELP ME I HAVE GOT NERVOUS FOR NOW

scarlet tiger
livid hare
#

don't need it

#

won't working i install 10000times

slate swan
#

Unfortunately if you don't provide more information, we can't help

#

You can send messages over exaggerating your attempts, sending in full caps, etc. it won't help us knowing what doesn't work

fast osprey
#

You need to describe a) exactly how you're trying to install it and b) exactly how you're trying to run your code

snow coral
snow coral
fast osprey
#

What is the duplicate message? Do you have debugging statements figuring out the code path that's sending them?

snow coral
fast osprey
#

Then you almost certainly are calling process_commands somewhere

#

Is anything else besides commands duplicating?

snow coral
#

don’t think so

snow coral
fast osprey
#

You only really ever need to do that in an on_message override, and even then 90% of the time people should be using listeners instead

blazing beacon
#

oof- sorry for the ping

fast osprey
#

If there are specific cases where you don't want commands to be processed

#

IMO if you have an event override that has a process commands not underneath an if clause, that should just be a listener

blazing beacon
#

yeah, lol

#

it looks neater too imo

#

thanks! o3ob

mint pecan
#

How do i add a command into a cog separately?

.
├── ping.py
├── kick.py
├── cog1.py
└── bot.py

Example i have a structure like this, i want to add ping and kick command from ping.py and kick.py into cog1.py and run the bot, how would i do this?

jaunty cape
mint pecan
slate swan
#

That's not how cogs work

mint pecan
#

😔

fast osprey
#

You should group the things in a file that are deployable together and/or are conceptually linked. You should not dogmatically split things because "that's how I do it" or "the file is too long". Those are anti patterns that you can and should reprogram yourself of

dire timber
#

Hi I'm back again to ask for more help
I'm trying to get my dropdown view working but I keep getting errors

    @commands.command()
    async def build(self, ctx: commands.Context) -> None:
        data = [
            "Test 1",
            "Test 2",
            "Test 3"
            ]
        view = DropdownView(ctx.author, data)

        print(type(view))
        content=""
        embed = self.create_embed()
        await ctx.send("Menu", view=view)
from __future__ import annotations

import logging
import discord
import typing
import traceback
import json

class DropdownView(discord.ui.View):
    message: discord.Message | None = None
    sep : int = 5
    current_page = 1

    def __init__(self, user: discord.User | discord.Member, timeout: float = 60.0, data = []) -> None:
        super().__init__(timeout=timeout)
        self.user = user
        self.data = data
        # self.menu = discord.ui.Select[DropdownView](
        #     custom_id="persistent_menu",
        #     placeholder="Select a build",
        #     min_values=1,
        #     max_values=1,
        #     options=[discord.SelectOption(label=f"{i}") for i in data],
        # )
        # self.menu.callback = self.callback
        # self.add_item(self.menu)

    async def callback(self, interaction: discord.Interaction) -> None:
        await interaction.response.defer()

    async def interaction_check(self, interaction: discord.Interaction) -> bool:

        if interaction.user == self.user:
            content = "Test"
            await self.update_message()

            return True
False
        await interaction.response.send_message(f"The command was initiated by {self.user.mention}", ephemeral=True)
        return False

Is this correct?

#

As for the error I'm getting

[2024-08-19 20:25:34,489] ERROR: Ignoring exception in command build
Traceback (most recent call last):
  File "C:\Users\bkwok\AppData\Roaming\Python\Python312\site-packages\discord\ext\commands\core.py", line 235, in wrapped
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\bkwok\OneDrive\Documents\Development Files\Discord Bots\Python\Discord Bot Test\cogs\builds.py", line 87, in build
    await ctx.send("Menu", view=view)
  File "C:\Users\bkwok\AppData\Roaming\Python\Python312\site-packages\discord\ext\commands\context.py", line 1039, in send
    return await super().send(
           ^^^^^^^^^^^^^^^^^^^
  File "C:\Users\bkwok\AppData\Roaming\Python\Python312\site-packages\discord\abc.py", line 1622, in send
    state.store_view(view, ret.id)
  File "C:\Users\bkwok\AppData\Roaming\Python\Python312\site-packages\discord\state.py", line 410, in store_view
    self._view_store.add_view(view, message_id)
  File "C:\Users\bkwok\AppData\Roaming\Python\Python312\site-packages\discord\ui\view.py", line 567, in add_view
    view._start_listening_from_store(self)
  File "C:\Users\bkwok\AppData\Roaming\Python\Python312\site-packages\discord\ui\view.py", line 440, in _start_listening_from_store
    self.__timeout_expiry = time.monotonic() + self.timeout
                            ~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~
#
TypeError: unsupported operand type(s) for +: 'float' and 'list'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\bkwok\AppData\Roaming\Python\Python312\site-packages\discord\ext\commands\bot.py", line 1366, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\bkwok\AppData\Roaming\Python\Python312\site-packages\discord\ext\commands\core.py", line 1029, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\bkwok\AppData\Roaming\Python\Python312\site-packages\discord\ext\commands\core.py", line 244, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for +: 'float' and 'list'
#

I'm basically trying to pass an array of strings into the view to be used as the option strings

fast osprey
#

What are you passing in as the timeout of your view?

dire timber
#

it's defaulting to 60s

fast osprey
#

It's not

#

you're passing something into that parameter

#

(You probably want to use keyword arguments here)

dire timber
#
def __init__(self, user: discord.User | discord.Member, timeout: float = 60.0, data = []) 

Is that 60.0 not a default value?

fast osprey
#

It is, but then you're passing something into it

#

data

dire timber
#

oh

#

OHH I SEE NOW

#

I didn't realise I needed to use colons

neon ocean
#

data: list

fast osprey
#
def func(a:Whatever = None, b:WhateverElse = None):
  ...

x: WhateverElse = ...
func(x)

python doesn't know what you want, and the typehinting is irrelevant. It will still pass x into a because you're calling it with positional arguments

neon ocean
#

i guess

fast osprey
#

nothing to do with typehinting

neon ocean
#

Oh

dire timber
#

I see. How would I define the 3rd argument in this case?

neon ocean
#

**kwargs?

dire timber
#

ohh alright I didn't know what that meant

#

I've never used that before

fast osprey
neon ocean
#

Oh

#

You mean this...

fast osprey
dire timber
#

So it would have to be like this?

def __init__(self, user: discord.User | discord.Member, timeout: float = 60.0, **kwargs)

View(data=data)
neon ocean
#

Yes

#

You forgot data

#

More like

fast osprey
#

You don't need **kwargs

#

you can list out the arguments normally in the function declaration, then just use keyword arguments when you're calling it

neon ocean
#
def __init__(self, user: discord.User | discord.Member, timeout: float = 60.0, data: list)

View(user=<PASTE_VALUE_HERE>, timeout=<PASTE_VALUE_HERE>, data=<PASTE_VALUE_HERE>)
#

More like this

dire timber
#

Ohh ok

finite salmon
#

I think

#

!eval
def a(b=1, c): ...

unkempt canyonBOT
# finite salmon !eval def a(b=1, c): ...

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

001 |   File "/home/main.py", line 1
002 |     def a(b=1, c): ...
003 |                ^
004 | SyntaxError: parameter without a default follows parameter with a default
finite salmon
#

Yea

dire timber
#

So put the data argument first?

finite salmon
#

Yes

dire timber
#

Ok I'll give this a shot

#

Thank you everyone

#

Ok that worked

#

Thank you very much

mint pecan
#

i've just added a hybrid command into my cog but it doesnt appear, is this because i didnt sync?

storm leaf
#

Im curious about one thing: is it possible to make a discord bot recognise its previous posts after a reboot? So if I make an embed and that embed has buttons attached to it, they will not work if we restart the bot. How do you make it recognise and remember these buttons?

#

Might have found something actually, pause

fast osprey
finite salmon
signal vortex
#

Hello

fast musk
#

Hi

jaunty flume
#

is there a server for asking voicelink questions?

slate swan
#
async def word(ctx):
    file1_path = 'fflags.txt'
    file2_path = 'ms.txt'
    

    def count_words_from_file(file_path):
        try:
            with open(file_path, 'r') as file:
                # Read file and split into words
                words = file.read().lower().split()
                total_words = len(words)
                return total_words
        except Exception as e:
            return None, f"An error occurred: {e}"
    
    total_words_file1 = count_words_from_file(file1_path)
    total_words_file2 = count_words_from_file(file2_path)
    
    embed = discord.Embed(
        title="Word Statistics from Files",
        description="Here are the word statistics from the text files:",
        color=discord.Color.blue()
    )
    
    embed.add_field(name="File 1 Statistics", value=f"Total words: {total_words_file1}", inline=False)
    embed.add_field(name="File 2 Statistics", value=f"Total words: {total_words_file2}", inline=False)
    
    await ctx.send(embed=embed)```

**this is my code it works 50% when i run the command it tells me how many words are in my fflags.txt file correctly, but not the ms.txt file correctly.  Does anyone know how to fix this?**
shrewd apex
#

how is it incorrect?

viscid hornet
shrewd apex
#

hmm?

glad cradle
#

(we're friends pls don't ban me)

shrewd apex
#

i totally don't know this person

#

complete stranger ducky_concerned

glad cradle
#

see you all in the valhalla ig

slate swan
fast osprey
#

Maybe try printing out the contents to see if it is what you think it is

vestal yew
#

hi

#

I created an embed message and put a button named test under it, but the button stops working after a while, how can I solve this because it times out?

fast osprey
#

You can pass a timeout into the view constructor

#

!d discord.ui.View

unkempt canyonBOT
#

class discord.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2\.0\.
scarlet tiger
vestal yew
#

but

#

this not working

scarlet tiger
#

If you just say it doesn't work, no one can help you. Share the error or code so someone can help you.

vestal yew
#

I will write sample code

#
    def __init__(self, user_id):
        super().__init__(timeout=None)
        self.user_id = user_id

    @nextcord.ui.button(label="test", style=ButtonStyle.green, custom_id="test")
    async def test(self, button: Button, interaction: Interaction):
        await interaction.response.send_message("test", ephemeral=True, delete_after=10)

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

    @nextcord.slash_command(description="Oyunu Başlatır")
    async def başlat(self, interaction: nextcord.Interaction):
        await interaction.response.send_message("test123",view=OyunView(interaction.user.id))```
#

Should it be like this?

#

@scarlet tiger

#

sorry for the tag

#

So it worked when I did it this way, but as I said, the button stops responding after a while.

scarlet tiger
#

Try removing the custom_id and use defer()

vestal yew
#

how

#

So how do I use it?

scarlet tiger
#

It is not recommended to put a custom_id because it can cause conflicts, they are only used when creating persistent views (at least in the library I use it is that way)

stark ingot
#

Why would defer help in this case?

vestal yew
vestal yew
scarlet tiger
#

😅

vestal yew
#

Actually, my code is a bit long.

#

wait

vestal yew
#

timeout = none but as I said, it does not respond after a while

#

I asked chatgpt but he also gave wrong solutions

#

By the way, I'm a newbie, I don't feel confident about the code I wrote, I'm just trying to improve myself. But I need to solve this problem

scarlet tiger
#

You can try putting a print() in each function of each button and see if it returns a response in the terminal

vestal yew
#

umm okey

#

@scarlet tiger How to use defer()

scarlet tiger
#

at the start of each function of each button put await interaction.response.defer()

But in this case send_message() will not work, you must use followup.

vestal yew
#

btw

#

The problem was solved in a way I did not understand

#

Now, even if I close and reopen the bot, I can run it again by pressing the previous message buttons.

#

._.

#

It's really weird

scarlet tiger
# vestal yew The problem was solved in a way I did not understand

In simple terms sometimes your connection speed or the discord servers have a high latency or you have a function that takes a long time to complete. An interaction must receive a response within 3 seconds, otherwise it doesn't work.

With defer() you tell discord to wait (I think the time increases to 15 minutes).

vestal yew
#

Even the button on the message I sent yesterday worked.

fast osprey
#

Setting the timeout to none on its own doesn't make python magically regenerate view objects that don't exist

vestal yew
#

But it worked, am I going to lie?

#

If you want, I can open a broadcast and show it.

fast osprey
#

That means something else is going on

vestal yew
fast osprey
#

The library on its own won't make view objects for you

#

something in your code is making those views

vestal yew
#

umm

scarlet tiger
#

you are using custom_id may be the reason for this

#

🤔

vestal yew
#
    def __init__(self, user_id):
        super().__init__(timeout=None)
        self.user_id = user_id

    @nextcord.ui.button(label="/oyna", style=ButtonStyle.green, custom_id="oyna")
    async def oyna(self, button: Button, interaction: Interaction):
        if interaction.guild is None:
            await interaction.response.send_message("Seni Akıllı İnsan Bu Komut Sadece Sunucuda Çalışır Hadi Sunucuda Dene.", ephemeral=True, delete_after=10)
            return
        await interaction.response.send_message(embed=embed, file=file, view=OyunView(interaction.user.id))

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

@nextcord.slash_command(description="Oyunu Panelini Açar")
    async def oyna(self, interaction: nextcord.Interaction):
        if interaction.guild is None:
            await interaction.response.send_message("Seni Akıllı İnsan Bu Komut Sadece Sunucuda Çalışır Hadi Sunucuda Dene.", ephemeral=True, delete_after=10)
            return
        await interaction.response.send_message(embed=embed, file=file, view=OyunView(interaction.user.id))```
fast osprey
#

Couldn't tell you if nextcord doesn't key the view by message id, in which case yeah you'd get overlapping views sharing state if they had the same custom ids shrug

vestal yew
fast osprey
#

I would assume nextcord would also give you a random custom id in that case

vestal yew
#

hmm

fast osprey
#

There's not a sane world where sending a view on Message A suddenly makes something start listening on Message B that wasn't before, so either you still have something going on or this library is doing something a bit silly

fast osprey
#

Sure hope your views never rely on having consistent internal state shrug

outer violet
#

is hosting a discord bot on gcp on the forever free tier actually free? i get mixed reviews on the internet about how it renews every month or you have to pay

vestal yew
#

like orange pi

outer violet
#

money is a problem for me

#

so im asking about gcp

vestal yew
#

umm

vestal yew
#

How can I add cooldown to slah commands?

#

If you're going to reply to me, please tag me. I need to sleep. I'll check tomorrow.

fast osprey
#

There are far fewer cases where you need to

vestal yew
#

i dont understand

fast osprey
#

Why do you want a cooldown?

vestal yew
#

because

#

I don't want people using the same command 50 times per second.

fast osprey
#

They can't

vestal yew
#

There is a command, I made it to be used only every 10 minutes, but I need to add a cooldown.

fast osprey
#

App commands already impose a limit natively in discord. It's fine if your actual application logic needs this cooldown functionally but if it's just fear of "spam" or rate limits there are better alternatives

pliant gulch
outer violet
#

interesting

#

thanks for the answer though

glad cradle
cedar nova
#

How would you use application emojis via the emoji tab? tried fetching the emoji using the provided id but it didn't work? Maybe there's an different way?

I'm just doing

@bot.command()
async def send_emoji(ctx, id:int):
    emoji = bot.get_emoji(id)    
    if emoji:
        await ctx.send(f"The Emoji: {emoji}")
    else:
        await ctx.send(f"{id} isn't an emoji")

and its returning the else statement? Honestly this isn't a big problem, I could just upload the emojis to a private server but yk why not try the tab

I've tried going through bot.application but it only provides the general information page

blissful crane
#

if you want to use of one your app's emojis you just need to follow the regular emoji format <:name:id>

hard kite
#

i was making a discord bot and i got into situation where i want the bot to send a message whenits added but idont know how to get a first available channel on that server

uhm how?

livid hare
#

guys how long it takes to learn discord bot creating using discord.py

fast osprey
fast osprey
#

You can get a hello world bot up in like 20 minutes with no prior experience just following the quickstarts

foggy laurel
random tapir
stark ingot
#

-# the above was resolved in the thread

livid hare
#

i don't want chatbot only

#

also i should start mysql

fast osprey
#

mysql is a pretty objectively bad db tbh

exotic hazel
#

What would you recommend instead?

wanton current
#

postgres

#

or sqlite depending on your use case

stark ingot
#

^ Postgres if you are planning on storing more data
Sqlite if you are not storing as much and need to set it up quick and easily

Also make sure you use an async wrapper. (asyncpg for Postgres.)

exotic hazel
#

Thank you chocojNoted

wanton current
#

99% sure you'll never run into a problem where you're storing "too much" data for SQLite

shrewd apex
#

but there are a few other reasons also to use postgres tho like extensions, diverse column or data types, triggers/functions, pg notify for a bit of limited realtime comm all of which might be useful provided you leverage it properly

ivory remnant
#

i was making a slash command for my bot and wanted it to have cooldown, so i used py @app_commands.checks.cooldown(1, 1200, key=lambda i: (i.guild.id, i.user.id))
but i wanted to make it so if you have such and such role, the cooldown doesnt apply to you

#

is this in anyway possible?

fast osprey
#

dynamic_cooldown probably

keen niche
#

In pycord slash commands, what @ thing do I use to check if user has certain role?

scarlet tiger
keen niche
stark ingot
slow hollow
#
@commands.has_permissions(manage_messages = True)
async def clear(ctx, amount: int):
  await ctx.channel.purge(limit=amount)
async def message_on(message):
      await message.channel.send("Les messages ont bien été supprimer", delete_after=5)```
#

the end message is not displayed

fast osprey
#

You're making a function called message_on. What calls this?

slow hollow
#

Idk

#

I want the end message displayed

fast osprey
#

Well I mean just making a function doesn't do anything

slow hollow
#

How should we do it?

fast osprey
#

Do what?

slow hollow
#

Because there is already the function of purge

slow hollow
fast osprey
#

You can do whatever you want in the body of the command

#

you don't need to make another function

slow hollow
#

Now the bot purge and after purge : crash

fast osprey
#

In the command function?

#
@bot.tree.command()
async def my_command(...):
  you_can_do()
  multiple_things()
  in_a_row()
  you_dont_need_another_function()
slow hollow
#

Sorry I starting in the code and in the English language

slow hollow
fast osprey
#

It's not, because that's a variable you made up

#

you have the things in your command to work with though

slow hollow
fast osprey
#

If you're making an app command, you don't get a context. Naming that parameter ctx is very misleading. You get an Interaction. That Interaction has all of the information of things you'd want to do here

#
@bot.tree.command()
async def my_command(interaction):
  #you can do things with the interaction, like access interaction.channel
slow hollow
#

But

async def clear(message, ctx, amount : int)

#

Is an error

fast osprey
#

You don't get a context

#

don't make a parameter named ctx

#

you get an interaction, and that is always the first parameter

slow hollow
#

Ok but me i want two interaction

#

( the purge and the message )

slow hollow
fast osprey
#

You don't get two interactions

#

They run the command. That's an interaction. That is the user interacting with your bot. They interacted with your bot once.

slow hollow
fast osprey
#

And you can do two things. You can do however many things you want

slow hollow
#

One things define, other not

fast osprey
#

You don't get a message. Again, you get an Interaction. And that has what you need

slow hollow
#

😭

#

To do…after doing…

slow hollow
fast osprey
#

Just...have multiple lines?

slow hollow
fast osprey
#

yeah it's just a normal python function

#

it can have however many lines you want

slow hollow
#

But it’s an error

fast osprey
#

Which is?

slow hollow
#

Help me I want sleep 😭

fast osprey
#

The error is very clear

#

you can't name two commands the same thing

slow hollow
#

But I want

#

One command

fast osprey
#

Then only make one

slow hollow
#

No error

#

But bot crash

#

After the purge

fast osprey
#

you're making another function

#

why are you making another function

#

You can have one function that does multiple lines, one after another

#

that's just how python works

slow hollow
#

Because if i make not : error = function note define

fast osprey
#

because you're referencing something that doesn't exist

#

the answer isn't to make another function. It's to use the variable you have

#

which should be interaction in the first place

#
@bot.tree.command()
async def my_command(interaction):
  interaction.x()
  interaction.y()
  interaction.z()
slow hollow
fast osprey
#

You don't get a context

#

do not have a variable called ctx

#

do not treat anything like a context. You don't get one

slow hollow
#

Now ctx it’s not define

fast osprey
#

That's not what your error says

slow hollow
#

I know

#

But if i don’t supp ctx in l65

#

The error is : ctx is not define

fast osprey
#

You don't have a context. You don't need one

slow hollow
#

What is a context

#

:/

fast osprey
#

It's best you don't copy paste code you don't understand

#

And start from scratch. You're making an app command. Forget ctx as a concept exists, because it's not relevant and should not show up in your code

#

You have your interaction and that's what you use. The error above has nothing to do with a ctx

slow hollow
fast osprey
#

Context, often shortened to ctx, is an object given to prefix text commands. You are not making that, so it does not apply

slow hollow
#

For tonight I would just like to finalize this order can you help me?

fast osprey
#

I don't write code for people. If that's what you'd like, you're welcome to wait for someone who might

fast osprey
# slow hollow

This code is almost correct. The error happens for a specific reason. It has nothing to do with a contest

slow hollow
#

Not right but just Say me or put it on, I've almost done everything

slow hollow
#

But it’s 4h am and i don’t want sleep if the commande is not finished

#

I’m French because it’s too difficult for communicate with you and with python language

#

The difficulty is x2

fast osprey
# slow hollow

So what is the error with that code from that screenshot?

slow hollow
fast osprey
#

That isn't what the error says. I'm looking right at it

slow hollow
#

Type error

#

Unsuport type annotation

fast osprey
#

That's also not what is in that screenshot

#

I'm reading it dude, I can see it with my eyes

#

"Unknown intera(cuts off)"

slow hollow
#

Interaction

fast osprey
#

What is that full error

slow hollow
fast osprey
#

Including the traceback

#

Copy and paste it

slow hollow
#
Traceback (most recent call last):
  File "C:\Users\david\PycharmProjects\pythonProject\bot discord\venv\Lib\site-packages\discord\app_commands\commands.py", line 828, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\david\PycharmProjects\pythonProject\bot discord\main bot discord.py", line 66, in clear
    await interaction.response.send_message("Les messages ont bien été supprimer", delete_after=5)
  File "C:\Users\david\PycharmProjects\pythonProject\bot discord\venv\Lib\site-packages\discord\interactions.py", line 801, in send_message
    await adapter.create_interaction_response(
  File "C:\Users\david\PycharmProjects\pythonProject\bot discord\venv\Lib\site-packages\discord\webhook\async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\david\PycharmProjects\pythonProject\bot discord\venv\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\david\PycharmProjects\pythonProject\bot discord\venv\Lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\david\PycharmProjects\pythonProject\bot discord\venv\Lib\site-packages\discord\app_commands\commands.py", line 846, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'clear' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
#

its after i realize the command

fast osprey
#

This happens because interaction.response.send_message has to be done within 3 seconds. Your purge is probably taking longer than that

slow hollow
#

💀

#

My purge taking 1-2s ?

fast osprey
#

I recommend doing await interaction.response.defer(ephemeral=True) before you purge, then await interaction.followup.send("whatever you want") after

slow hollow
#

Yes it’s good

#

Can you explique me ?

fast osprey
#

You have to respond within 3 seconds. response.defer is one way of responding which means "the bot is doing something that will take time", it gives the "bot is thinking" message

#

followup.send is how you send a message after a response. In this case, signaling the bot is no longer "thinking"

slow hollow
#

Oh okay it’s just time problems ?

fast osprey
#

Yes. Your interaction.response must be fast

slow hollow
#

The "whatever you want", delete _after=5

fast osprey
#

You don't need to delete it

#

It's a temporary message anyways

slow hollow
#

Really ? Oh okay.

Thank you for all

#

Good night

fast osprey
#

Night

mint pecan
#

where should i sync commands in my bot?

scarlet tiger
mint pecan
#

i am getting
TypeError: 'Bot' object does not support the context manager protocol
trying to run

with Bot(command_prefix=prefix, intents=intents) as bot:
        bot.run(dotenv.dotenv_values('.env')['BOT_TOKEN'])

how do i fix this?

mild token
#

Select can have take url and instead of emoji and put like thumbnails?

mild token
#

And also remove as bot

#

Is there a way to hide private threads from thread list ,i want only certain individuals should be able to see the thread

#

Not all

#

If they are not added

slow hollow
#
from discord import Intents
from discord import app_commands
from discord.ext import commands

class SlashCog(commands.Cog):
    def _init_(self, bot : commands.Bot) -> None :
        self.bot = bot

intents = discord.Intents().all()
bot = commands.Bot(command_prefix="+", intents=intents)

intents.message_content = True
intents.members = True


class MyBot(commands.Bot):
    def _init_(self) -> None:
        super()._init_(command_prefix="+", intents=discord.Itents.all())


intents = Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)
bot = commands.Bot(command_prefix= "+", intents=discord.Intents.all())

@bot.event
async def on_ready():
    print("Le bot est prêt.")

    try:
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} commands")

    except Exception as e:
        print(e)


@bot.event
async def on_message(message):
    if message.content.lower() == "ping":
       await message.channel.send("pong", delete_after=5)

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

def is_owner():
    def predicate(interaction: discord.Interaction):
        if interaction.user.id == 1125518202835841044:
            return True
        return app_commands.check(predicate)

@bot.command()
@commands.has_permissions(manage_messages=True)
async def say(ctx, *, message):
    await ctx.send(message)
    await ctx.message.delete()

    @app_commands.command(name="cog_command")
    async def command(self, interaction : discord.Interaction):
        return interaction.response.send_message("Message dans un Cog")

@bot.tree.command(name="test", description="Cette commande est un test !")
async def test_slash(interaction: discord.Interaction):
    await interaction.response.send_message('test')

@bot.tree.command(name="owner", description="Cette commande est réservé a mon développeur")
async def owner_slash(interaction: discord.Interaction):
    await interaction.response.send_message(f"Salut, {interaction.user.mention} !", ephemeral=True)


@bot.tree.command(name="clear", description="Supprimer des messages")
@commands.has_permissions(manage_messages = True)
async def clear(interaction: discord.Interaction, amount: int):
    await interaction.response.defer(ephemeral=True)
    await interaction.channel.purge(limit=amount)
    await interaction.followup.send("Les messages ont bien été supprimer")```
#

Since I put my smash orders, my prefix commands no longer work

#

Why ?

fast osprey
#

Don't use an on_message event, use a listener. And don't sync or really do anything in on_ready

#

Also you should not have a client and a bot

slow hollow
#

My events function but not my prefix command

slow hollow
#

Ok i know

#

I delete client

fast osprey
#

Don't use an on_message event

#

This is overriding the bot processing text commands, you should use a listener instead

#

!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...
solar bone
#
    ^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Intents' object has no attribute 'message_content'

[Done] exited with code=1 in 0.672 seconds```
#

bro

wanton current
#

what version are you on

solar bone
solar bone
fast osprey
#

pip freeze

vestal yew
#
    async def avatar(self, interaction: nextcord.Interaction, kişi: nextcord.User = nextcord.SlashOption(description="Avatarını görmek istediğiniz kişiyi etiketleyin", required=False), gizli: bool = nextcord.SlashOption(description="Avatar komutunu gizler", required=False)):
        if interaction.guild is None:
            await interaction.response.send_message("Bu Komut Sadece Sunucuda Kullanılabilir.", ephemeral=True,delete_after=10)
            return
        
        if kişi is None:
            kişi = interaction.user
        avatar_url = kişi.avatar.url
        avatar = f"[Avatar Link]({avatar_url})"
        embed = nextcord.Embed(
            title="",
            description="**["+f"{avatar}"+"]**",
            color=nextcord.Color.green()
        )
        embed.set_author(icon_url=avatar_url, name=f"{kişi.name}")
        embed.set_image(url=avatar_url)
        embed.timestamp = current_time
        embed.set_footer(icon_url=self.bot.user.avatar.url, text=self.bot.user.name)

        if gizli is None or False:
            await interaction.response.send_message(embed=embed)
        else:
            await interaction.response.send_message(embed=embed, ephemeral=True)```
#

kişi is none but bot not response

vocal plover
#

does it respond if you do pick a user in the slash command when you use it?

vestal yew
#

but user only use /avatar and bot not response

vocal plover
#

Are you getting any errors in the console? Interaction.user could be None, in which case I'd expect it to raise an exception at avatar_url = kişi.avatar.url looking something like "NoneType has no attribute 'avatar'"

#

I don't see why Discord wouldn't be providing a user but according to the api schema it's possible, and I'm not sure why else you'd get no response at all

vestal yew
#

The problem is, I don't get any errors in this job.

vocal plover
#

You're debugging this without access to the terminal/console output? That seems like a task from hell

#

I guess you could try adding another check to guard in case there is an error, something to the effect of

        if kişi is None:
            if not interaction.user:
                await interaction.response.send_message("An error occurred, no user was found")

            kişi = interaction.user

        avatar_url = kişi.avatar.url
vestal yew
#

If there was an error, it would already give the error to the terminal like crazy, but it doesn't give an error.

vocal plover
#

I'm guessing that translates to something like "Command/interaction timed out"?

vestal yew
#

yes

#

the app did not respond

vocal plover
#

hmmm, ok there's no path in your code I can see that should cause that to happen, no matter what you should be getting either a response or an exception raised - are you 100% certain that the bot is running on the most recent code, it couldn't be running an older version where it might not respond? ik it sounds obvious but it happens to everyone at some point and it's easy to overlook

vestal yew
#

Look, the nonsense is that it only gives an error when I type /avatar, but it works when I set /avatar gizli=false or true.

#

And when I set gizli=false or true, I still don't select user.

#

but when I just type /avatar it doesn't give an answer

vocal plover
#

Ok so - as long as you set gizli to anything other than leaving it empty, it works, regardless of whether you set kişi?

vestal yew
#

Normally when I type /avatar it should work

#

kişi or gizli also required = false

#
    async def avatar(self, interaction: nextcord.Interaction, kişi: nextcord.User = nextcord.SlashOption(description="Avatarını görmek istediğiniz kişiyi etiketleyin", required=False), gizli: bool = nextcord.SlashOption(description="Avatar komutunu gizler", required=False)):
        if interaction.guild is None:
            await interaction.response.send_message("Bu Komut Sadece Sunucuda Kullanılabilir.", ephemeral=True,delete_after=10)
            return
        
        if kişi is None:
            if not interaction.user:
                await interaction.response.send_message("An error occurred, no user was found")

            kişi = interaction.user
        
        if kişi.avatar.url is None:
            await interaction.response.send_message("Kullanıcının avatarı yok")
            return
            
        avatar_url = kişi.avatar.url
        avatar = f"[Avatar Link]({avatar_url})"
        embed = nextcord.Embed(
            title="",
            description="**["+f"{avatar}"+"]**",
            color=nextcord.Color.green()
        )
        embed.set_author(icon_url=avatar_url, name=f"{kişi.name}")
        embed.set_image(url=avatar_url)
        embed.timestamp = current_time
        embed.set_footer(icon_url=self.bot.user.avatar.url, text=self.bot.user.name)

        if gizli is None or False:
            await interaction.response.send_message(embed=embed)
        else:
            await interaction.response.send_message(embed=embed, ephemeral=True)```