#discord-bots

1 messages · Page 290 of 1

slow escarp
#

i want it to close automaticly(give me a weopon)

shrewd apex
#

make a bat script or python script

#

close the bot

slow escarp
#

bat script or python script to close the bot?

shrewd apex
#

simplest way is just make a task and call bot.close after half an hour

slow escarp
#

idk how to make a timer 😭

shrewd apex
#
await asyncio.sleep(60 * 30) # sleep 30 mins
await bot.close()
#

make a task and call it in setup hook

#

!d asyncio.create_task

unkempt canyonBOT
#

asyncio.create_task(coro, *, name=None, context=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task) and schedule its execution. Return the Task object.

If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name).

An optional keyword-only *context* argument allows specifying a custom [`contextvars.Context`](https://docs.python.org/3/library/contextvars.html#contextvars.Context) for the *coro* to run in. The current context copy is created when no *context* is provided.

The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError) is raised if there is no running loop in current thread.

Note

[`asyncio.TaskGroup.create_task()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.TaskGroup.create_task) is a newer alternative that allows for convenient waiting for a group of related tasks.
slow escarp
shrewd apex
#

thats basic async python

slow escarp
#

i though it was just @client.setup_hook

shrewd apex
#

no?

#

setup_hook takes in a function dont think you can use it as a decorator

#

my point is make a function with those two lines above and call it using create_task

dusk dagger
slow escarp
#

await asyncio.sleep(1) that 1 is a second right?

dusk dagger
#

yep

#

check out this it you’d like

slow escarp
#
import asyncio
import time

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    print(f"started at {time.strftime('%X')}")

    await say_after(1, 'hello')
    await say_after(2, 'world')

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())
#

i dont understand it

#

async def say_after(delay, what): what is that arg "what"

#

WHY DO U NEED IT

buoyant quail
#

Why not ¯_(ツ)_/¯

#

You can remove it if you don't need it

slow escarp
#

PLUH🗣️

buoyant quail
#

Here it's to give message to print out later

slow escarp
#

cant i just make a timer with time

buoyant quail
#

You can.
But your bot will go offline for the time you will sleep with time

naive cave
#

i have intermediate experience w/ python but not the discord package. for some reason my code isnt working? i think i setup wrong?

from discord.ext import commands
intents = discord.Intents.default()  # This creates a default set of intents
intents.messages = True 
client = commands.Bot(command_prefix = '!', intents=intents)
# waiting for bot to be ready for use
@client.event 
async def on_ready():
    print("Bot is ready :)")
# a command whenever a client types in "hello" it calls the "hello" func
@client.command()
async def hello(ctx):
    await ctx.send("hello, i am kenneth pause")
client.run("here is my token i am assuming")```
#

is this fine? i was following some tutorial

unkempt canyonBOT
#
Discord Message Content Intent

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

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

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

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

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

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

naive cave
#

and for some reason whenever i type in the command !Hello its not working

buoyant quail
slow escarp
#

its hello not Hello with a capital

buoyant quail
#

Also true

naive cave
#

yeah i did !hello

#

and its not working but let me try the fix

slow escarp
#

intents = Intents.default()

turbid condor
slow escarp
#

intent.message_content

#

not messages

#

also try this

#
@client.command()
async def test(ctx):
    await ctx.send("RUNNING")```
naive cave
#
intents.message_content = True # enable message content ```
so like this?
naive cave
#

i did but i get an error 😦

turbid condor
naive cave
#

ohhh wait i didnt enable it

slow escarp
#

intents = Intents.default()

naive cave
#

mb

#

hol up

turbid condor
slow escarp
#

oh

#

if its less typing i will 100% do it xd

turbid condor
naive cave
#

where can i enable privileged intents on discord developers?

turbid condor
slow escarp
#

bot section

naive cave
#

oh shit nvm im stupid

slow escarp
turbid condor
naive cave
#

its working is intents part of the discord package?

turbid condor
#

Yeah

#

@slow escarp
intents= discord.Intents.default() is same as

from discord import Intents

intents= Intents.default()
naive cave
#
intents.message_content = True # enable message content 
client = commands.Bot(command_prefix = '!', intents=intents)```

i tried asking chatgpt what this does but i think the discord package might have updated after 2021 since chatgpt is saying this is wrong. what does this do?
slow escarp
#

if you dont import intents client = commands.Bot("!",intents=intents) doesnt work

naive briar
#

Why wouldn't it?

naive cave
slow escarp
#

intents = intents how does it know what it intents

naive briar
#

If you defined it, it doesn't matter what you import

turbid condor
turbid condor
#

Most of it's knowledge is old

#

And d.py has changed too much

naive cave
#

mmm okay what does intents mean and do though?

slow escarp
#

if i dont import it NameError: name 'Intents' is not defined

naive briar
unkempt canyonBOT
#
Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

slow escarp
#

Intents are a feature of Discord that tells the gateway exactly which events to send your bot (copy pasted)

turbid condor
naive briar
zealous lance
#

how do i make slash commands?

turbid condor
zealous lance
naive briar
#

Library

slow escarp
turbid condor
#

What library are you using?

slow escarp
#

i think

zealous lance
turbid condor
zealous lance
#

ty i will try!

turbid condor
#

Welp read it carefully

zealous lance
#

i will!

turbid condor
#

Since it contains almost everything you require to create and use slash command s

upbeat otter
#

and 2.0**+** wow

cloud dawn
dreamy dune
#

Why does this work

#

Methods with ping

cold sonnet
#

don't question it if it works don't touch it

buoyant quail
#

I love the url

#

malware-l.ink

slate swan
cold sonnet
#

what's there that shouldn't work

buoyant quail
cold sonnet
#

I see

#

perhaps the command is well coded

buoyant quail
#

You know jishaku?

cold sonnet
#

no

#

what's that

slate swan
#

!pip jishaku

buoyant quail
unkempt canyonBOT
cold sonnet
#

more japanese named cool shit

zealous lance
#

can someone help me with my slash commands? discord.py

cerulean folio
#

Hi guys !
This question concerns Discord API but not bots, although I still think I should post it here.

I'm trying to get user informations from a user id and according to discord api reference, I have to set up my oauth 2.0 token which I did. The following request works like a charm:
https://discord.com/api/v10/users/@me and the ressource server responds with all my informations.

However when I replace @me with a user_id it responds with a 401 unauthorized error, which is not supposed to happen according to discord api reference.

Anyone has a tip about that? I'm still new to oauth and api requests so I got quiet lost

cold sonnet
#

not reading allat on phone

slate swan
#

I'm trying to put a thumbnail on discord.Embed object. The url I'm trying to set requires cookies in order to fetch the image.
I thought of two options:

  1. Download the image in a local directory and put it on the embed.
  2. Send the image using discord.File(BytesIO(requests.get(url, cookies=cookies).content), filename=filename) , get the image url from the sent message using message.attachments[0].url , and put the url to discord.Embed().set_thumbnail() .
    Is there any other way? I don't want to download or send the actual image before the process.
cerulean folio
naive briar
zealous lance
#

why do i need to add fallback with this? @client.hybrid_group(fallback="info")

slate swan
buoyant quail
zealous lance
naive briar
buoyant quail
zealous lance
# buoyant quail Where Show code + error

the error: ```2023-08-22 20:37:17 ERROR discord.app_commands.tree Ignoring exception in command tree
Traceback (most recent call last):
File "C:\Users\Flori\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\tree.py", line 1089, in wrapper
await self._call(interaction)
File "C:\Users\Flori\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\tree.py", line 1221, in _call
command, options = self._get_app_command_options(data)
File "C:\Users\Flori\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\tree.py", line 1153, in _get_app_command_options
raise CommandSignatureMismatch(command)
discord.app_commands.errors.CommandSignatureMismatch: The signature for command 'server' is different from the one provided by Discord. This can happen because either your code is out of date or you have not synced the commands with Discord, causing the mismatch in data. It is recommended to sync the command tree to fix this issue.



code: ```@client.hybrid_group()
async def server(ctx):
    guild = ctx.guild
    if guild:
        embed = discord.Embed(title=f'Server Info - {guild.name}', color=discord.Color.blue())
        embed.add_field(name='Server ID', value=guild.id, inline=False)
        embed.add_field(name='Owner', value=guild.owner.mention, inline=False)
        embed.add_field(name='Member Count', value=guild.member_count, inline=False)
        await ctx.send(embed=embed)
    else:
        await ctx.send("This command can only be used in a server.")```
buoyant quail
#

Just your commands are not synced?

zealous lance
naive briar
naive briar
zealous lance
# buoyant quail Just your commands are not synced?

i used this code to sync it ```@client.command()
@commands.guild_only()
@commands.is_owner()
async def sync(
ctx: Context, guilds: Greedy[discord.Object], spec: Optional[Literal["~", "", "^"]] = None) -> None:
if not guilds:
if spec == "~":
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "
":
ctx.bot.tree.copy_global_to(guild=ctx.guild)
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "^":
ctx.bot.tree.clear_commands(guild=ctx.guild)
await ctx.bot.tree.sync(guild=ctx.guild)
synced = []
else:
synced = await ctx.bot.tree.sync()

    await ctx.send(
        f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}"
    )
    return

ret = 0
for guild in guilds:
    try:
        await ctx.bot.tree.sync(guild=guild)
    except discord.HTTPException:
        pass
    else:
        ret += 1

await ctx.send(f"Synced the tree to {ret}/{len(guilds)}.")```
zealous lance
buoyant quail
#

Wait some time after syncing ¯_(ツ)_/¯

zealous lance
dusk dagger
glad cradle
zealous lance
#

bruuhhh why doesnt it work 💀

slate swan
buoyant quail
zealous lance
buoyant quail
#

hybrid_group works absolutely fine without fallback by me (and it should)

zealous lance
# buoyant quail `hybrid_group` works absolutely fine without `fallback` by me (and it should)

can u test my full code?

import discord
from discord.ext import commands
from typing import Union, Literal, Optional
from discord.ext.commands import Greedy, Context

intents = discord.Intents.default()
intents.members = True
intents.message_content = True
intents.bans = True
intents.guilds = True
intents.reactions = True
intents.presences = False

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


@bot.event
async def on_ready():
    await bot.change_presence(activity=discord.Game(name="test"))
    print("Bot started succesfully!")




@bot.hybrid_group()
async def server(ctx):
    guild = ctx.guild
    if guild:
        embed = discord.Embed(title=f'Server Info - {guild.name}', color=discord.Color.blue())
        embed.add_field(name='Server ID', value=guild.id, inline=False)
        embed.add_field(name='Owner', value=guild.owner.mention, inline=False)
        embed.add_field(name='Member Count', value=guild.member_count, inline=False)
        await ctx.send(embed=embed)
    else:
        await ctx.send("This command can only be used in a server.")





@bot.command()
@commands.guild_only()
@commands.is_owner()
async def sync(
    ctx: Context, guilds: Greedy[discord.Object], spec: Optional[Literal["~", "*", "^"]] = None) -> None:
    if not guilds:
        if spec == "~":
            synced = await ctx.bot.tree.sync(guild=ctx.guild)
        elif spec == "*":
            ctx.bot.tree.copy_global_to(guild=ctx.guild)
            synced = await ctx.bot.tree.sync(guild=ctx.guild)
        elif spec == "^":
            ctx.bot.tree.clear_commands(guild=ctx.guild)
            await ctx.bot.tree.sync(guild=ctx.guild)
            synced = []
        else:
            synced = await ctx.bot.tree.sync()

        await ctx.send(
            f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}"
        )
        return

    ret = 0
    for guild in guilds:
        try:
            await ctx.bot.tree.sync(guild=guild)
        except discord.HTTPException:
            pass
        else:
            ret += 1

    await ctx.send(f"Synced the tree to {ret}/{len(guilds)}.")





