#discord-bots

1 messages · Page 106 of 1

glad cradle
#

the interaction has expired consider to defer it

slate swan
#

pretty sure when u clean the chat ur deleting the interaction so there is no interaction to respond to

#

Correct, you can send a message in the channel though - without responding to an interaction

lost yoke
#

Is there a way to make this not happen?

#

@slate swan @slate swan

hushed galleon
#

do what snipy said and defer the interaction before you start purging messages

#

after deferring the interaction you can use the .followup webhook that lasts for 15 minutes, a way longer window than 3 seconds

slate swan
rancid raptor
#

I know exactly on what line the command freezes but I can't figure out why.

    @app_commands.command()
    @app_commands.guild_only()
    # pylint: disable=too-many-arguments
    async def reminder(self, inter: discord.Interaction, note: str,
                       seconds: int):
        """
            (Instable) You can set a reminder that will send you a message in a given time.
        """
        await inter.response.defer(ephemeral=True, thinking=True)
        timestamp = numpy.datetime64(datetime.now())

        added_time = numpy.timedelta64(seconds, "s")
        if added_time <= 0:
            await inter.response.send_message("There is no time given for the reminder.", ephemeral=True) # Here is an alternative freeze
            return

        trigger_time = timestamp + added_time

        rem = sqldata.Reminder(note, inter.user.id, inter.guild_id,
                               inter.channel_id, True, timestamp, trigger_time)

        await inter.response.send_message(f"Reminder scheduled for ", ephemeral=True) # I is freezing here.
#

Funny thing is that the exact same function is working on menu interactions...

lost yoke
# slate swan cna you show the code of the "cleaning chat"

@tree.command(guild = discord.Object(id=id_do_servidor), name = "clear", description="Limpa uma quantidade de mensagens") async def clear(inter:discord.Interaction,amount:int=100): if inter.user.guild_permissions.ban_members: await inter.channel.purge(limit=amount) msg = discord.Embed( description = f'Olá **{inter.user.name}**, as mensagens foram apagadas com sucesso ^-^', colour = 3844214 ) await inter.channel.send(embed=msg, ephemeral=False) else: falta = 'Você não tem permissão para usar o comando!' embed = discord.Embed(title=f"{falta}") await inter.channel.send(embed=embed, ephemeral=True)

hushed galleon
slate swan
hushed galleon
#

@rancid raptor interactions can only be responded to once, so after your defer() you need to use the .followup webhook instead

lost yoke
#

exemple?

hushed galleon
#
await interaction.response.defer()
# do some work in between...
await interaction.followup.send('my actual message')```
cloud dawn
hushed galleon
#

its not a dpy specific thing

rancid raptor
#

Thank you very much.

cloud dawn
rancid raptor
#

now i will continue writing on my reminder system

cloud dawn
#

That's a tough one.

slate swan
lost yoke
#

wait

#

Logs:

#

Traceback (most recent call last): File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\discord\app_commands\tree.py", line 1242, in _call await command._invoke_with_namespace(interaction, namespace) File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\discord\app_commands\commands.py", line 887, in _invoke_with_namespace return await self._do_call(interaction, transformed_values) File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\discord\app_commands\commands.py", line 876, in _do_call raise CommandInvokeError(self, e) from e discord.app_commands.errors.CommandInvokeError: Command 'clear' raised an exception: TypeError: InteractionResponse.defer() got an unexpected keyword argument 'embed'

#

code:

#

@tree.command(guild = discord.Object(id=id_do_servidor), name = "clear", description="Limpa uma quantidade de mensagens") async def clear(inter:discord.Interaction,amount:int=100): if inter.user.guild_permissions.ban_members: await inter.channel.purge(limit=amount) msg = discord.Embed( description = f'Olá **{inter.user.name}**, as mensagens foram apagadas com sucesso ^-^', colour = 3844214 ) await inter.response.defer(embed=msg, ephemeral=False) else: falta = 'Você não tem permissão para usar o comando!' embed = discord.Embed(title=f"{falta}") await inter.response.defer(embed=embed, ephemeral=True)

slate swan
slate swan
cloud dawn
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...
lost yoke
#

I didn't understand 😦

hushed galleon
lost yoke
#
async def clear(inter:discord.Interaction,amount:int=100):
    if inter.user.guild_permissions.ban_members: 
      await inter.channel.purge(limit=amount)
      msg = discord.Embed(
        description = f'Olá **{inter.user.name}**, as mensagens foram apagadas com sucesso ^-^',
        colour = 3844214
        )
      await inter.response.defer(embed=msg, ephemeral=False)
    else:
      falta = 'Você não tem permissão para usar o comando!'
      embed = discord.Embed(title=f"{falta}")
      await inter.response.defer(embed=embed, ephemeral=True)```
#

I don't understand what's wrong, it erases but doesn't send the embed

slate swan
#

you send the actual content in the followup

#

the defer goes at the beginning of the interaction

#

before any code

slate swan
lost yoke
#

sorry, iam from brazil, can you write for me to test?

#

I'll try

hushed galleon
lost yoke
#

the code:

#
async def clear(inter:discord.Interaction,amount:int=100):
    if inter.user.guild_permissions.ban_members: 
      await inter.channel.purge(limit=amount)
      msg = discord.Embed(
        description = f'Olá **{inter.user.name}**, as mensagens foram apagadas com sucesso ^-^',
        colour = 3844214
        )
      await inter.response.defer(embed=msg, ephemeral=False)
    else:
      falta = 'Você não tem permissão para usar o comando!'
      embed = discord.Embed(title=f"{falta}")
      await inter.edit_original_message(embed=embed, ephemeral=True)```
#

its correct?

slate swan
# lost yoke ```@tree.command(guild = discord.Object(id=id_do_servidor), name = "clear", desc...
@tree.command(guild = discord.Object(id=id_do_servidor), name = "clear", description="Limpa uma quantidade de mensagens")
async def clear(inter:discord.Interaction,amount:int=100):
    await inter.response.defer(ephemeral=True)
    if inter.user.guild_permissions.ban_members: 
      await inter.channel.purge(limit=amount)
      msg = discord.Embed(
        description = f'Olá **{inter.user.name}**, as mensagens foram apagadas com sucesso ^-^',
        colour = 3844214
        )
      
    else:
      falta = 'Você não tem permissão para usar o comando!'
      embed = discord.Embed(title=f"{falta}")
      await inter.followup.send(embed=embed)
lost yoke
#

await inter.response.defer(with_message=True)

mighty pilot
#

Defer just makes it so the bot says it's thinking right?

slate swan
mighty pilot
#

I think... that's all I've done with it lol

lost yoke
#

he erases but he never stops showing: "Geraldo is thinking..."

#

@slate swan

hushed galleon
#

huh, sure enough it looks the same as sending a message after deferring

#

thats weird

#
@app_commands.command(name='test')
async def app_test(self, interaction: discord.Interaction):
    await interaction.response.defer(thinking=True)
    await asyncio.sleep(1)
    await interaction.edit_original_response(content='test')```
slate swan
hushed galleon
#

yes

slate swan
#

they should fix their docs lmao

#

and let ppl know thats a viable solution alongside .follow.send

hushed galleon
#

what did it say that misled you

slate swan
#

the fact that is only says .followup

It is your responsibility to eventually send a followup message via Interaction.followup to make this thinking state go away.
lost yoke
#
async def clear(inter:discord.Interaction,amount=100):
    if inter.user.guild_permissions.ban_members: 
      await inter.channel.purge(limit=amount)
      msg = discord.Embed(
        description = f'Ola **{inter.user.name}**, as mensagens foram apagadas com sucesso ^-^',
        colour = 3844214
        )
      await inter.response.send_message(embed=msg, ephemeral=True)
    else:
      falta = 'você não tem permissão para usar o comando! '
      embed = discord.Embed(title=f"{falta}")
      await inter.response.send_message(embed=embed, ephemeral=True)```
#

Traceback (most recent call last): File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\comandos.py", line 88, in <module> async def clear(inter:discord.Interaction,amount=100): File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\discord\app_commands\tree.py", line 889, in decorator command = Command( File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\discord\app_commands\commands.py", line 685, in __init__ self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__) File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\discord\app_commands\commands.py", line 390, in _extract_parameters_from_callback raise TypeError(f'parameter {parameter.name!r} is missing a type annotation in callback {func.__qualname__!r}') TypeError: parameter 'amount' is missing a type annotation in callback 'clear

hushed galleon
hushed galleon
#

hm if anything followup.send() after defer(thinking=True) would be the odd one

#

also found out dpy automatically sets thinking=True for app commands but doesnt mention it in documentation

slate swan
hushed galleon
lost yoke
#

I just saw this but it doesn't send the embed after cleaning

unkempt canyonBOT
#

discord/interactions.py lines 647 to 648

elif parent.type is InteractionType.application_command:
    defer_type = InteractionResponseType.deferred_channel_message.value```
`disnake/interactions/base.py` lines 744 to 745
```py
if parent.type is InteractionType.application_command:
    defer_type = InteractionResponseType.deferred_channel_message```
`nextcord/interactions.py` lines 690 to 691
```py
if parent.type is InteractionType.application_command or with_message:
    defer_type = InteractionResponseType.deferred_channel_message.value```
slate swan
#
with_message (bool) –

Whether the response will be a separate message with thinking state (bot is thinking…). This only applies to interactions of type InteractionType.component (default False) and InteractionType.modal_submit (default True).

True corresponds to a deferred_channel_message response type, while False corresponds to deferred_message_update.
hushed galleon
#

oh yeah at least they say something about it

#

pycord

This parameter does not apply to interactions of type InteractionType.application_command.
nextcord
This is always True for interactions of type InteractionType.application_command.

#

i guess its more of a nitpick since discord.py mentions it, but doesnt really imply that it forces thinking=True rather than erroring or something

Application commands (AKA Slash commands) cannot use InteractionResponseType.deferred_message_update.

mental hollow
#

How can I add indexes to my snipe command so I can also see previous deleted messages?

hushed galleon
#

store a list of messages per channel instead of one message?

ebon dagger
#

hello everyone, I had an issue with discord form. Everything is working correctly until I click on send form. Method callback of class MyModal, which is the child of discord.ui.Modal, just doesn't work. And I dont know why. Please, help me

hushed galleon
#

!d discord.ui.Modal.on_submit

unkempt canyonBOT
#

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

Called when the modal is submitted.
kindred epoch
#
default_time = datetime.datetime.utcnow().replace(hour=12,minute=0,second=0,microsecond=0)
future_time = default_time.replace(hour=abs(set_hour),minute=45,second=0,microsecond=0)
formatted_time = disnake.utils.format_dt(future_time,style='F')
await ctx.send(f"Guid refresh loop will start at: {formatted_time}.")
await disnake.utils.sleep_until(future_time,result=self.guild_refresh_reminder.start())

im trying to start this loop at a certain time, but whenever i use this command it sends the message its supposed to send when the loop starts right after

potent spear
#

Because, chances are, your future_time is something in the past, since you're replacing instead of adding up

kindred epoch
kindred epoch
torn sail
kindred epoch
slate swan
#

can someone help me idk what code to send man im confused

sick birch
#

so you need to await it

await bot.add_cog(...)
robust fulcrum
#

Guys how can i make a !d command like @unkempt canyon
It's very hard to understand code in its GitHub repo

unkempt canyonBOT
#
Command: docs

Look up documentation for Python symbols.

Source Code
robust fulcrum
sick birch
#

Well you did want to know how it's done

#

It's all right there

robust fulcrum
sick birch
robust fulcrum
hushed galleon
# robust fulcrum Guys how can i make a `!d` command like <@409107086526644234> It's very hard to...

based on @unkempt canyon's code it specifically reads documentation sites generated by Sphinx, which is fairly easier to handle since they come with a secret "objects.inv" file that stores all the objects described in their documentation and the corresponding URIs
https://github.com/python-discord/bot/blob/main/bot/exts/info/doc/_inventory_parser.py#L108-L114
https://www.sphinx-doc.org/en/master/usage/extensions/intersphinx.html

unkempt canyonBOT
#

bot/exts/info/doc/_inventory_parser.py lines 108 to 114

async def fetch_inventory(url: str) -> Optional[InventoryDict]:
    """
    Get an inventory dict from `​url`​, retrying `​FAILED_REQUEST_ATTEMPTS`​ times on errors.

    `​url`​ should point at a valid sphinx objects.inv inventory file, which will be parsed into the
    inventory dict in the format of {"domain:role": [("symbol_name", "relative_url_to_symbol"), ...], ...}
    """```
hushed galleon
slate swan
#

what's the d.py 2.0 equivalent to ctx.author.avatar_url

hushed galleon
#

ctx.author.display_avatar.url

slate swan
#

why'd they change it?

vocal snow
#

ctx.author.avatar_url returned an Asset which is misleading, you would expect it to return a str

hushed galleon
#

and yet it can convert to a url string, which dpy does for most methods

#

there are now also different avatars like default_avatar, avatar, and guild_avatar, hence why display_avatar exists to give you the one that you would expect to see

#

the old api was quite everywhere

meager linden
#

Not any pinned post for heroku alternatives?

hushed galleon
meager linden
real venture
#

Does anyone know a good replit bot template that I can use?

hushed galleon
sick birch
real venture
#

OK

hot prawn
#

I've create a hikari bot but the bot ain't responding

#
import hikari
bot = hikari.GatewayBot(token="...")

bot.listen()
async def ping(event: hikari.GuildMessageCreateEvent) -> None:
    if event.content.startswith("hk.ping"):
        await event.message.respond("Pong!")




bot.run()
#

it's online

patent lark
#

LMAO

#

WRONG CHANNEL

sick birch
#

sir this is a python discord server

rugged shadow
#

what were they saying

slate swan
#

get_user or fetch_user
I amuse fetch_user is better in most case's
because get_user does not return sometimes due to odd cahceing etc

Discord.py

#

guys

#

how do i make my discord bot only make commands work for a person with a specific role

#

Use a Decorator

#

@commands.has_role

#

use the documents if your not sure on how to use it

#

whats a decent way to delete any message that gets sent in a channel after a certain delay?

slate swan
slate swan
#

im using py-cord, i want to have options but the user must chose only one option like how we chose in radio button where there are multiple options and the user can only choose only one

slate swan
#

in slash commands

#

lets say 30

slate swan
slate swan
#

ah-

#

well imma have to rework everything probably then xd..

rugged shadow
#

why do you have to rework everything

slate swan
#

Creating bots for bitcoin. ThumbsUp

#

i may or may not have all my commands in an on_message()

#

!d

unkempt canyonBOT
slate swan
#

bruhhhhhhhhhhh

#

hm

#

how do i use @commands.has_role

#

!d discord.ext.commands.has_role

unkempt canyonBOT
#

@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return `False`.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
slate swan
#

like this


@command.has_role("Admin", 2298398498958)```
#

Nothing?
Like no one can help with a simple question

#

so you can whitelist a role only to use that command by name of ID.

#

or*

#

ok so

slate swan
slate swan
#

like this

#

so i put the command.has_roles right above the code

#

above @client.command()

#

ooo above it

#

Change "Admin" to the role name you want or use the role ID.

slate swan
# slate swan <:This:608402918172917770>

yes ur correct get_user might return None if the object was not cached, you should use fetch when get returns None
a proper way of doing it would be ```py
user = bot.get_user(id) or await bot.fetch_user(id)

#

don't have to use both

#

ik dont worry

slate swan
slate swan
#

Intents are good, cache is fine.
But the user does currently share a server with the client.

#

does that happen for a specific user or all users?

slate swan
#

Seems like a caching problem

#

mind showing your intents code and the bot class?

#

you already know i got that custom client class
lol


class client(commands.Bot):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.ipc = ipc.Server(self, secret_key="LevelMe")

    async def on_ipc_error(self, endpoint, error):
        print(f"IPC Error: {endpoint} raised {error}")
Client = client(command_prefix=commands.when_mentioned_or(config['Prefix']), intents=discord.Intents.all(), case_insensitive=True)
#

hm weird issue

#

Ikr.

#

anyways just use the get_user or await fetch,_user thing

#

mk

#

thanks,

vale wing
#

Doesn't nextcord have Interaction.send shortcut that automatically handles response and followups

#

!d nextcord.Interaction.send

unkempt canyonBOT
#

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

This is a shorthand function for helping in sending messages in response to an interaction. If the interaction has not been responded to, [`InteractionResponse.send_message()`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.InteractionResponse.send_message "nextcord.InteractionResponse.send_message") is used. If the response [`is_done()`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.InteractionResponse.is_done "nextcord.InteractionResponse.is_done") then the message is sent via [`Interaction.followup`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Interaction.followup "nextcord.Interaction.followup") using [`Webhook.send`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Webhook.send "nextcord.Webhook.send") instead.
vale wing
#

Yeah just use this why'd you need that response and followups grass

quick ice
#

Hello people, im looking to build a discord bot that will delete messages after a certain time. Can you help?

vocal snow
quick ice
vocal snow
quick ice
vocal snow
#

pretty much

#

on_message -> if message.content has a twitch link (using regex or whatever) -> asyncio.sleep for 5 hours -> message.delete

quick ice
#

So would that work on replit?

vocal snow
#

sure

#

replit poses a whole bunch of other issues which could interfere though

slate swan
#

how to get a specific guild in a button interaction

quick ice
#

I got this @vocal snow

vocal snow
#

...thats just pseudocode

#

you're supposed to write the actual python code yourself... lol

slate swan
quick ice
slate swan
slate swan
vocal snow
#

you need to know python in order to program a discord bot in python

slate swan
#

slate swan
#

anyone?

vocal snow
#

!d discord.Interaction.client

unkempt canyonBOT
#

property client```
The client that is handling this interaction.

Note that [`AutoShardedClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AutoShardedClient "discord.AutoShardedClient"), [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot"), and [`AutoShardedBot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.AutoShardedBot "discord.ext.commands.AutoShardedBot") are all subclasses of client.
slate swan
#

thanks man!

quick ice
vocal snow
#

If you know python basics, this should be easy to implement based on the pseudocode. You already have an on_message event, the next step is to check if the twitch link is in the message content

quick ice
#

Okays, so that link will explain pretty mu h everything i need to know? @vocal snow

vocal snow
#

yes

quick ice
vocal snow
slate swan
#

@vocal snow can you help me with one more thing?

vocal snow
#

sure

slate swan
#
class menu(ui.View):
    def __init__(self):
        super().__init__()
        self.value = None

    
    @ui.button(label='Bugs', style=discord.ButtonStyle.green)
    async def Bugs(self, interaction: discord.Interaction, button: discord.ui.Button):
        embed = Embed(title="Creating a ticket for Bug report")
        await interaction.response.send_message(embed=embed,ephemeral=True)
        guild = interaction.client.get_channel(guildid)
        print("test")
        #category = discord.utils.get(guild.categories, name="TICKETS")
        print("test")
        channeel = await guild.create_text_channel(f"ticket-{interaction.user.name}")
        print("test")``` i am trying to create a ticket system, it should work when someone presses the button but idk why it's not creating the text channel, guild id is correct
#

any idea?

vocal snow
slate swan
#

my bot scripts never throw any error 😦 it leaves me with finding the bug myself

#

it's in a cog

vocal snow
slate swan
#

apparently i don't

vocal snow
#

any error handlers for the command?

slate swan
#

nope

vale wing
#

I highly doubt that you overrided on_error method but check it anyway

slate swan
#

i'll add that later but any idea why it's not working tho?

vale wing
#

So use regex search on_.*error

slate swan
#

@vale wing can you help me with my interaction?

vale wing
#

First fix the error handlers

#

Because the errors don't appear ONLY because of that and nothing else can be eating them

vale wing
slate swan
#

@ticket.error
async def ticket_error(self, ctx, error):
raise error

#

smthn like this?

vale wing
#

Yes but globals

#

Locals too tho but the regex would be @.*\.error

slate swan
#

there used to be a default error handler in discord.py 1.7.3

#

how can i get that to work

#

i just wanted a little help with my interaction 🥲

#

Error handlers have been kept the same in 2.0 iirc

vale wing
#

Correct except I think there were events added for app commands

slate swan
#

the old ones don't work for me

#

Other than using this log thingy now

#

the old ones work fine for me kryptonShrug

slate swan
slate swan
#

What do you use to start the bot

#

In code

#

in cmd

#

How do you start the bot in code

#

In your code, you start/connect the bot

#

Most likely at the end of your file

#

client.run()

#

Yeah then you have an error handler eating your errors

#

And without error(s) we can't help as we're not seers that can guess your error(s)

#

i don't have any error handler in my code

vocal snow
#

something is eating your errors, we should pinpoint that first

#

have you set up logging?

slate swan
#

Though when using bot.run() there's a default one, which doesn't need to be setup

#

I've never setup logging and works fine with default logging when I tested the 2.0 changes

#

Was the most basic script to just get the bot online

slate swan
#

how do i make that a command would work only in one channel?

#

!custom-check

unkempt canyonBOT
#

Custom Command Checks in discord.py

Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check which allows you to create you own checks like this:

from discord.ext.commands import check, Context

def in_any_channel(*channels):
  async def predicate(ctx: Context):
    return ctx.channel.id in channels
  return check(predicate)

This check is to check whether the invoked command is in a given set of channels. The inner function, named predicate here, is used to perform the actual check on the command, and check logic should go in this function. It must be an async function, and always provides a single commands.Context argument which you can use to create check logic. This check function should return a boolean value indicating whether the check passed (return True) or failed (return False).

The check can now be used like any other commands check as a decorator of a command, such as this:

@bot.command(name="ping")
@in_any_channel(728343273562701984)
async def ping(ctx: Context):
  ...

This would lock the ping command to only be used in the channel 728343273562701984. If this check function fails it will raise a CheckFailure exception, which can be handled in your error handler.

slate swan
#

oh thanksss

#

how do i make buttons work anytime

#

like if i stop the bot and run it again it doesnt work

#

You probably need to setup a unique ID to the button and listen to events

#

listen to events?

#

Reading/taking a look at the documentation helps

#

also they do have an id

#
class system(discord.ui.View):
    def __init__(self, user):
        super().__init__(timeout=None)
        self.value = None
        self.timeout = None
        self.user= user

    @discord.ui.button( label="Other Games", style=discord.ButtonStyle.blurple, custom_id="other_games:blurple")
    async def system(self, interaction: discord.Interaction, button: discord.ui.Button):
      await interaction.response.send_message(view=TicketView(interaction.user), ephemeral=True)

class TicketView(discord.ui.View):
    def __init__(self, user):
        self.user= user
        super().__init__(timeout=None)

    
    @discord.ui.select(placeholder="Choose a role!", options=[
        discord.SelectOption(
            emoji="![1CounterStrike](https://cdn.discordapp.com/emojis/569987371538579456.webp?size=128 "1CounterStrike")", label="Counter Strike", description="Choose me if you want to be updated when someone wants to play CS!"
        ),
        discord.SelectOption(
            emoji="![valorant](https://cdn.discordapp.com/emojis/870290237530705973.webp?size=128 "valorant")", label="Valorant", description="Choose me if you want to be updated when someone wants to play Valorant!"
        ),
        
        discord.SelectOption(
            emoji="![cds](https://cdn.discordapp.com/emojis/1030088005786021899.webp?size=128 "cds")", label="Haxball", description="Choose me if you want to be updated when someone wants to play Haxball!"
        )
    ])
    async def help_callback(self, interaction: discord.Interaction, select):
        select.placeholder = f"Reason: {select.values[0]}"
        reason=select.values[0]
        if reason == 'Counter Strike':
            
            role=get(interaction.guild.roles, id=1030085444534292560)
            if role in interaction.user.roles:
                await interaction.user.remove_roles(role)
            else:
                await interaction.user.add_roles(role)
                await interaction.response.send_message(f"Chooses Counter Strike Succssesfully!", ephemeral=True)
        if reason == 'Valorant':
            role=get(interaction.guild.roles, id=1008808500744441876)
            if role in interaction.user.roles:
                await interaction.user.remove_roles(role)
            else:
                await interaction.user.add_roles(role)
                await interaction.response.send_message(f"Chooses Valorant Succssesfully!", ephemeral=True)
        if reason == 'Haxball':
            role=get(interaction.guild.roles, id=1030085098600669195)
            if role in interaction.user.roles:
                await interaction.user.remove_roles(role)
            else:
                await interaction.user.add_roles(role)
                await interaction.response.send_message(f"Chooses Haxball Succssesfully!", ephemeral=True)


@bot.command()
async def sys(ctx):
    view = system(ctx.author)
    embed=discord.Embed(title="**רוצים לדעת ראשונים כשמישהו רוצה לשחק?**", description="מוזמנים לבחור אחד מהרולים המופיעים כאשר אתם לוחצים על הכפתור! \n תהנו!")
    embed.set_footer(text=f"Requested by {ctx.author}")
    await ctx.send(embed=embed, view=view)```
slate swan
#

@slate swan

slate swan
#

and it doesnt work in any channel now

#

show code

slate swan
# slate swan show code
@bot.command(aliases=["Amongus"])
@discord.ext.commands.guild_only()
@commands.cooldown(1,940,commands.BucketType.guild)
async def amongus(ctx): 
    if ctx.channel.id is not 1005776398507581490:
        await ctx.reply("Please use that command in [#1005776398507581490](/guild/267624335836053506/channel/1005776398507581490/)!")
        return
        
    check = ctx.author.voice
    if check is None:
       voice = f'לא מחובר לחדר'
    else:
      voice = ctx.author.voice.channel.mention
    emibed = discord.Embed(title="מחפש שחקן למשחק אמונג אס", description=f'{ctx.author.mention} Among us מחפש מישהו לשחק! ',color=0x6c97c5)
    emibed.add_field(name="המשתמש נמצא בוויס:", value=voice, inline = False)
    await ctx.send(f" {ctx.author.mention} מזמין אתכם לשחק איתו! <@&890044017776136202>", embed=emibed)```
#

you sure that the ID is correct?

#

yes

#

use != instead of is not then

#

tho is not should have worked

#

okay

glad cradle
#

remove the not

slate swan
#

ill try now

#

WORKS

#

thankss

honest shoal
#

why I'm unable to have embed's color 0x000000?

#

I get an error console In data.embeds.0.fields.5.value: This field is required

glad cradle
#

!e
print(0x000000)

unkempt canyonBOT
#

@glad cradle :white_check_mark: Your 3.11 eval job has completed with return code 0.

0
honest shoal
#

idk it's hex code

glad cradle
#

!d discord.Colour

unkempt canyonBOT
#

class discord.Colour(value)```
Represents a Discord role colour. This class is similar to a (red, green, blue) [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)").

There is an alias for this called Color...
honest shoal
#

or not set

glad cradle
#

if you're speaking about embed it's the default color, you don't have to set it

honest shoal
#

you're right

slate swan
honest shoal
#

I got the issue

honest shoal
pseudo jungle
#
Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.```
#

how to fix this?

slate swan
#

enable intents from dev page

pseudo jungle
slate swan
#

Yes, try it and see PES_Smart

pseudo jungle
#

nothing happens

slate swan
#

Because you need to enable all the ones you've enabled in your code

#

If you enabled message_content, enable it in portal

#

If you enabled members, enable it in portal

slate swan
pseudo jungle
#

how to import youtube.dl?

slate swan
#

!ytdl

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
slate swan
#

In addition to that, Discord doesn't verify such bots anymore and start to unverify those who are doing it bravemmlol

pastel basin
#

Is there any way to send embed rules in a rules channel without using a specific command.

slate swan
#

You can use a webhook

pastel basin
#

Any documentation for it?

slate swan
pastel basin
#

Thanks!

slate swan
#

Just like sending a message in a channel but use the webhook url instead

quick ice
#

So I finally found the autodelete restapi.go file, so do i just copy all that into repl.it go file?

slate swan
#

To my knowledge this is a Python server

quick ice
slate swan
quick ice
slate swan
quick ice
slate swan
#

Someone most likely can gophercool

shadow vigil
#

like how reply to a message or send when it boots or you are new so you need an example

slate swan
#

What's wrong with it?```py
await msg.create_thread(f"{customid} | Let us know you voted!")
TypeError: create_thread() takes 1 positional argument but 2 were given

zealous jay
#

does it makes a difference if you do this?

    await msg.create_thread(name=f"{customid} | Let us know you voted!")
dull knot
tough stratus
#

I enjoy helping people in the help channels, but I know my area of expertise (numpy, matplotlib, etc.)
I'm sure it is possible to set up a bot to monitor the help channels and notify me when keywords show up, but i'm not sure the admins here welcome outside bots
Anyone have any thoughts on this?

slate swan
#

They most likely won't invite random third party bots.

unkempt canyonBOT
#

@pastel basin, looks like you posted a Discord webhook URL. Therefore, your message has been removed, and your webhook has been deleted. You can re-create it if you wish to. If you believe this was a mistake, please let us know.

slate swan
#

Specifically when it has only one use case, and mostly used by you (only)

uncut comet
#

i cant get my image to go inside the embed it currently just posts separately
with this code

        embeds = GetEmbed.act_triangle(endpoint.player, [data,season], response, self.bot)
        
        await interaction.followup.send(file = embeds[1], embed=embeds[0],view=view)
        result = TriangleGen.generator_triangle(data[0],player)
        if result:
            embed=discord.Embed(title=f"{player}", description="")
            x = discord.File(f".//{player}.png", filename=f"{player}.png")
            embed.set_image(url = f"attachment://{player}.png")
                                            #embed.set_footer(text=f"""Last updated: {jsonplayer["data"]["last_update"]}""")
                                            #print("made")
            return [embed,x]
        else:
            print("ERROR")

how can i fix it?

pastel basin
#
from discord import Webhook
import aiohttp

async def foo():
    async with aiohttp.ClientSession() as session:
        webhook = Webhook.from_url('', session=session)
        await webhook.send('Hello World', username='Foo')
#

It's not working..

#

I copied the code from documenation.

#

documentation*

#

Also, my url is correct.

#

I think I need to set the username to my webhook username?

slate swan
#

Well, with just that code it will never call the function foo()

pastel basin
#

Oh..

slate swan
#

So the code will never get executed kryptonShrug

pastel basin
#

There's another way, right?

#
import requests
slate swan
pastel basin
slate swan
pastel basin
slate swan
pastel basin
pastel basin
slate swan
#

asyncio.run(foo())

pastel basin
#

ok

slate swan
#

how to get all messages in a channel?

#
TypeError: object async_generator can't be used in 'await' expression```
paper sluice
#

its an async generator, so you have to iterate over it like

async for var in async_generator: ...
bright wedge
slate swan
#

thanks!

#

There is even an example in the documentation, if people would take the time to read it...

#

!d discord.abc.Messageable.history

unkempt canyonBOT
#

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

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

Examples

Usage...
slate swan
#

Even more than one example, actually two of them

#

Lazy people not looking at the documentation notlikethis

pseudo jungle
#
TypeError: BotBase.__init__() missing 1 required keyword-only argument: 'intents'```
#

how to fix this?

pastel basin
#

@slate swan

#

How can I enter guild name?

pastel basin
pastel basin
pseudo jungle
pastel basin
#

@pseudo jungle Learn the basics of python first.

pastel basin
#

Make discord bots after you are familiar with data structures...

slate swan
#

Also don't use .all() but .default()

pastel basin
#

Or maybe after leaning OOP

pastel basin
pastel basin
slate swan
slate swan
pastel basin
#

oh yes

slate swan
#

As well as you won't be given access to them if when verifying your bot if you don't have a valid use case. So yes, it matters

pastel basin
#

but... doesnt reall ymatter you know

#

I have a question

#

Do embeds update automatically with webhooks?

#

Like if the embed has my guild name

#

Will the name change if i change the guild name

slate swan
#

No, the message/text won't be edited automatically

pastel basin
#

Oh..

#

Thanks! I had this doubt

#

@pseudo jungle What's a string?

slate swan
#

No point on asking that.

pastel basin
#

Learn basics first mate

pastel basin
slate swan
#

Criticism like that is pointless and leads to nothing.

pastel basin
#

He's new to coding... and making bots

slate swan
#

It's rather offensive and not friendly at all.

#

So I'd recommend keeping such comments for yourself

velvet compass
#

This is still relevant btw

slate swan
#

Thanks Prayge

uncut comet
#

i cant get my image to go inside the embed it currently just posts separately
with this code

        embeds = GetEmbed.act_triangle(endpoint.player, [data,season], response, self.bot)
        
        await interaction.followup.send(file = embeds[1], embed=embeds[0],view=view)
        result = TriangleGen.generator_triangle(data[0],player)
        if result:
            embed=discord.Embed(title=f"{player}", description="")
            x = discord.File(f".//{player}.png", filename=f"{player}.png")
            embed.set_image(url = f"attachment://{player}.png")
                                            #embed.set_footer(text=f"""Last updated: {jsonplayer["data"]["last_update"]}""")
                                            #print("made")
            return [embed,x]
        else:
            print("ERROR")

how can i fix it?

slate swan
#

That's general python you can ask in the respective channel

sacred plume
#

oh. alright

#

didn't really want to occupy a help channel for a question little as that one

slate swan
pastel basin
#

It's not offensive!!! maybe you are thinking like that.

#

I asked him everything polite.

#

You are just being p..... .

velvet compass
sick birch
#

I wonder if pydantic has anything to do with that 🤔🤔

slate swan
#

That sounds to fit better when asked in the appropriate channel. Not a single thing related to Discord bots, even if used in a Discord bot that has nothing to do with any python Discord library.

#❓|how-to-get-help

cerulean folio
maiden fable
#

Yo @sick birch have u ever used the HTTP Based events?

pastel basin
#

Ah I need help with something

maiden fable
#

Shit

pastel basin
#

!e

print("\n Hello")
unkempt canyonBOT
#

@pastel basin :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 
002 |  Hello
pastel basin
#

It prints hello in new line

#

but.. how can I do that in embeds?

#

\n doesn't work.

maiden fable
#

Discord trims spaces and new line chars before and after the message

paper sluice
#

maybe ****\n....

pastel basin
#

Like here

#

Oh

maiden fable
#

Yea prolly that is the best way

#

That is still a discord bug lol

pastel basin
paper sluice
#

abusing bugs is the way of life

pastel basin
#

😅 lol

#

Fact

sick birch
#

I find using a list with “\n”.join to be a lot cleaner than having a large string with \n scattered about

paper sluice
#

or just use multiline strings

pastel basin
#

I used """"""

paper sluice
unkempt canyonBOT
#

@paper sluice :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | a
002 | b
003 | c
#

Hey @slate swan!

It looks like you tried to attach file type(s) that we do not allow (.zip). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.

Feel free to ask in #community-meta if you think this is a mistake.

paper sluice
#

or you can do

a = """a
b
c"""
print(a)
sick birch
#

Using sep=“\n” is better for print

paper sluice
#

yea

pastel basin
#

Not ****\n

maiden fable
#

Ryuga have u worked with HTTP Interactions?

paper sluice
#

nope

#

what are they btw

maiden fable
#

has anyone even worked with those

sick birch
#

!e print("line 1", "line 2", "line 3", sep="\n")

unkempt canyonBOT
#

@sick birch :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | line 1
002 | line 2
003 | line 3
paper sluice
maiden fable
#

Same

sick birch
#

shame

paper sluice
#

🔫

torn sail
maiden fable
#

Nice, but my friend do be using nextcord and I am too lazy to rewrite the bot 😭

torn sail
#

I don’t see the point of http interactions tho

maiden fable
#

You can host bot on websites like replit with HTTP Interactions since u don't get ratelimited if any other bot spams (ig lol)

paper sluice
maiden fable
paper sluice
#

just try it and break code

maiden fable
#

Might instead just ditch him

paper sluice
#

friendship++

slate swan
#

mission passed successfully

slate swan
maiden fable
primal token
# velvet compass Please finish that word

intimidating/encouraging a user to break the rules, not saying he was, i'm saying it in general, isnt something friendly or professional, personally i think referring a user to the rules of the guild and the Code of conduct and TOS is more friendlier way over intimidating a user which then other users will make fun of which you dont really mention to stop with the criticism and unnecessary comments, i'm saying this because it has happened to me and it gives a vision to the use that all mods can be condescending and at the end of the day the action done is inappropriate, why didnt i mentioned it to modmail? well, because i just didnt really felt like it

#

With all due respect i'm saying you should work on your approach to users that can be breaking the rules

cold sonnet
#

holy shit

velvet compass
primal token
#

Maybe marking the sentence with a question mark would be better and less intimidating, also finishing a discussion that isnt on topic and is inappropriate is better over causing more attention, as you can see there was a joke about it which I'm not going to say the users name but it was just totally unnecessary and can fall into the meaning of criticism

velvet compass
#

I just wanted to know what they were trying to say, to determine if it was something that broke our server rules. Given the context of discouraging other users by saying " go learn python first", I felt like it was worth asking in a direct way.

#

Any ways, as you have already pointed out lets finish the discussion which is off topic, and already over.

primal token
velvet compass
#

Clarifying what they meant to type directly leads to stopping the discussion

primal token
#

I wouldnt say it stopped the discussion at all but did the opposite of stopping it

cloud dawn
#

I don't want to mingle but I think this was better suited for Modmail. If you reacted instantly fine, but this was 3 hours ago, the chat is interrupted again.

primal token
#

The only discussion here was off topic. i wanted to tell my view to the user directly, but i will do next time if there's a question

mighty pilot
#

is there a way to grab the guild info inside ui.view?

#

or even a way to grab guild info outside any sort of interaction? trying to set button names according to a table thats different per guild

cloud dawn
#

!d discord.ui.Button.callback

unkempt canyonBOT
#

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

The callback associated with this UI item.

This can be overridden by subclasses.
mighty pilot
#

but dont they need to push the button for that? i need the name displayed on the button they press

cloud dawn
#

Well you pass the view class in the message right?

#

...("Message", view=View())

mighty pilot
#

yes

cloud dawn
#

It's a class so you can pass variables trough the init.

mighty pilot
#

hmm i think i see what youre saying. i can grab the guild info from the event triggering my message

cloud dawn
#

...("Message", view=View(interaction))

class View(discord.ui.View):
    def __init__(self, original_inter: Interaction) -> None:
        ...
mighty pilot
#

oooo ok ill play around with that

cloud dawn
#

Just note that you can't do any respond things but you can still get info from it.

mighty pilot
#

thats fine i just need guild info to use to recall a role name from mysql

cloud dawn
#

Why not the ID?

mighty pilot
#

putting role name as button name to press

cloud dawn
#

What if the role changes name?

mighty pilot
#

command to update db

cloud dawn
#

Wouldn't it be easier to insert the id then fetch the role get the name then display it? Auto updates unless the role is deleted ofc. But on_guild_role_delete could check for that.

mighty pilot
#

that is an option, it would be cleaner on discord

#

that just uses utils.get right?

cloud dawn
cloud dawn
mighty pilot
#

this is true

slate swan
#

if I use commands.AutoShardedBot, does it automatically manage sharding for me? Or do I have to do some stuff with it?

cloud dawn
#

tldr no

cloud dawn
mighty pilot
mighty pilot
#

tb...?

slate swan
#

!traceback

unkempt canyonBOT
#

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

A full traceback could look like:

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

If the traceback is long, use our pastebin.

mighty pilot
slate swan
#

Well, you don't give the parameter type when calling a function

#

What are you doing there though 3HC_what

fluid shadow
mighty pilot
#

i have role IDs stored in a database to recall later, im trying to pull the id from a database, in order to do that i need the guild id (name of the table) then using the ID, pull the name of the role, and use the name of the role in a button

slate swan
#

Well what's wrong is that you call __init__ and specify the parameter type when calling it, that's not allowed

#

You also use -> None: - that's also only for defining functions

#

Someone trying non existing commands

mighty pilot
slate swan
#

Well there's a small difference between that

mighty pilot
#

oh the super instead of the def

slate swan
#

and that

#

Create the command?

fluid shadow
slate swan
#

No you can't, the bot will just not do anything so don't need to care

north escarp
#

help to make a message counter, that is, it will show how many messages the user has written for the entire time while there is a bot on the server. I know that this requires a database. But I want to do just a message counter for now.

slate swan
#

Have you even tried anything?

If not

  • Try something
  • Come back with issues or uncertainties you're facing
north escarp
slate swan
#

Well as you said, you need a database at some point

#

Other than that you can listen to the on_message event to know who sends a message, then you can increase their personal counter

north escarp
slate swan
#

When using a command like, for example, /messages the bot will give that personal counter back

north escarp
fluid shadow
slate swan
#

I mean, without database it's just about increasing a counter variable

fluid shadow
slate swan
#

Maybe use a dictionary to store like that

{
  user_id_one: counter,
  user_id_two: counter,
  ...
}
fluid shadow
slate swan
#

And when there is a message sent, you can use the on_message event

#

Increase, or create if it's not existing yet, the counter for the user ID

fading marlin
#

Oh, I just checked your code, and your RowButton class doesn't appear to have any callback @fluid shadow

fluid shadow
slate swan
#

Yeah was about to say that

mighty pilot
#

now how do i get btn1 to carry over to the button name?

slate swan
#

You cannot access a variable that is inside a function, within a different function

#

Python scopes basics

mighty pilot
#

whelp. sorry i suck lol

slate swan
#

!e

def a():
  x = "hello"

def b():
  print(x)

a()
b()
unkempt canyonBOT
#

@slate swan :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 8, in <module>
003 |   File "<string>", line 5, in b
004 | NameError: name 'x' is not defined
slate swan
#

x is only available in the scope of the function a

hidden yarrow
#

then the function inside can access it too

fading marlin
# mighty pilot now how do i get btn1 to carry over to the button name?

discord.ui.button is a decorator that returns a Button class. Decorators "convert" the given function to whatever they return. So basically, Role1 will be a Button class instead of a function. Knowing this, you can set the label of the class in your __init__:

class A:
    def __init__(self, ...):
        self.button_callback.label = "label"

    @discord.ui.button(...)
    async def button_callback(self, ...):
        ...
slate swan
#

Well, the issue is not in the function

#

It's in the decorator

#

So no, that won't help

#

What Lee said though, is correct

mighty pilot
#

oh so i can define the label in the init instead of in the button itself. that makes it a whole lot easier. thanks guys

fading marlin
#

No problem!

slate swan
#

Exactly, that way you can access the variable you need

slate swan
#

how i can change percent ram to int number?

#
{int(psutil.virtual_memory().percent)}%`/`8 RAM```
#

That's basic maths

#

So how to do it?

#

Use the maths you've learned in first class

#

8 * 0.84?

#
| 100% | 84%  |
|------|------|
| 8 GB | X GB |
#

Yah

#

Probably want to use MBs though

#

So i can do:

#
{int(psutil.virtual_memory().percent * 8)}GB`/`8 RAM 
#

I can't try it rn

#

i'm on mobile

slate swan
#

That's the rule of three....

#

So i alway have percents

#

Among the first thing you learn

#

In mathematics, specifically in elementary arithmetic and elementary algebra, given an equation between two fractions or rational expressions, one can cross-multiply to simplify the equation or determine the value of a variable.
The method is also occasionally known as the "cross your heart" method because lines resembling a heart outline can be...

#

8*84/100

fading marlin
slate swan
#

Yeah

#

Output is in bytes, just as side note

#

Can convert to MBs with x / 2 ** 20

mighty pilot
#

been messing with get() for a while and cant get it to return anything but None. should i be using an api call with fetch_roles instead?

fading marlin
#

id kwarg should be an int, not a string

mighty pilot
#

tried roleid instead of f'{}' and still nothing

fading marlin
#

is roleid an integer?

mighty pilot
#

you can see in the back window i printed roleid and what get returns

#

numbers, and None

slate swan
#

Hello, i need some help creating a transcript function, so when a user does !close it will save the chat history and send it to a channel

fading marlin
mighty pilot
#

is there a way to change their type?

fading marlin
#

use type sorry, I read something else. Cast the value to int to change it to an integer

north escarp
#

how can I make it so that when you click on the bot there is a tab to try out slash commands that you can click on and they will work. How can this be done ?

fading marlin
#

you can't. That is something Discord does

north escarp
fading marlin
#

what?

slate swan
#

You can't control it or write/change them manually

#

When your bot has slash commands that are used, it will show the most used (if I remember correctly) slash commands there

north escarp
slate swan
#

You mean that right

north escarp
slate swan
#

Yeah as already said, that is done automatically there is nothing you need to do

#

It's done automatically by Discord
You can't control it or write/change them manually

north escarp
slate swan
#

Nope, not in that section

north escarp
#

it's just that I already have slash commands

slate swan
#

What you can do though

#

Then they need to be used and they will appear there

#

Though you can use </command name:command id> and write that down in the "About me" section of the bot

glad cradle
#

they appear only in verified Bots

slate swan
#

It then looks like </command name:0> for example

#

And to copy a command ID, you just need to write the command and then right click on it

slate swan
#

?

north escarp
grim mica
#

So I'm trying to make a mini database with a json file that stores some info about discord users for a bot. I've watched multiple tutorials but all of them just create them not the way I need it. I would need something like this:

{
    "IDV":{
        "userId":562699506253168640,
        "channelUrl":"https://www.youtube.com/channel/UCiUQbWlzRDO-WOr7Ld2z6Kg",
        "latest video":"https://www.youtube.com/watch?v=UaB80cqQm7c"
    },
    "Ety60":{
        "userId":721412435378176047,
        "channelUrl":"https://www.youtube.com/channel/UCiUQbWlzRDO-WOr7Ld2z6Kg",
        "latest video":"https://www.youtube.com/watch?v=4HA00LGtlTk"
    }

I need to be able to search thru all usernames (In ex: IDV & Ety60) and get info when needed.

  1. I need to be able to add a new "user" with its data to the database
  2. I need to be able to get data when a username is given
  3. I need to be able to change specific data of a specific user

I just need help to get started...

fading marlin
#

please just use an actual database instead of JSON

grim mica
#

Thats way more complicated

#

I just need to store some data

fading marlin
#

maybe read this first

grim mica
#

Ye I already read something like it

#

Thats its going to corrupt etc

#

Then what database should I use? sqlite?

fading marlin
#

sure

grim mica
#

I want something simple tho

#

sqlite look very complicated

fading marlin
#

sqlite is as simple as databases can get lol. SQLite is file-based, so no worries about credentials and all of that other hassle. Learning some basic SQL is basically all you need to know

lament acorn
#

Indeed

fading marlin
grim mica
#

wait I need wrappers

#

nope thats not happening

#

I want it to be simple

#

I just need to store some data, like I already said

#

No need for big complicated data base sql ...

slate swan
fading marlin
#

jeez, you'd probably need an async io wrapper if you're gonna be using JSON too

grim mica
#

why tho

lament acorn
#

sqlite is simple, the integration for async is likely drop in

slate swan
#

Because that's how it works

#

You need a wrapper either way

slate swan
#

So use an async wrapper instead of an awful json wrapper

slate swan
#

Don't remember saying it.

grim mica
#

I didn't mean installing it ofc thats simple.
I don't want to go thru the docs for hours just to store some yt channel id's

fading marlin
slate swan
#

You said

I want it to be simple

Installing the correct async wrapper for sqlite is simple.
You will also need a wrapper for JSON either way, so directly go for the sqlite one.

grim mica
#

ok sure

slate swan
#

You'll need to read the documentation of JSON wrapper as well either way, so just read the one of sqlite

#

And if you need help with sqlite there's a #databases channel made for it

grim mica
#

Ok what wrapper would you recommend

slate swan
#

aiosqlite is fine

grim mica
#

ok thnx

fading marlin
#

no problem and happy coding!

grim mica
#

You mean happy reading docs 😉

slate swan
#

Not that complex you'll see, most likely also have some examples. Otherwise yeah ask in #databases gophervictorious

primal token
#

aioqlites docs are quite easy to read, very simple and straight forward

slate swan
#
  • reading documentations is part of being a developer kryptonShrug
primal token
lament acorn
fading marlin
#

documenting code blobpain

primal token
#

I hate it

slate swan
primal token
#

🤨

slate swan
#

Just not documenting code itself, that's horrible

primal token
#

i hate both, documenting the code and working with front end

slate swan
#

But documenting your project or an API for example, that's nice

primal token
#

just not a nice experienceducky_regal

slate swan
#

Depends honestly

primal token
#

i hate it when i document my code and the docs fail to build, i hate reading the readthedocs logs

#

they're huge

slate swan
#

Yeah that I don't like

#

But documenting a project or writing a wiki, that's cool

primal token
#

you write a wiki about the project?

slate swan
#

Usually I do yeah

#

Specifically when it's a big project

primal token
#

nice

slate swan
#

Or something that is used and needs documentation on how to use it

fading marlin
#

"Just try to figure out what I'm trying to accomplish by reading my function names, argument names, and my non-existent comments" notlikeduck

slate swan
#

But yeah not everyone likes it the same way kryptonShrug

slate swan
primal token
slate swan
#

The code itself is your comments

primal token
fading marlin
primal token
#

ive actually never used that comment

fading marlin
#

Pretty useful (type checking-wise) when you wanna reverse-engineer something (like interaction objects)

grim mica
#

Hmm just saw this

#

Thats an async bot with none async json

slate swan
#

Welcome to the side of bad YouTube tutorials you should not be following

primal token
slate swan
#
  1. Using JSON is bad
  2. Not doing it async is bad
  3. It's 2 years old
#

Simply don't follow YouTube tutorials

#

Haven't seen any that is anywhere close to good

grim mica
#

Very nice tutorials

primal token
#

Lucas🥹

slate swan
#

Isn't that the guy that everyone criticizes for bad tutorials bravemmlol

grim mica
#

Than you haven't watched them lol

#

Helped a lot while starting out

slate swan
#

knew it

primal token
slate swan
#

Good thing I never watch any YouTube tutorials

#

Documentation + articles are so much better for everything

grim mica
primal token
#

His tutorials made me fall into tutorial hell and his code wasnt even good

primal token
#

most python docs use the OOP paradigm

slate swan
#

They all look the same so yeah

primal token
#

theyre mostly mapped the same also

grim mica
#

no examples = unreadable
You read all that bs takes you an hour to understand and if they just put a fking example it would take 2 seconds to understand that shit

slate swan
#

Even when I first read the documentation it wasn't hard to understand it

slate swan
#

No?

grim mica
#

Ye

#

well maybe if you read docs regualry

slate swan
#

You don't know how I understand and read documentations. You're not me.

grim mica
#

No but I know that exaples are better

slate swan
#

So don't say it's bullshit if you're the one not being able to read documentations properly.

grim mica
#

waaaayyy easyer to understand

slate swan
#

There are examples, the ones that are needed.

grim mica
#

aka none

slate swan
#

So you've never opened the documentation

grim mica
#

I have

primal token
slate swan
#

That explains everything now

grim mica
#

A lot of times

grim mica
slate swan
#

Everything else that is not explicitly written is self explaining for someone that has the knowledge that is highly recommended before starting a bot.

dry kelp
primal token
#

Have you actually read the documentation?

slate swan
grim mica
#

I have

slate swan
#

No you haven't

grim mica
#

How do you know I haven't

#

I read them so i know lol

slate swan
#

There is a quick start, lots of examples, as well as explanations for using commands etc.

primal token
#

I'm not saying you havent read the documentation but your opinions are just incorrect

grim mica
#

Bruh not the quick start

slate swan
#

So either you haven't read or you just don't want to take the time to read and navigate through the documentation properly.

grim mica
#

opinions are never incorrect

#

thats bs

slate swan
#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
slate swan
#

No examples you say huh

primal token
slate swan
#

I wonder what "Examples" means

primal token
dusky rock
#

My bot keeps getting rate limited 😔

primal token
grim mica
slate swan
#

And those are just some among lots of examples

dusky rock
grim mica
#

Nahh not lots

primal token
#

Your point is still incorrect

slate swan
grim mica
#

Opinions are never incorrect @primal token

slate swan
#

They're just attributes to use

primal token
slate swan
#

You for real want something like

discord.Member

id - Attribute
Example

print(member.id)

name - Attribute
Example

print(member.name)
#

That's just not knowing that the library recommends you to know before starting.

primal token
slate swan
# dusky rock Ye

In that case you'll need to change, Replit is known for that as they share IPs among lots of projects. See the pinned messages to read why Replit is a bad solution.

primal token
grim mica
#

Well I have been reading the docs to get things working and I did not have any examples for the things I was using so my opinion is that the docs are bad

#

Now happy?

primal token
#

That's from personal experience but do you have the knowledge needed to read the documentation? That's like doing a surgery without the knowledge of basic anatomy

dusky rock
grim mica
primal token
slate swan
rare saddle
#

What could be the problem?

sick birch
rare saddle
sick birch
#

That error is somewhere else entirely

rare saddle
sick birch
#

Also please paste the traceback as text, it's hard to read

rare saddle
#
Traceback (most recent call last):
  File "F:\IT\Discord Bots\Neka\main.py", line 49, in <module>
    asyncio.run(Neka().main())
  File "C:\Users\Egor\AppData\Local\Programs\Python\Python310\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Users\Egor\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
    return future.result()
  File "F:\IT\Discord Bots\Neka\main.py", line 24, in main
    await self.custom_load_extension(path='commands')
  File "F:\IT\Discord Bots\Neka\main.py", line 20, in custom_load_extension
    await self.load_extension(f'{path}.{cog[:-3]}')
  File "F:\IT\Discord Bots\Neka\venv\lib\site-packages\discord\ext\commands\bot.py", line 1012, in load_extension
    await self._load_from_module_spec(spec, name)
  File "F:\IT\Discord Bots\Neka\venv\lib\site-packages\discord\ext\commands\bot.py", line 937, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'commands.play' raised an error: TypeError: callback 'PlayCommand.play' must have more than 1 parameter(s)
sick birch
#

what's the code for your play command?

sick birch
rare saddle
#

ohhh, right

rare saddle
# rare saddle
Traceback (most recent call last):
  File "F:\IT\Discord Bots\Neka\main.py", line 49, in <module>
    asyncio.run(Neka().main())
  File "C:\Users\Egor\AppData\Local\Programs\Python\Python310\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Users\Egor\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
    return future.result()
  File "F:\IT\Discord Bots\Neka\main.py", line 24, in main
    await self.custom_load_extension(path='commands')
  File "F:\IT\Discord Bots\Neka\main.py", line 20, in custom_load_extension
    await self.load_extension(f'{path}.{cog[:-3]}')
  File "F:\IT\Discord Bots\Neka\venv\lib\site-packages\discord\ext\commands\bot.py", line 1012, in load_extension
    await self._load_from_module_spec(spec, name)
  File "F:\IT\Discord Bots\Neka\venv\lib\site-packages\discord\ext\commands\bot.py", line 951, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'commands.play' raised an error: TypeError: object NoneType can't be used in 'await' expression
sick birch
#

add_cog needs to be awaited

rare saddle
slate swan
#

What's the best way to implement a command with pagination? @sick birch

rapid bough
#

how do i get the guild id

primal token
unkempt canyonBOT
rapid bough
#
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
#

why am i getting this error when the token is correct

sick birch
sick birch
#

You can try printing out the token to see if it's None or your actual token

rapid bough
#

when i put the token in the main file it is working and when i get the token from env file its showing the error

#

thanks i did it now its working

slate swan
#

can i make a dropdown menu of members?

fluid shadow
hot prawn
glad cradle
fluid shadow
#

same thing, kinda lost

fluid shadow
# glad cradle you need to defer the interaction
@ui.button(label="Cashout", style=discord.ButtonStyle.green, custom_id="erqwkelrqwkadsf")
    async def cash_callback(self, button, inter):
        await self.Cashout()
        button.disabled = True
        button.label = "Cashed"
        await inter.message.edit(view=self)
        

This results in not disabling and messed up format

austere vale
#
    #Authentication with twitch API:
    client_id = os.getenv('client_id')
    client_secret = os.getenv('Dweller_token')
    twitch = Twitch(client_id, client_secret)

does anyone know how to get my twitch token?

Traceback (most recent call last):
  File "C:\Users\kouxi\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 800, in _load_from_module_spec
    setup(self, **extras)
  File "c:\Users\kouxi\Runa\cogs\twitch.py", line 102, in setup
    bot.add_cog(TwitchCog(bot))
  File "c:\Users\kouxi\Runa\cogs\twitch.py", line 15, in __init__
    twitch = Twitch(client_id, client_secret)
  File "C:\Users\kouxi\AppData\Local\Programs\Python\Python310\lib\site-packages\twitchAPI\twitch.py", line 168, in __init__
    self.authenticate_app(target_app_auth_scope if target_app_auth_scope is not None else [])
  File "C:\Users\kouxi\AppData\Local\Programs\Python\Python310\lib\site-packages\twitchAPI\twitch.py", line 436, in authenticate_app
    self.__generate_app_token()
  File "C:\Users\kouxi\AppData\Local\Programs\Python\Python310\lib\site-packages\twitchAPI\twitch.py", line 408, in __generate_app_token
    raise MissingAppSecretException()
twitchAPI.types.MissingAppSecretException
slate swan
#

how can i make my bot wait for something like a message

#

like when i press a button it should say: send your message

#

is there any way to do it?

naive briar
unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
slate swan
slate swan
#

interaction.response.send_message

#

u mean reply to an interaction with a message or???? this question is confusing

slate swan
slate swan
slate swan
#

i don't want to use modal

#

i wnat to mention a user and it's not possible in modal

slate swan
slate swan
slate swan
slate swan
slate swan
#

no offense but ppl make stuff so complicated w bot sometimes

slate swan
#

it would be simpler to just use a slash command that has member parameter

slate swan
#

no like ur use case has no logic. It would make more sense to just use a slash command rather than creating an entire button

#

sending a message then using wait_for

#

a get a mentioned user in that message

#

i understand that it's total non-sense to use a button then add a whole different function to it when you can just use slash commands and make it simple

#

it's just that my client wants something else lol

#

tell him to wait for new select menu to be implemented into ur lib

#

you can fill them with roles, members, etc… now

#

I stopped making bots for ppl like that lmao

#

So bascially you're asking us to help you code something you're getting paid for instead of reading the documentation 3HC_what

#

haha, i think you're right and it's best if i stick to slash command i'll just tell him it's waste of time

#

Why would you offer that in the first place

slate swan
slate swan
slate swan
#

ik dpy and disnake have them

#

Just use the documentation and examples, if you have the knowledge people want when buying your services then you don't need anything else than that

#

If you don't have the knowledge you're selling them and expect you to have, that's another situation

#

it's just people see other people doing that stuff they want a taste of it too

glad cradle
slate swan
slate swan
vale wing
#

😏

#

I live in Russia anyway I can't get paid

slate swan
#

with their automod

slate swan
#

whatt

slate swan
honest shoal
#

It's nice, dyno/mee6 made a lot money with that

vale wing
slate swan
#

u know what I recently found out discord is protecting mee6 lol

#

all the discord music bots mostly got removed yet you can still play YouTube videos with mee6 in VCs 🤣

vale wing
#

L

honest shoal
slate swan
#

yea sadgeeeee

#

Well we don't know what their internal specifications are

#

There was only one wave, and there are other bots than MEE6 that are still verified and still use YouTube

#

More might and probably will be coming later

#

And you don't know if MEE6 may have an official contract with YouTube - doubt they have but you never know

#

So wouldn't randomly speculate

#

i doing a command which requires to wait and lets say update time every one min and give result after 5 min, how do i achieve this?

buoyant quail
maiden fable
buoyant quail
#

sad.. ok, thanks

hot prawn
#

I made a command named deathnote, i want it to go like, if user left reason null it will give output Heart attack but when i give reason it dont work and if i dont give a reason it says None(bad english btw)

@bot.command()
async def deathnote(ctx, member: discord.Member, *, reason = None ):
  if reason==None:
    reason=="Heart attack"
    await ctx.send(f"User {member.mention} has died because of {reason}")
slate swan
#

its possible for commands

maiden fable
buoyant quail
# slate swan for commands, or interaction in general?

I think for commands will be enough for me.

Also won't

setattr(Interaction, "something", lambda self: print("hello"))

work?
bcs this code works:

class Something:
    ...

setattr(Something, "something", lambda self: print(self))

x = Something()
x.something()
slate swan
maiden fable
#

^

slate swan
unkempt canyonBOT
#

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

This function processes the application commands that have been registered to the bot and other groups. Without this coroutine, none of the application commands will be triggered.

By default, this coroutine is called inside the [`on_application_command()`](https://docs.disnake.dev/en/latest/api.html#disnake.on_application_command "disnake.on_application_command") event. If you choose to override the [`on_application_command()`](https://docs.disnake.dev/en/latest/api.html#disnake.on_application_command "disnake.on_application_command") event, then you should invoke this coroutine as well.
slate swan
#

can override this method with providing your own interaction subclass

buoyant quail
#

cool, thanks!

slate swan
#

it does say the bot is offline only your emoji is wrong

buoyant quail
#

also

import disnake
from disnake.ext import commands
bot = commands.Bot()

setattr(disnake.Interaction, "test", lambda self: print("hello"))

@bot.slash_command()
async def show(interaction: disnake.CommandInteraction):
    interaction.test()


bot.run()

this worked for me really, i got hello in console

buoyant quail
slate swan
glad cradle
#

that's not true, it's saying that the Bot is offline

#

lmao you switched the emojis

#

probably the cache has not been updated yet

#

try to use an Api call

slate swan
#

fetch_

slate swan
#

!d discord.on_member_join

unkempt canyonBOT
#

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

This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
shrewd apex
#

del/back space that part and write again

#

delete that whole thing and rewrite it

hazy oxide
#

nextcord.TextChannel

#

oh, you're using slash command

#

Use GuildChannel and SlashOption

vale wing
vale wing
#

But why

buoyant quail
#

i need to add some functions there

#

just because i want

#

it will make my life easier

vale wing
#

I'd say this is an untypical way of extending functionality

#

Because you will have to do all this stuff for literally every function

#

You better make a custom subclass and then assign entire subclass to parent class name

#

Like

class MyInteraction(discord.Interaction):
    def some_custom_func(self):
         ...

discord.Interaction = MyInteraction```
#

Apparently this works fine

maiden fable
vale wing
#

Whose is

#

Both are tho

slate swan
#

exenifix's method is better cause it will support stuff like IDEs autocompletes and typechecks lol

#

setattr wont help in either

vale wing
#

Depending on what stuff he wants the functions to do it might be better to just use functions with interaction as argument instead of OOP

maiden fable
# vale wing Whose is

Even tho yr method is the correct one, tbh I feel like its ugly. I myself prefer editing the source files directly due, but we all got different opinions

vale wing
maiden fable
#

Nice

vale wing
#

But for stuff like "send success embed to interaction" I use some module with utility functions why bother subclassing internals and then overriding them

maiden fable
#

I agree
Diving in discord.py's source is the same as trying to dive into black magic ;-;

#

I never understood how everything works, all I know is, it ✨works✨

vale wing
#

Python C sources (literally any C code actually) look even darker to me

maiden fable
#

Never tried to dive into it since I already have a headache for most of the day without diving into the same lol

slate swan
#

can i make my cooldowns to only work if it's not me?

shrewd apex
#

make ur custom cooldown

primal token
novel prairie
#

Why it doesnt work? py @bot.command() async def meme(ctx): subreddit = reddit.subreddit("dankmemes") all_subs = [] hot = subreddit.hot() for submission in hot: all_subs.append(submission) random_sub = random.choice(all_subs) url = random_sub.url name = random_sub.title author = random_sub.author upvotes = random_sub.score if random_sub.is_reddit_media_domain and not random_sub.is_video: embed = discord.Embed(title=name, description=f"{ctx.author.mention}", color=000000) embed.set_image(url=url) embed.set_footer( text=f'''from r/dankmemes by {author} | {upvotes} upvotes''') await ctx.send(embed=embed)

slate swan
#

guildID I suppose