with open("token.txt", "r") as token_file:
    token = token_file.read().strip()

bot.run(token)```
buoyant quail
#

hybrid_group shouldn't be a command

zealous lance
#

wym by that?

buoyant quail
#

you are making it as server is a command

#

it shouldn't be

#

group server means that you have commands like server something not just server

zealous lance
buoyant quail
#

fallback adds an extra command

buoyant quail
#

wdym

#

hybrid_command will give you just one command server (prefix + slash)

zealous lance
#

ooooooooh

#

@buoyant quail ty XDD

#

@buoyant quail do i need to resync the bot every time it joins a server?

slate swan
#

no

zealous lance
gloomy dune
#

guys this codes why doesnt work:


@bot.hybrid_command()
async def naber(ctx):
    await ctx.reply("hi")


@bot.tree.command()
async def aber(interaction: discord.Interaction):
    await interaction.response.send_message("hi1")
buoyant quail
#

doesn't work doesn't define the problem

#

this part of code is absolutely correct

gloomy dune
#

umm i mean when i try /naber or /aber thats doesnt see in "slash pannel?"

buoyant quail
#

Did you sync the commands?

gloomy dune
#

idk how can ı

buoyant quail
thin raft
#

That looks like the bots in here

buoyant quail
#

I guess it was to show an example

#

But funny if not

gloomy dune
#

yes its for example

thin raft
#

I can't understand what he meant

buoyant quail
#

Described what slash panel is

Or, if you mean the whole question - the commands don't show up

gloomy dune
#

xd idk how can ı mean it

thin raft
#

That i got decapitated

potent mulch
#

Got this error:

Traceback (most recent call last):
  File "C:\Users\simoc\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\simoc\OneDrive\Desktop\Comune di Roveto\DiscordBot\Comune di Roveto, Regione Toscana V2\bot_v2.py", line 45, in on_message
    if message.attachment:
       ^^^^^^^^^^^^^^^^^^
AttributeError: 'Message' object has no attribute 'attachment'

I'm trying to see if a message has a photo or not.
The code i actually have:

@bot.event
async def on_message(message):
    if message.attachment:
        await message.channel.send(content=message.attachments[0].url)
slate swan
#

!d discord.Message

unkempt canyonBOT
#

class discord.Message```
Represents a message from Discord.

x == y Checks if two messages are equal.

x != y Checks if two messages are not equal.

hash(x) Returns the message’s hash.
slate swan
#

Look what attributes it has

potent mulch
#

alr

#

don't actually understand ngl

slate swan
#

Message object does not have .attachment attribute

slate swan
potent mulch
#

ok but, how do i get attachment

#

oh wait

#

solved, thanks lol

hasty pike
#

Long time no see

harsh orbit
#

Is this legal?

potent mulch
#

ye (ig)

harsh orbit
#

How to use it

#

Is there a doc for it?

potent mulch
#

idk

hexed gorge
shrewd apex
#

u add those scopes to the bot when requesting oauth and granting perms

harsh orbit
#

I know

#

But how to use them in a project?

shrewd apex
shrewd apex
#

meaning u make some sort of dashboard website

harsh orbit
#

So?

#

Can give me a doc for this thing?

shrewd apex
#

its in discord developer docs

harsh orbit
#

Requests?

shrewd apex
#

just check the oauth section

harsh orbit
#

In discord developers or where?

slate swan
#

Discord manages that how could it be illegal

harsh orbit
#

How to use it?

#

I just saw it in the oath generator

#

But no explain how to use it in the project

glad cradle
#

yeah you need a library that supports Oauth2

#

there are some extensions for that

harsh orbit
#

Can you give me some?

#

Names

#

Or docs

harsh orbit
buoyant quail
#

Raw requests : )

harsh orbit
#

Requests need to access for token

buoyant quail
#

?

#

You need the token anyways

harsh orbit
#

There is something called user key or IDK what is but when the user authorize in a bot have a condition of join servers for you you can get it

buoyant quail
#

Maybe some another key, doesn't matters

#

What will be the difference between raw requests and something else

#

If libraries are just sending requests

harsh orbit
#

When someone athorize in the bot, you get this thing

glad cradle
#

brooooo

harsh orbit
harsh orbit
glad cradle
harsh orbit
#

It's public project

#

But you can't make any thing with this

#

Cause this users didn't authorized in your bot

buoyant quail
harsh orbit
#

You never used this before?

buoyant quail
#

Nope

#

Yeah, it doesn't seem popular

#

The most popular library i found has 16 stars

harsh orbit
#
  • is there a way to convert a JavaScript code to Py
    Cause there are too many bots using this but all of them in JavaScript
buoyant quail
harsh orbit
#

IDK anything in java

buoyant quail
#

it's kinda same

harsh orbit
#

I saw something called js2py

buoyant quail
#

from what i see it can only execute it and extract resulting output, variables and so on

#

not make a python code

#

HAHHAHAH

#

lmao

#

i found some "Online JavaScript to Python Converter"

harsh orbit
#

Not working in big codes

buoyant quail
#

not working at all

harsh orbit
#

Nice

#

Also chatGBT makes this but it trash

sick birch
#

There are probably transpilers that might do a better job

#

But would recommend just writing it by hand

harsh orbit
sick birch
#

learn it

#

luckily not knowing something is usually the easiest problem to fix 😉

buoyant quail
#

You do
You already know variables, some operations with numbers, strings and so on

buoyant quail
#

But it uses variables

harsh orbit
#

And I see a wired things

#

Like variable start with var

#

And why every line in code start with consest or IDK what

buoyant quail
harsh orbit
buoyant quail
#

You understood that variables are starting with var

#

var is not problem for you

harsh orbit
#

But not a full language

buoyant quail
#

that's true

#

but a lot of it already

#

and a lot of things just have some different syntax, but are also same

harsh orbit
#

Yup

#

IDK

#

Maybe I should learn it

buoyant quail
#

Motivating to learn js on python server

harsh orbit
obsidian fable
#
async def gpt4(interaction: discord.Interaction, query: str, context: Literal['8k', '32k']):

how can I make the context option optional?

obsidian fable
obsidian fable
slate swan
#
def f(arg: str = "default")
obsidian fable
#

thank you

slate swan
#

yo is there a reason that in discord.py this code isn't working?:

@bot.event
async def on_member_update(before, after):
    print(after.activities.CustomActivity.name)
#

the bot has the right intents, is only in my server, and i've changed my status and nothing changes

hasty pike
#

@slate swan Downie

slate swan
#

?

hasty pike
#

Can i login multiple bots using loop?

#

And task

#

🙂

slate swan
#

i doubt using a loop

#

but using some threads prolly

hasty pike
#

I tried something but it took first of list

#

Rest were off

hasty pike
slate swan
#

!d threading.Thread

unkempt canyonBOT
#

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)```
This constructor should always be called with keyword arguments. Arguments are:

*group* should be `None`; reserved for future extension when a `ThreadGroup` class is implemented.

*target* is the callable object to be invoked by the [`run()`](https://docs.python.org/3/library/threading.html#threading.Thread.run) method. Defaults to `None`, meaning nothing is called.

*name* is the thread name. By default, a unique name is constructed of the form “Thread-*N*” where *N* is a small decimal number, or “Thread-*N* (target)” where “target” is `target.__name__` if the *target* argument is specified.

*args* is a list or tuple of arguments for the target invocation. Defaults to `()`.

*kwargs* is a dictionary of keyword arguments for the target invocation. Defaults to `{}`.
slate swan
#

thats literally all i know about threads so cant really help more

hasty pike
#

Oh

#

Thanks

#

But is there anything else you could tell me?

sick birch
#

You don't really need threads for this tbh

#

discord bots are asynchronous anyway

hasty pike
#

Then what option do i have?

sick birch
#

!d asyncio.create_task

unkempt canyonBOT
#

asyncio.create_task(coro, *, name=None, context=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task) and schedule its execution. Return the Task object.

If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name).

An optional keyword-only *context* argument allows specifying a custom [`contextvars.Context`](https://docs.python.org/3/library/contextvars.html#contextvars.Context) for the *coro* to run in. The current context copy is created when no *context* is provided.

The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError) is raised if there is no running loop in current thread.

Note

[`asyncio.TaskGroup.create_task()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.TaskGroup.create_task) is a newer alternative that allows for convenient waiting for a group of related tasks.
sick birch
#

Though I am not sure if there's many good reasons for wanting to run two bots at once in the same process

hasty pike
#

Tried this ngl

sick birch
#

This starts getting a bit deep into the event loop and asynchrony so would recommend getting comfortable before proceeding

#

the most straightforward is to just run the bots in their own processes separately

hasty pike
#

Oh

sick birch
slate swan
#

everything under .start will never be called

#

so only first one will start

hasty pike
#

Sht I didn't know

#

I tried for loop too

#

Neither that worked

slate swan
sick birch
final iron
#

A specific image isn't loading in an embeds url, I don't know why but could it be too high quality?

#

The url is valid

#

I'm using

#

!d discord.Embed.set_image

unkempt canyonBOT
#

set_image(*, url)```
Sets the image for the embed content.

This function returns the class instance to allow for fluent-style chaining.
sick birch
#

client.run is not a coroutine

#

You are going to run into the same issue as before

#

client.start waits for the duration of the bot

hasty pike
#

I'm confused

glad cradle
#

you can run only 1 bot per process

hasty pike
sick birch
#

You technically can but there's no point

slate swan
#

any clue? @sick birch

slate swan
#

oh

#

but I need requests

#

is there a way around it

final iron
unkempt canyonBOT
#

Common data structures used by aiohttp internally...

final iron
#

Documentation is ass but 🤷‍♂️

#

!d aiohttp.ClientSession.request

unkempt canyonBOT
#
coroutine async-with request(method, url, *, params=None, data=None, json=None, cookies=None, headers=None, skip_auto_headers=None, auth=None, allow_redirects=True, ...)```
Performs an asynchronous HTTP request. Returns a response object.
final iron
#

I often have large texts like these in my embeds, how would yall recommend I format it to make it readable while not taking an entire page?

slate swan
#

you can reduce number of Ls

upbeat gust
final iron
#

It's just an example of the output

final iron
upbeat gust
#

I don't mean do this like programatically

final iron
#

Oh, it would have to be

#

There's millions of different outputs so it's impossible to anticipate

#

For a solution to work it would have to be 100% automatic, here's another example of a large output

upbeat gust
#

wtf

final iron
#

It's scraping data off a website, that's why it's so weird

upbeat gust
#

makes sense

final iron
#

And deleting the repeating words isn't a good solution either

slate swan
#

i need someone to review this code ```py
@commands.Cog.listener("on_command_error")
@commands.Cog.listener("on_application_command_error")
async def log_exceptions(self, context: commands.Context | nextcord.Interaction, exception: Exception):
if isinstance(exception, commands.CommandNotFound):
return

if not isinstance(context, commands.Context | nextcord.Interaction):
    raise TypeError(f"Unknown context type: {type(context)}")

if isinstance(exception, commands.CommandError):
    exception = exception.original

if isinstance(context, commands.Context):
    invoker = context.author
    created_at = context.message.created_at
    name = f"`{context.command.qualified_name}`"
    _args = context.args[2:]  # ignore self and ctx
    _kwargs = context.kwargs

    args = " ".join(_args + [f"{k}={v}" for k, v in _kwargs.items()])

elif isinstance(context, nextcord.Interaction):
    invoker = context.user
    created_at = context.created_at
    name = context.application_command.get_mention()
    _options = context.data.get("options")

    args = " ".join(f"{option['name']}={option['value']}" for option in _options)

guild = context.guild
channel = context.channel

tb = "".join(traceback.format_exception(type(exception), exception, exception.__traceback__))

_log_channel = self.bot.get_channel(1096144011460358315)
embed = (
    nextcord.Embed(
        title="Exception occured!",
        color=nextcord.Color.red(),
        timestamp=created_at,
    )
    .add_field(
        name="Invokation details",
        value=(
            "backticks...yaml\n"
            f"Guild: {guild.name} ({guild.id})\n"
            f"Channel: {channel.name} ({channel.id})\n"
            f"Invoker: {invoker.name} ({invoker.id})\n"
            "backticks..."
        ),
        inline=False,
    )
    .add_field(
        name="Command details",
        value=(
            f"**Command**: {name}\n"
            f"**Arguments**: `{args}`\n"
            f"**Executed at**: {format_dt(created_at)} ({format_dt(created_at, style='R')})\n"
        ),
        inline=False,
    )
)
if len(tb) < 4080:
    embed.description = f"backticks...py\n{tb}backticks..."
    await _log_channel.send(embed=embed)
    return

await _log_channel.send(
    "Traceback is too long to embed. Uploading as a file.",
    embed=embed,
    file=nextcord.File(StringIO(tb), filename="traceback.txt"),
)
upbeat gust
upbeat gust
slate swan
#

ah hell nah not pep 9001

final iron
#

Chinese marketplaces

upbeat gust
#

same point

slate swan
#

pep 9001 style guide not using in this project yk yk

final iron
#

Yeah, I've noticed that as well

#

I've had to introduce a bit of hard coding as the headers for the sizes of the item vs the color aren't always accurate

#

For the majority of the items their IDs are 0 for color and 1 for sizes, but not all

#

So that messes it up

final iron
#

Real question

slate swan
#

just used to it for 2 years

#

when discord.py was discontinued i chose it and im still with it 🫡

final iron
#

I used disnake and migrated back after Danny said he was working on discord.py again

slate swan
#

you see, i did not migrate

#

and im happy about it

final iron
#

Show an example of nextcord

slate swan
#
    @nextcord.slash_command(name="ping")
    async def _ping(self, interaction: nextcord.Interaction):
        await interaction.send(f"Pong! {round(self.bot.latency * 1000)}ms")
``` (this is in Cog)
#

normally you would do @bot.slash_command()

final iron
slate swan
#

not really if you look at it

#

the main difference is that nextcord auto syncs

#

and i very like it

final iron
#

Autosync is nice

#

I'm gonna need to make a command for it

slate swan
#

discord.py is the only framework i know that does not auto sync so

#

i dont know where this choice comes from

golden portal
#

how often do you change slash signature that you need auto sync tho?

slate swan
void mauve
slate swan
#

i also add some commands to test if something works

radiant patio
#

Hello everyone!

slate swan
#

especially when making error logger

void mauve
golden portal
golden portal
slate swan
void mauve
golden portal
#

auto sync do eats away API calls which i dont like

void mauve
slate swan
radiant patio
#

So I’m hoping I can find someone who can help me on my journey to help a friend. Long story short, I have a friend that’s been in my clan for well over a year now. He is an older gentleman, doctors told him he had 2 weeks to live, and here we are 2+ years later, hanging out together and having late night chats.
But he can’t speak to me. So I’m always reading out his messages.
Is there any way to code a bot to automatically speak what is being sent in the chat boxes?

slate swan
#

so had to change it few times

slate swan
unkempt canyonBOT
#

directories/discord/bot/cogs/setup_cmd.py line 36

bot.add_cog(CogName(bot))```
radiant patio
#

I really want to figure something out for him. And he has such an amazing attitude towards it. He says he wants a voice like Stephen Hawkins or Nicolas Cage lol

slate swan
#

he is awaiting the load_extension so

golden portal
#

true i keep forgetting this server have multiple types of discord.py forks

golden portal
slate swan
radiant patio
golden portal
#

o, not sure i've never tried tts related things

radiant patio
#

Oh well. Thanks for the help! Will continue the search.

final iron
#

You would have to find an async text-to-voice library

#

!pip aiogTTS

unkempt canyonBOT
#

A Python library to interface with Google Translate text-to-speech API

final iron
#

Last commit was over a year ago so hopefully it's still working

#

Seems like files are being saved locally but since it's only for 1 person it doesn't seem like it'll be much of an issue

slate swan
#

Run that in your ide

crisp valley
#

Correct way to define these image glpyh emojee things ?

#

No idea how this works

slate swan
#

It explains how to get string that will result in an Emoji on discord

crisp valley
#

I am trying to use the python emoji library to convert the shorthand to a unicode string that discord will accept

#

So far it is unclear what shorthand I actually need to use, I guess I can just skip that process and figure out the strings that discord requires

obsidian fable
#
@ai.command(name="sdxl", description="Generate images with DALL-E")
@app_commands.describe(prompt = "The prompt to generate", width = "Width of the image", height = "Height of the image")
async def sdxl(interaction: discord.Interaction, prompt, width: Literal[512, 1024] = 512, height: Literal[512, 1024] = 512):
    await interaction.defer(ephemeral=False)
    try:
        await interaction.send(sdxl(prompt, width, height))
    except Exception as e:
        await interaction.send(f"Cannot generate with SDXL. \n{e}")
        traceback.print_exc()

E:\files\bot-py\extension\ai.py:42: RuntimeWarning: coroutine 'Command.__call__' was never awaited await interaction.send(sdxl(prompt, width, height))

#

why do I have to await sdxl?

import replicate

def sdxl(prompt, width, height):
    output = replicate.run("stability-ai/sdxl:d830ba5dabf8090ec0db6c10fc862c6eb1c929e1a194a5411852d25fd954ac82",
                           input={"prompt": prompt, "width": width, "height": height}
                           )
    image_url = output[0]
    return image_url
shrewd apex
#

that would recurse infinitely

#

oh

crisp valley
shrewd apex
#

u have 2 functions

#

sdxl def and async

#

@obsidian fable rename the function ur calling

obsidian fable
#

oh so I have to name the async def part

#

I never noticed that thank you

opaque parcel
#

how to solve this error ?

naive briar
#

Await the load_extension function

opaque parcel
opaque parcel
naive briar
#

I meant this one

opaque parcel
#

ohh okk my bad

shrewd apex
opaque parcel
glad cradle
#

it was discontinued but they started again the development

opaque parcel
shrewd apex
#

dpy

opaque parcel
#

okay

opaque parcel
# shrewd apex dpy

can you help me in another thing like i wanna create a presonal music bot for my server so how to create it like i've searching for last 2-3 days but idk why all the ways are not working correctly, can you help me like how should i work on it?

shrewd apex
#

look into soundcloud

#

some grayer areas are wavelink/lavarel

#

it uses ytdl underneath iirc tho 😔

harsh orbit
#

When I make 2 checks like @has_role & @has_permissions The user of the command need to have them both
How I can make it should have only one
Like if you have the role without the permissions you can use it and if you have the permissions without the role also you can use it

buoyant quail
#

!d discord.ext.commands.check_any

unkempt canyonBOT
#

@discord.ext.commands.check_any(*checks)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that is added that checks if any of the checks passed will pass, i.e. using logical OR.

If all checks fail then [`CheckAnyFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckAnyFailure) is raised to signal the failure. It inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).

Note

The `predicate` attribute for this function **is** a coroutine.

New in version 1.3.
harsh orbit
#

I put @has_permisssion in the coro?

#

Or any check

#

In coro?

buoyant quail
#

any check

#

there is an example

ember mango
#

Hello How to add emoji by Id?

#

Why he did not Paste?

buoyant quail
#
:red_x_cross:
💣💣💣💣
buoyant quail
#

Is it a code block?

ember mango
buoyant quail
#

Then where it is

#

That background is not just message

ember mango
# buoyant quail Then where it is
        grid = [':smile: ',':red_x_cross: ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ','💣 ' ,'💣 ','💣 ','💣 ','💣 ','💣 ']
        already_used = []
buoyant quail
#

the message

buoyant quail
#

it's not just raw message

#

it has another background

ember mango
#

Emoji did nt work why?

buoyant quail
#

It is a code block

ember mango
buoyant quail
#
abc

is a code block

ember mango
#

how to fix this?

ember mango
buoyant quail
#

Send it as just text
without backticks

ember mango
#

One more no work why?

#

@buoyant quail

buoyant quail
ember mango
#

no work

eager mural
#

hello

eager mural
eager mural
#

help me plz

buoyant quail
ember mango
buoyant quail
#

Maybe not saved?

ember mango
#

bruh

ember mango
#

No work

buoyant quail
#

Check the emoji id

ember mango
#

my id emoji evrytime change why?

buoyant quail
#

It doesn't

#

You copied something wrong

ember mango
#

For example 💀

#

1143818446635802644 Look

buoyant quail
#

?

ember mango
#

Evrytime change

#

can you come my server test?

#

Evrytime change

#

idk why?

buoyant quail
#

invite

ember mango
eager mural
#

yes

rugged shadow
#

disnake ftw imo

glad cradle
#

yeah

finite sage
#

I have too problem. It say the token is invalid and intent are needed, but i check 10 times and all intent are correct and the token is correct

slow escarp
#

show code

opaque parcel
#

can we add multiple button using discord.py in an embed?

slate swan
#

Yes

opaque parcel
slate swan
ember mango
buoyant quail
ember mango
#

Cool ty

potent mulch
#

Ok, that actually crazy, when i start the bot and send a command on Discord, the Bot do nothing and the console give no error 🤔

buoyant quail
#

Maybe you didn't add any code except creating bot...?)
Show code

potent mulch
#

I have 2 Code, with commands and everything, both don't do anything

buoyant quail
#

Show them

potent mulch
#

i can't send txt file bruh

buoyant quail
#

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

potent mulch
#

bruh

#

i've done it, the bot still delete the message

buoyant quail
naive briar
#

Just paste the link

potent mulch
#

alr

naive briar
potent mulch
#

in the console there's no error :\

#

when i run the code

potent mulch
#

mh, don't understand

naive briar
#

Then read it again

potent mulch
#

still don't understand

buoyant quail
#

Then read it again

potent mulch
#

still, don't, understand

buoyant quail
#

Then ask what exactly you don'y understand

potent mulch
#

everything :|

#

i've removed the on_message part and it works, with it, it doesn't work

buoyant quail
#

Prefix commands are called from the on_message event
You did your own on_message event so nothing is calling the commands more
Link shows two ways to fix it

I can also give a third because you have a subclass:

class Bot(commands.Bot):
    # your code ...
    async def on_message(self, message):
        await super().on_message(message)
        # your code ...
potent mulch
#

mhh, but

class Bot(commands.Bot):
    # your code ...
    async def on_message(self, message):
        await super().on_message(#what does this message mean?)
        # your code ...
naive briar
#

Call the original on_message method of the commands.Bot class

#

!e

class A:
    def say(self):
        print("A")

class B(A):
    def say(self):
        super().say()
        print("B")

B().say()
unkempt canyonBOT
#

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

001 | A
002 | B
potent mulch
#

tf

#

alr, solved, thank you

young dagger
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

young dagger
buoyant quail
young dagger
#

Wierd

buoyant quail
#

Pycharm just uses your terminal

#

It doesn't do anything extra

#

You need to install what library need to be installed anyways
After that it will be possible to install it in pycharm too

buoyant quail
#

huh

#

nah it works

unkempt canyonBOT
#
Microsoft Visual C++ Build Tools

When you install a library through pip on Windows, sometimes you may encounter this error:

error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/

This means the library you're installing has code written in other languages and needs additional tools to install. To install these tools, follow the following steps: (Requires 6GB+ disk space)

1. Open https://visualstudio.microsoft.com/visual-cpp-build-tools/.
2. Click Download Build Tools >. A file named vs_BuildTools or vs_BuildTools.exe should start downloading. If no downloads start after a few seconds, click click here to retry.
3. Run the downloaded file. Click Continue to proceed.
4. Choose C++ build tools and press Install. You may need a reboot after the installation.
5. Try installing the library via pip again.

slate swan
#

@young dagger ^

slate swan
buoyant quail
#

skill issue ducky_beer

slate swan
#

blud you didnt know there is a tag for that

buoyant quail
#

😰

ember mango
#

A question is whether json is used as a database?

ember mango
buoyant quail
#

A lot of people use it but it is not database :p

ember mango
slate swan
lament depotBOT
slate swan
ember mango
#

..

ember mango
#

like date base

buoyant quail
slate swan
#

what do you mean by save command as json

ember mango
buoyant quail
#

No one will stop you from doing this

ember mango
#

like datebase

buoyant quail
#

what

ember mango
#

It's not like a database, but it should be

buoyant quail
#

json ~= dictionary/list

slate swan
#

if you really wanna stick with json format check out Mongo DB

#

it uses Documents that are in json format

ember mango
ember mango
fiery girder
#

i wanna add a function to my bot that whenever a new video get uploaded on my yt channel it will give a output

#

how do i do that

cloud dawn
fiery girder
#

the google article sucks and is too much complitcated

ember mango
#

When you done

fiery girder
#

hahaha so funny

ember mango
#

Lern discord or disnake

fiery girder
#

i cant stop laughing man

ember mango
fiery girder
#

sommon if i didnt knew python why tf will i be on discord-bots section making discord bots

ember mango
ember mango
#

and i answer your questionducky_lemon

ember mango
fiery girder
#

what error?

ember mango
fiery girder
ember mango
# fiery girder

Then we can help you if you have a problem with the code, not us creating it for you

fiery girder
#

i dont have a problem with code i just wanna know a good lib for getting notifies when i upload a new video gets uploaded on youtube

cloud dawn
fiery girder
#

i am starting to learn a bit of java

#

and c++

ember mango
cloud dawn
#

That's good, c++ is not very beginner friendly but spending time programming is a good start.

fiery girder
#

i forgot it now because i didnt continue coding and just stopped

cloud dawn
ember mango
#

If you learn python in my opinion
All languages will be easy

fiery girder
#

i like python syntax no ; no {} just peace

cloud dawn
fiery girder
#

python is easier then more language

#

most*

ember mango
fiery girder
#

html would be the easiest to start

ember mango
#

Python is great for hacks

cloud dawn
#

If you know both C and Java then you basically know almost every language. But then you also have SQL and other things.

ember mango
buoyant quail
cloud dawn
slate swan
buoyant quail
#

i'd even guess that it's youtube api

slate swan
#

yeah prolly exists

#

but how to use it and what endpoint would it be

#

no idea

buoyant quail
#

something like get all videos of author after some timestamp i guess

eager mural
#

hello and t it possible to make a handlerd python? or do the commands only in the main.py

fiery girder
fiery girder
vocal snow
#

similar to how discord.py is a wrapper for the discord api

unkempt canyonBOT
slate swan
#

no idea if it works but might be helpful

#

last commit month ago

finite sage
#

I find out why. It use api v6

velvet tinsel
#

I've this piece of code, but for some reason, it completely resets my balance if I run it. What's the issue?

@bot.tree.command(name="deposit", description="Dump your cash in the bank")
async def deposit(interaction: discord.Interaction, amount: int):
    async with bot.db.cursor() as cursor:
        await cursor.execute("SELECT wallet FROM bank WHERE user = ?", (interaction.user.id,))
        data = await cursor.fetchone()
        if amount > data[0]:
            await interaction.response.send_message("You not that rich.")
        
        res = await update_bank(interaction.user, amount)
        if res == 0:
            await interaction.response.send_message("You don't have an account. Run `/balance` to create one.", ephemeral=True)
        
        suc = discord.Embed(
            title="Success!",
            description=f"You deposited **${amount}** into your bank!",
            color=discord.Color.green()
        )
        await interaction.response.send_message(embed=suc)

update_bank function:

async def update_bank(user, amount):
    async with bot.db.cursor() as cursor:
        await cursor.execute("SELECT wallet, bank FROM bank WHERE user = ?", (user.id,))
        data = await cursor.fetchone()
        if data is None:
            await create_bal(user)
            return 0
        if amount > data[0]:
            return 1
        await cursor.execute("UPDATE bank SET wallet = ? AND bank = ? WHERE user = ?", (data[0] - amount, data[1] + amount, user.id))
    await bot.db.commit()   
fiery girder
#

!pypi google-api-python-client

unkempt canyonBOT
fiery girder
#

this is the one

velvet tinsel
#

... you mean languages as in programming languages, right?

fiery girder
#

yes

velvet tinsel
#

discord.py and discord.js would be different from each other

#

what language are you trying to use

fiery girder
#

python

#

duh

velvet tinsel
fiery girder
#

huh

velvet tinsel
#

documentation is for all languages not python specific

What are you looking for?

fiery girder
#

i am looking for a python sepcific documentatin

velvet tinsel
#

I won't question your weirdly worded question

velvet tinsel
fiery girder
#

simple thing google docs is confusing and dont give the answer as per shown and it dont show code so i cant test it or anthing neither pycharm shows it variable

velvet tinsel
#

google docs??

#

you mean the api doc?

slate swan
velvet tinsel
#

I'm very lost ATP

slate swan
#

"Intents" Object Has No Attribute "message_delete"

#

idk how to fix this

#

!d discord.Intents

unkempt canyonBOT
#

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

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

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

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

New in version 1.5.
slate swan
slate swan
ember mango
#

disnake.ext.commands.errors.MissingAnyRole: You are missing at least one of the required roles: '<disnake.ext.commands.slash_core.InvokableSlashCommand object at 0x7f6421839910>' How can fix error>?

slate swan
unkempt canyonBOT
slate swan
#

its in default intents anyway

#

my log thing isn't working, hm

#

what is not working about it?

#

it dosent send the message to the logs channel, when set

#

show code then

buoyant quail
slate swan
slate swan
buoyant quail
#
@commands.command()
async def a(ctx):
    ...

@commands.command()
@commands.has_any_role(a)
async def b(ctx):
    ...
slate swan
buoyant quail
#

¯_(ツ)_/¯

#

maybe he had like

role = 123

@commands.command()
async def role()
slate swan
#

we wont know until he provides code

buoyant quail
#

He disappeared

slate swan
#

dipped

#

other guy too

buoyant quail
#

xd

slate swan
buoyant quail
#

we are losing people

slate swan
buoyant quail
#

you checked it bad 👍

slate swan
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

slate swan
#
@bot.event
async def on_message_delete(message):
    channel_id = retrieve_channel_id(message.guild.id)
    
    channel = bot.get_channel(channel_id)
    
    if channel is not None:
        embed = discord.Embed(title="Deleted Message", description=f"Message deleted in #{message.channel.name}", color=discord.Color.red())
        embed.add_field(name="Author", value=message.author.mention, inline=False)
        embed.add_field(name="Content", value=message.content, inline=False)
        
        await channel.send(embed=embed)```
buoyant quail
#

retrieve_channel_id too

slate swan
#

huh

#

!d discord.ext.commands.Bot.get_channel

unkempt canyonBOT
slate swan
#

I don't get it

#

to ensure you have the channel object use this: py channel = bot.get_channel(...) or await bot.fetch_channel(...)

slate swan
slate swan
buoyant quail
#

retrieve_channel_id

#

bro
how did you broke your own code

slate swan
#

idk grizlaugh

slate swan
slate swan
unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 3, in <module>
003 |     if None + sex == None:
004 |        ~~~~~^~~~~
005 | TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'
buoyant quail
#

!e ```py
from fishhook import hook

@hook(type(None))
def add(self, other):
return

print(None + None)

unkempt canyonBOT
#

@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.

None
buoyant quail
#

Why does discord not make emoji only by id if it doesn't need the name?
![pithink](https://cdn.discordapp.com/emojis/652247559909277706.webp?size=128 "pithink") pithink
![something_random](https://cdn.discordapp.com/emojis/652247559909277706.webp?size=128 "something_random") pithink

slate swan
#

so its readable

zealous lance
#

how do i make that it will open a link when i click on a button?

naive briar
#

!d discord.ui.button pass the url argument

#

Ah, right

naive briar
unkempt canyonBOT
#

class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.

New in version 2.0.
ember mango
#
      name="staff_logs",
      description="Only satff can use it"
)
@commands.has_any_role(staff)
async def staff_logs (ctx, user: disnake.Member, id_member,  timeout: staff_logs, rasson, date , by: disnake.Member):
    await ctx.channel.send(f"{by}",embed=embed)
    print(by,"Timeout member")
buoyant quail
#

did what

#

that was an example of bad code

#

what is staff variable

ember mango
ember mango
buoyant quail
#

put an integer into staff variable

#

not something else

ember mango
buoyant quail
#

@commands.has_any_role(staff)

ember mango
buoyant quail
#

yes. what is inside staff

ember mango
#

I've done that before.

buoyant quail
#

?

ember mango
buoyant quail
#

answer my question finally lemon_pensive

ember mango
buoyant quail
#

What is inside staff variable

ember mango
#

?.............

buoyant quail
ember mango
#

yes

buoyant quail
#

Press ctrl + f and search for def staff

ember mango
buoyant quail
#

here we go

#

Your staff is not an integer

ember mango
#

..........

buoyant quail
#

It is your staff command

#

You redefined it

#

!e

x = 5

def x():
    ...

print(x)
unkempt canyonBOT
#

@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.

<function x at 0x7fbf3c7e0680>
ember mango
#

man I don't want to change staff positions.

naive briar
#

Just change the function's name then

ember mango
slate swan
#

yo, do you guys know how I would add a description for my hybrid_command? I don't want a description for the command itself, more like any arguments given to it

@bot.hybrid_command()
async def uptime(ctx):
    await ctx.send(embed=discord.Embed(title="Uptime", description=f"{round(time.time() - st)} seconds", color=discord.Color.green()))
#

this is a bad example because theres no args in this command but if there was how would I do it?

naive briar
#

!d discord.app_commands.describe

unkempt canyonBOT
#

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

Example:

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

ty

#

🙏

#

do you know how I could make it epheremal?

#

using hybrid_command

buoyant quail
#

!d discord.ext.commands.Context.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.

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

For interaction based contexts this does one of the following...
buoyant quail
#

ephemeral (bool) –

Indicates if the message should only be visible to the user who started the interaction. If a view is sent with an ephemeral message and it has no timeout set then the timeout is set to 15 minutes. This is only applicable in contexts with an interaction.

New in version 2.0.

cloud dawn
slate swan
#

this is only for use with hybrid_command

dusk dagger
cloud dawn
#

Didnt knew it had that arg, kinda cursed

sick birch
#

It should get its own class tbh

slate swan
buoyant quail
#

ClassThatStoresContextAndInteractionForHybridCommandsTogether

#

java be like

slate swan
buoyant quail
#

docstrings are not needed

#

just write good names

slate swan
#

did they reduce cooldown to 4 seconds brbrbrbr_animated ?

buoyant quail
#

idk

#

what it was?

slate swan
slate swan
slate swan
#

its called portmanteau nerdmoment

buoyant quail
#

Port Man Tea You

slate swan
zealous lance
#

should i make my bot disable the button after some time? if so how?

zealous lance
#

ty

final iron
#

Is there anyway to center a field in an embed?

cloud dawn
#

Set inline to true

final iron
#

Oh smart

#

How would the formatting be on mobile though

cloud dawn
cloud dawn
final iron
#

I'll test it in a bit

zealous lance
#

is it possible to add a enter in here? async def invite(ctx):

final iron
#

wdym add an enter

#

Add an argument for a user to use?

zealous lance
final iron
#

wdym enter

zealous lance
final iron
#

I still have no clue what you're asking

#

Add a space where

zealous lance
#

like: 'auto invite removal' and not like auto invite-removal

final iron
#

!d discord.ext.commands.command

unkempt canyonBOT
#

@discord.ext.commands.command(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command) or if called with [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.group), [`Group`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Group).

By default the `help` attribute is received automatically from the docstring of the function and is cleaned up with the use of `inspect.cleandoc`. If the docstring is `bytes`, then it is decoded into [`str`](https://docs.python.org/3/library/stdtypes.html#str) using utf-8 encoding.

All checks added using the [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
final iron
#

Try it and see if it works

#

Use the name arg

zealous lance
#

kk

zealous lance
final iron
#

You're using slash commands?

zealous lance
final iron
#

I don't believe it's possible then

zealous lance
#

like i also cant use bot in async

final iron
#

!d discord.app_commands.command

unkempt canyonBOT
#

@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
final iron
#

name arg

final iron
#

wdym

#

It'll have to be async or everytime something is run the entire bot will freeze

zealous lance
zealous lance
# unkempt canyon

and with this do i need to put it in the () from: @bot.hybrid_group?

#

or command

final iron
#

what

zealous lance
# final iron Share your code
@bot.hybrid_group(fallback="info")
async def alpra(ctx):
    support = Support()
    latency = round(bot.latency * 1000)
    embed = discord.Embed(title="Bot Information", description="", color=0x009cff)
    embed.set_author(name=bot.user.name, icon_url=bot.user.avatar.url)
    embed.add_field(name="Bot ping", value='<@' + str(bot.user.id) + '>', inline=False)
    embed.add_field(name="Bot ID", value=bot.user.id, inline=False)
    embed.add_field(name="Latency", value=f"{latency} ms", inline=False)
    creation_date = bot.user.created_at
    embed.add_field(name="Creation Date", value=creation_date.strftime("%B %d, %Y"), inline=False)
    embed.add_field(name="Creator", value="@sp1nkel", inline=False)
    await ctx.send(embed=embed, view=support)```
#

like i couldnt do alpra bot info and bot info also doesnt work

final iron
#

I'm so confused lmao

#

Read the Github for examples on slash commands

#

I have a feeling you haven't worked with them before

zealous lance
sick birch
#

You don't make one command with spaces in it

zealous lance
final iron
#

Also for next time, the way you speak is incredibly confusing and hard to follow

slate jackal
#

can discord bots not play audio anymore?

final iron
#

Doesn't dyslexia affect the way you read letters?

fiery salmon
#

Hi. I have an idea, trying to find best way to implement.

My users have items. They can /use item (e.g. /use VoterChip).
I want to make a way to have items effect other commands..

Such as /use BlindChip will make the /rob command a 100% success.

How should I implement this? Is this ok:
Create a DB table (ex: ActiveItems), then when people /use these type of items, it'll be appended to the table.
Then in the commands, like /rob, it'll search table for that user and that item

final iron
#

Seems good enough

#

Having a DB of active buffs, then when the command (rob) is run checking those active buffs and altering the result

fiery salmon
#

thank u for the validation!

obsidian fable
#

does anyone know why this is happening? I have a folder of functions in .\defs\, and I use for example from spotify_track import extract_first_artist_link to import functions from other files in the same folder

for other files I use for example from defs.spotify_artist import extract_artist_icon so that I can import but seems like I can't do that anymore?

    from spotify_base import embed_scrape
ModuleNotFoundError: No module named 'spotify_base'
eager mural
#

Hello I have a problem my ping command does not work can someone help me?

#
import discord
from discord.ext import commands

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

        @commands.Cog.listener()        
        async def on_ready(self):
            print("Bot is online !")

            @commands.command()
            async def ping(self, ctx):
                await ctx.send("Pong")

async def setup(bot):
    await bot.add_cog(ping(bot))```
twilit grotto
twilit grotto
eager mural
#

TYYYYYYYYYYYYYYYYYYYYYYYYY

final iron
#
import discord

from discord.ext import commands


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

    @commands.Cog.listener()        
    async def on_ready(self) -> None:
        print("Bot is online !")

    @commands.command()
    async def ping(self, ctx: commands.Context) -> None:
        await ctx.send("Pong")


async def setup(bot: commands.Bot):
    await bot.add_cog(Ping(bot))
#

Superior

#

I already asked yesterday but I want to see if somebody has solution. My bot will often send large amounts of text with a lot of repeating words because it's coming from a websites json data, does anybody have any idea how I could dynamically reduce the amount of unneccesary words?

#

Those are some examples

#

I could also share the json data if somebody wants to help me figure out a different solution

sick birch
buoyant quail
#

Try

from defs.spotify_base import embed_scrape
obsidian fable
final iron
#

Let me share the json data real quick

buoyant quail
obsidian fable
#

let me try again

obsidian fable
buoyant quail
#

Show that file

obsidian fable
#

let me check

#

oh

#

there isnt one

#

thank you

eager mural
#

can you help me ?

buoyant quail
#

lmao

#

you can't always ask to indent your code

#

it's the most basic thing in python

twilit grotto
#

your serverinfo function needs to be inside of your serverinfo class, and btw, you have to rename either the class or function

#

because you cant have both with both names

buoyant quail
eager mural
unkempt canyonBOT
#
Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

twilit grotto
# buoyant quail why not

because when he'd be adding the cog it would most likely be trying to use the function & not the class due to them having the same name

#

maybe im wrong, not entirely sure just bad practice imo

eager mural
buoyant quail
#

But yeah the naming isn't good

twilit grotto
#

no, you need to learn, learn how to simply indent your code and have it inside of the class

twilit grotto
buoyant quail
#

!resources to learn python pixels_snek_2

unkempt canyonBOT
#
Resources

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

twilit grotto
final iron
#

Right now I'm looping through ["prop_arr"]["propName"] to differentiate the names and the colors, then when I know it's a colour I access ["valueName"] and use that as the name
Here's a little snippet to show the structure: https://paste.pythondiscord.com/2CMQ

This is the entire JSON if you're willing to try and see if there's whole new way I could do it: https://paste.pythondiscord.com/G23A

@sick birch

#

The issue is, this has to be like 99% automatic

#

I could input the item id into a DB and when each command is run it'll check the item ID against the stored IDs, then execute the code to remove the excess letters

#

That would be possible, but I couldn't manually go through each individual link and choose the text

eager mural
final iron
#

It's the exact same code, the class and function names are just different

#

Well, it is changed, the code is following pep8

eager mural
#

Ohh thank

obsidian fable
#
    class ArtworkButton(ui.Button):
        async def callback(self, interaction: discord.Interaction):
                try:
                    result = songs_query(f"{artists} {name}")
                    print(result)
                    url = format_url(result)
                    await interaction.followup.send(url)
                except Exception as e:
                    await interaction.followup.send(f"Cannot find artwork for `{name}`.")
                    traceback.print_exc()
raise NotFound(response, data)

discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook

obsidian fable
#

no idea

#

it errors out when I click the button

final iron
#

Send the full traceback

obsidian fable
#

1s

buoyant quail
#

Are you sure that it's already responded?

#

If interaction is not responded you'd get "Unknown Webhook" by trying to send followup

obsidian fable
#

im pretty sure it is

buoyant quail
#

Actially

#

We have the code

buoyant quail
#

Only followup