#discord-bots

1 messages · Page 312 of 1

still spade
#

ayo tell me the documnatation for username one

vapid parcel
#

thats the best i can do sadly

vapid parcel
#

i dont have any of the documentations on me lol

naive briar
#

!d discord.Member.display_name get one

unkempt canyonBOT
#

property display_name```
Returns the user’s display name.

For regular users this is just their global name or their username, but if they have a guild specific nickname then that is returned instead.
vapid parcel
turbid condor
#

Getting a role object using id

vapid parcel
#

permissions?

turbid condor
#

add_roles

vapid parcel
#

ohhh

#

okay then.

still spade
#

finding for long time

turbid condor
still spade
#

tysm u r W

turbid condor
still spade
unkempt canyonBOT
turbid condor
#

Or

#

!d discord.User.global_name

unkempt canyonBOT
vapid parcel
#

global?

#

wtf

still spade
#

i want that each should come one by one not on one line how would i do that

naive briar
#

!d discord.Embed.add_field - set the inline argument to False

unkempt canyonBOT
#

add_field(*, name, value, inline=True)```
Adds a field to the embed object.

This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
naive briar
vapid parcel
vapid parcel
still spade
still spade
vapid parcel
#

that would be a display name lol

naive briar
vapid parcel
#

"Catlover" is your display name..?

#

like RejectModders is my display name

still spade
vapid parcel
#

user name is zac_the_catlover

naive briar
#

Nah, that's the global name, it will be used as the default server nickname

vapid parcel
#

yeah thats also display name 😭

#

im so confused rn 😭

turbid condor
still spade
naive briar
vapid parcel
#

display name

naive briar
#

Global name

vapid parcel
#
    embed.add_field(name="Username", value=member.name, inline=False)
    embed.add_field(name="Global Name", value=member.global_name, inline=False)
    embed.add_field(name="Display Name", value=member.display_name, inline=False)```
slate swan
#

The API returns both. Display name is deprecated and global name is the correct terminology

vapid parcel
#

ive always said display name 😭

#

ive never heard of global till now tbh

naive briar
#

It's new in discord.py 2.3, that's likely why

vapid parcel
#

So global would return Catlover, but if they changed their nickname in here display_name would display the new nickname correct?

slate swan
vapid parcel
#

or am i just on a whole different topic XD

still spade
#

2020-05-16 18:47:32.545000+00:00
2022-01-25 14:46:34.432000+00:00
i doesnt want the time how can i removed it ?

vapid parcel
#

or are yall saying global_name is the exact same at display_name

naive briar
#

No, no

vapid parcel
#

😭

naive briar
#

If you're talking about Discord, probably

vapid parcel
#

yes

naive briar
#

But I assumed that you're talking about discord.py

vapid parcel
#

yes

naive briar
#

!d discord.Member.display_name

unkempt canyonBOT
#

property display_name```
Returns the user’s display name.

For regular users this is just their global name or their username, but if they have a guild specific nickname then that is returned instead.
vapid parcel
#

i mean let me test it

naive briar
# unkempt canyon

Since Discord will use the user's global name as the default nickname for every server

vapid parcel
#

okay i was correct, display name is the nickname for that server

turbid condor
#

!d discord.utils.format_dt

vapid parcel
#

so global name is better i guess in a way, but i like display name

#

well thats nice to know now... didnt know about global lol

still spade
#

huh didnt get

turbid condor
#

!d discord.utils.format_dt

unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
still spade
#

also my roles are showing like this

slate swan
#

Because it's a list of roles objects

turbid condor
#

!d discord.Asset

unkempt canyonBOT
#

class discord.Asset```
Represents a CDN asset on Discord.

str(x) Returns the URL of the CDN asset.

len(x) Returns the length of the CDN asset’s URL.

x == y Checks if the asset is equal to another asset.

x != y Checks if the asset is not equal to another asset.

hash(x) Returns the hash of the asset.
vapid parcel
#

they look cleaner

still spade
#

yeh fixing

vapid parcel
#

@turbid condor

turbid condor
#

??

vapid parcel
#

give me a sec ffs

#

how could you make this remember giveaways, like ones that havent been finished yet

#

like if it restarted or crashed or sum

turbid condor
#

Not sure but you will need to create a task to check if the giveaway has ended and also store the end date and time of the give away in the db

slate swan
#

Database

stark nexus
#

Where should i put?

vapid parcel
vapid parcel
stark nexus
#

A panel my friend hosted for me

vapid parcel
#

weird...

stark nexus
#

Why?

vapid parcel
#

never seen the website before

stark nexus
#

At least it will auto keep alive

turbid condor
vapid parcel
#

i have a host too

#

which is bot hosting net

#

idk if its the best, but its free :)

#

im poor 😭

#

@turbid condor rate my credits command :)

turbid condor
#

Haven't seen it

vapid parcel
#

and rate my status command

turbid condor
#

Make everything inline = false for credits

vapid parcel
#

and it does to much XD

#

i have to add this so discord server doesnt inline with special thanks to

embed.add_field(name="\u200b", value="\u200b", inline=False)
turbid condor
#

The credits won't look good on mobile

vapid parcel
#

it never does

#

mobile = poopy

#

also uh

#

can you tell me if this is correct..?

#

    latency = round(bot.latency * 1000)

    server_count = len(bot.guilds)
    user_count = len(bot.users)
    command_count = len(command_list)

    cpu_usage = psutil.cpu_percent(interval=1)
    ram_usage = psutil.virtual_memory().percent
    disk_usage = psutil.disk_usage('/')

    network_stats = psutil.net_io_counters()
    network_inbound = network_stats.bytes_recv
    network_outbound = network_stats.bytes_sent```
#

are these correct or false?

#

idk if psutil is good, but ive been using it for the cpu and stuff like that

#

@turbid condor ^

turbid condor
#

Its good

vapid parcel
#

so it is calculating correctly?

turbid condor
#

Yes

vapid parcel
#

oh okay then

#

@turbid condor can i send you some code in dms and you review it? rather not send it here XD

turbid condor
#

Just put it on GitHub and share a link

#

I'll review it when free

vapid parcel
#

i dont use GitHub XD, ill just send a paste okay?

turbid condor
#

You should if you are looking to get into coding it is a good thing to save your code

vapid parcel
#

yeah ill do that some other time XD

solemn gust
turbid condor
#

Seems like your bot is using more disk then you have

#

Try running it on pc or use pydroid app

final iron
slate swan
#

very rules following

solemn gust
final iron
#

Rule 5

#

TOS

solemn gust
#

Where

slate swan
#

!rule 5

unkempt canyonBOT
#

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

slate swan
#

here

still spade
#

@vapid parcel

like how r u doing

embed.add_field(name="User creation date",value=formatted_creation_date,inline=False)
 #formatted_creation_date = format_dt(ctx.author.created_at, style='F')
vapid parcel
#
    if ctx.guild and member.guild == ctx.guild:
        embed.add_field(name="Joined Server", value=f'<t:{str(member.joined_at.timestamp()).split(".")[0]}:R>', inline=False)
    embed.add_field(name="Account Created", value=f'<t:{str(member.created_at.timestamp()).split(".")[0]}:R>', inline=False)```
still spade
#

uhh

vapid parcel
#

XD

#

i use timestamps

still spade
#

i m also using tho the idk which way is correct

#

so check mine

vapid parcel
#

?

#

is there an issue?

#

if it works, then it works?

#

not my problem

#

cry abt it ig

still spade
#
embed.add_field(name="User creation date",value=formatted_creation_date,inline=False)
 formatted_creation_date = format_dt(ctx.author.created_at, style='F')
kind roost
#

do you have a code for slash ban kick ect commands please

slate swan
still spade
slate swan
unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 6, in <module>
003 |     increment()
004 |   File "/home/main.py", line 4, in increment
005 |     counter += 1
006 |     ^^^^^^^
007 | UnboundLocalError: cannot access local variable 'counter' where it is not associated with a value
slate swan
#

you are trying to access a varriable not defined in your scope

final iron
unkempt canyonBOT
#

@slate swan :warning: Your 3.12 eval job has completed with return code 0.

[No output]
slate swan
#

blud really suggests using globals

still spade
slate swan
unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.

1
slate swan
#

suggesting to use globals isnt a help at all

final iron
#

Shouldn’t be using globals like this

vapid parcel
#

Bro was talking shit and now hes getting shit talked 😭

slate swan
#

you dont care then why you help

still spade
final iron
#

💀

turbid condor
#

Passing 1 as an argument is better

#

Or counter in this case

vapid parcel
#

💩 code

still spade
#

how can i do like this like if we mention then it aslo give other user info

final iron
still spade
#

Like when i mention other user aswell for ex
!userinfo @still spade
Like this it shows other user info aswell

hushed galleon
#

presumably whoever was mentioned?

vapid parcel
#

i showed him this, and he wanted to copy and idc if he does

#

but im sure thats what he means

final iron
#

Discord already shows all that 🤷‍♂️

vapid parcel
#

nuhuh

vapid parcel
fiery salmon
sick birch
pulsar lance
#

=hellp

#

hello

oak abyss
#

does anyone want to make a bot together

vapid parcel
vapid parcel
oak abyss
#

we can see, ive worked with multipurpose bots

#

i can make game, utilities, music, moderation and all types of commands

oak abyss
#

wtv type we do

vapid parcel
#

music cant work

#

no app is gonna allow that

#

you will break ToS in some way

oak abyss
#

hm

#

i can help you dev unibot?

vapid parcel
#

YouTube, Spotify, sound cloud, all off the list lol

vapid parcel
oak abyss
vapid parcel
#

they closed their api

oak abyss
vapid parcel
#

so its off the limits now

oak abyss
vapid parcel
#

i have a video on it

#

i do have music in my bot, but it will be removed soon, because it breaks youtubes ToS and i didnt know that

oak abyss
#

hmm

#

can we move this to dms?

vapid parcel
#

sure

still spade
oak abyss
#

does anyone want to work on a discord bot project?

fiery girder
#

what r you working at rn

oak abyss
fiery girder
#

wdym

#

you must have a bot or two

#

if you asking people to work with u

#

@oak abyss ??

oak abyss
fiery girder
#

oh

#

sure but i need to see if you are capable enough

#

you can come on dms if you want

#

@oak abyss ??

oak abyss
#

ive prob got more experience then you buddy

#

anyways yes dms

fiery girder
#

why did you remove friends request?

#

why you blocked me @oak abyss

oak abyss
#

add me bro

night crater
vapid parcel
#

Sketchy shit..

still spade
#

ahah

final iron
quick mason
#

Is there any place where i can refer to someone else's discord bot text based game?

graceful ermine
#

How could I fix this?

Traceback (most recent call last):
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 828, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\berka\Desktop\folder\main.py", line 96, in post
    await interaction.response.send_modal(modal=Modal)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: InteractionResponse.send_modal() got some positional-only arguments passed as keyword arguments: 'modal'

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

Traceback (most recent call last):
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'post' raised an exception: TypeError: InteractionResponse.send_modal() got some positional-only arguments passed as keyword arguments: 'modal'```
#
randmon_number = random.randint(1, 1000000)


class Modal(discord.ui.Modal):
    def __init__(self):
        super().__init__(
            "Post"
        )

        self.emworks = discord.ui.TextInput(label="Commission", min_length=5, max_length=1500, required=True, placeholder="write here!", style=discord.TextStyle.paragraph)
        self.add_item(self.emworks)
        


    async def on_submit(self, interaction: discord.Interaction) -> None:
        work = self.emworks.value



        async with self.bot.db3.cursor() as cursor:

            cursor.execute("INSERT INTO a (number, user, text) VALUES (?, ?, ?)", (randmon_number, self.emworks.placeholder, interaction.user.id))
            
            
            await self.bot.db3.commit()



        channel = await self.bot.get_channel(1066505917929111587)


        await channel.send(work)


@bot.command(name="sync2")
async def sync2(ctx):
    await bot.tree.sync()
    print("This command work")
    await ctx.send("all commands should be synced")


@bot.tree.command(name="post", description="Post's your commission")
async def post(interaction: discord.Interaction):

    




    await interaction.response.send_modal(modal=Modal)
        

        ```
pallid meadow
#

Last line interaction.response.send_modal(Modal())

#

I’m on mobile right now so the code doesn’t really make sense to me but that’s why I got based off your trace back error

final iron
graceful ermine
#

error*

#
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 828, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\berka\Desktop\folder\main.py", line 96, in post
    await interaction.response.send_modal(modal=Modal())
                                                ^^^^^^^
  File "C:\Users\berka\Desktop\folder\main.py", line 52, in __init__
    super().__init__(
TypeError: Modal.__init__() takes 1 positional argument but 2 were given

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

Traceback (most recent call last):
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'post' raised an exception: TypeError: Modal.__init__() takes 1 positional argument but 2 were given```
#
randmon_number = random.randint(1, 1000000)


class Modal(discord.ui.Modal):
    def __init__(self):
        super().__init__(
            "Post"
        )

        self.emworks = discord.ui.TextInput(label="Commission", min_length=5, max_length=1500, required=True, placeholder="write here!", style=discord.TextStyle.paragraph)
        self.add_item(self.emworks)
        


    async def on_submit(self, interaction: discord.Interaction) -> None:
        work = self.emworks.value



        async with self.bot.db3.cursor() as cursor:

            cursor.execute("INSERT INTO a (number, user, text) VALUES (?, ?, ?)", (randmon_number, self.emworks.placeholder, interaction.user.id))
            
            
            await self.bot.db3.commit()



        channel = await self.bot.get_channel(1066505917929111587)


        await channel.send(work)


@bot.command(name="sync2")
async def sync2(ctx):
    await bot.tree.sync()
    print("This command work")
    await ctx.send("all commands should be synced")


@bot.tree.command(name="post", description="Post's your commission")
async def post(interaction: discord.Interaction):

    




    await interaction.response.send_modal(Modal())
        

        ```
vapid parcel
#

drugs

vapid parcel
#

if it thinks its a virus?

#

i kinda made my own for that, if it starts with www or https or http it will scan it through virus total, if it thinks its a virus then it deletes it, there might be a lot of fake flags but i think its pretty cool

mystic marsh
#

Don't call it like that, its not how it works.

cursive bane
#

Can I get the command itself from a slash command (hybrid_command)?

ctx.message.content works when the command is called via a prefixed command but is blank when the command is called via a slash command.

mystic marsh
cursive bane
#

I have a command called /when, when users call it the bot replies with the time difference to a predetermined date

When using prefixed commands i had .when reply in all lowercase and .WHEN reply in all uppercase. I am running into issues having uppercased commands within my slash commands so I was instead looking to get command itself.

I can get the command typed easily when its a prefix command, but I cannot find a way to get it when its a slash command

https://xyproblem.info/

golden portal
golden portal
vapid parcel
#

drugs

cursive bane
golden portal
#

welcome

nova vessel
golden portal
slate swan
#

``line 4, in <module>
from discord_slash import SlashCommand
ModuleNotFoundError: No module named 'discord_slash'`

i tried to fix it still not working

#

`from discord.ext import commands
import discord, string, random, os, json, mysql.connector
from discord.ext import commands
from discord_slash import SlashCommand

intents = discord.Intents.default() # You can adjust these based on your bot's needs
intents.typing = False
intents.presences = False

client = commands.Bot(command_prefix="/", intents=intents)
slash = SlashCommand(client, sync_commands=True) # Initialize SlashCommand extension`

anyone help plz

#

Don't use that module if you already use discord.py

#

discord.py has built-in support for slash commands so you don't need anything else

slate swan
#

should i remove from discord_slash import SlashCommand

#

Remove everything related to discord_slash

slate swan
stark nexus
#

Is it normal that drugdown menu only can use once?

turbid condor
#

No you can use it multiple times

slate swan
#

😭 idk why

#

Continue reading the page

#

Especially the syncing part

slate swan
vapid parcel
#

is 30 days good..?

vapid parcel
#

do most bots do 30 days or what? i kinda wanna know what most bots do for security reasons?

turbid condor
#

It's your choice how much age you want the account to be

vapid parcel
#

Oh this guy

#

this DUDE

vapid parcel
turbid condor
#

Yup

#

!d discord.Interaction

unkempt canyonBOT
#

class discord.Interaction```
Represents a Discord interaction.

An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.

New in version 2.0.
turbid condor
#

Error is pretty self explaining

#

And slash command in discord.py use interaction instead of ctx

brazen raft
#

You named it ctx instead of interaction and now it's complaining about not knowing what interaction is

brazen raft
#

Are you referring to interaction.response.send_message?

shrewd fjord
#

interaction.user.mention?

#

...

naive briar
#

What is not working specifically?

shrewd fjord
#

catty .-.

naive briar
#

Hi 🐈

shrewd fjord
#

how are you? Cosy_a_hehe

#

oh btw, are you familiar with disnake interactions?

naive briar
shrewd fjord
shrewd fjord
#

!d disnake.MessageInteraction

naive briar
#

I never used disnake, so no

unkempt canyonBOT
#

class disnake.MessageInteraction```
Represents an interaction with a message component.

Current examples are buttons and dropdowns.

New in version 2.1.
shrewd fjord
#

cant seem to find view property from anywhere

shrewd fjord
#

!d discord.Interaction.defer first use this on top of the code

unkempt canyonBOT
#
Naw.

No documentation found for the requested symbol.

shrewd fjord
#

whoa

naive briar
#

You need to defer the intersection if you need more time to respond

#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

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

Defers the interaction response.

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

This is only supported with the following interaction types...
shrewd fjord
#

yeah forgor

#

!d discord.Interaction.followup then use this instead of send_message

unkempt canyonBOT
vapid parcel
#

hey

#

is a serverlist against ToS?

#

doesnt give an invite, just shows the servers the bot is in.

naive briar
#

Should be fine with just member counts

vapid parcel
#

okay so thats good?

#

cuz i know if it makes an invite and invites you to all the servers it breaks the privacy ToS or whatever

naive briar
#

!ytdl ducky_sphere

unkempt canyonBOT
#
Our youtube-dl, or equivalents, policy

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)
vapid parcel
#

this is breaking youtubes ToS

#

we cant help you here if you are breaking ToS in some way

#

yeah

#

when i heard abt it breaking ToS i was sad, i had a whole bass booster for it a volume control and like everything

#

i was really sad :/

#

yep, but soundcloud you could use, but api is closed so you are really limited ig

naive briar
#

You can't? pithink

#

I remember you can accept discord.File or discord.Attachment for the user to input files

vapid parcel
#

its discord.File

#

ye

naive briar
#

Use it as a typehint

brazen raft
#

Use asyncio.subprocess.create_subprocess_exec instead of subprocess.run. You should also probably find asynchronous alternatives for other operations you're doing there

vapid parcel
shrewd fjord
#

!pip strmath

unkempt canyonBOT
#

A module for evaluating math expressions without eval()

vapid parcel
#

thats cool

brazen raft
#

Aren't they

shrewd fjord
#

but whenever i do something like 9**99999999 bot crashes,,, i was thinking to do something with asyncio.wait_for then use 3 second or n second tmeout

vapid parcel
#

im just saying its against ToS we cant help them

#

but yes, they would use ffmpeg

shrewd fjord
#

do yk if it is possible?

brazen raft
#

I thought they said they were going to provide the bot with a file instead of a YouTube URL

#

YouTube allows human users to download content as far as I know

shrewd fjord
#

not anymore

vapid parcel
shrewd fjord
#

you need yt premium

vapid parcel
#

just read it...

brazen raft
#

Why is the download button still on the platform

vapid parcel
#

premium

brazen raft
vapid parcel
#

youtube just being an L

shrewd fjord
#

real

vapid parcel
#

like normal.

brazen raft
#

In any case the command is still ok if it accepts a legal file, no?

vapid parcel
#

"we lose money" not like you are losing 10b a year bro 😭

brazen raft
#

It could be any file

naive briar
brazen raft
#

If it's been downloaded it means the user subscribed to YouTube Premium

#

If it's been downloaded from YouTube

shrewd fjord
#

i think, from youtube side its okay to add premium and stuff, they also now dont allow ad blockers, main source of their income is just ad

shrewd fjord
naive briar
#

You won't be able to await anything during the calculation to allow the wait_for to process

vapid parcel
#

just not through youtube

brazen raft
#

Downloading YouTube content not through YouTube sounds fishy

naive briar
shrewd fjord
vapid parcel
#

how do you think it works in bots..?

brazen raft
#

Do these downloader websites have YouTube Premium that they can download content?

vapid parcel
#

tbh idk how they do it

slate swan
#

no lol

shrewd fjord
#

sed, i need to now remove math command, wait i have an idea

vapid parcel
#

but it does break youtubes ToS thats all i know

naive briar
shrewd fjord
#

GIL?

brazen raft
naive briar
brazen raft
#

Why are you writing to a temporary file btw

#

For the ffmpeg command?

vapid parcel
shrewd fjord
vapid parcel
#

XD

shrewd fjord
brazen raft
vapid parcel
#

hes using mp3

shrewd fjord
#

i used to spell interpreter as interepter Peepo_SpeakNoEvil

vapid parcel
#

😭

shrewd fjord
#

isnt it basically using discord as file host?

vapid parcel
#

yall hear about the file host for discord? they are changing it to max 24 hours or sum now

shrewd fjord
#

yh

vapid parcel
#

instead of never expiring lol

#

which idk how thats gonna work for bots tbh

shrewd fjord
#

with new ex, is and hm param to attachment endpoint

shrewd fjord
#

where ex refers to the expiry of an attachment

shrewd fjord
brazen raft
#

You can create a discord.File from an io.BytesIO

naive briar
#

!d discord.File

unkempt canyonBOT
#

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

Note

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

huh linux is weird

vapid parcel
#

here let me ask a question.

@bot.hybrid_command(name="codechallenge", description="Sends a random coding challenge with required difficulty")
@commands.guild_only()
async def codechallenge(ctx, difficulty):
    available_difficulties = ', '.join(coding_challenges.keys())

    if difficulty not in coding_challenges:
        error_embed = discord.Embed(
            title="Error",
            description=f"Invalid difficulty level. Available levels: {available_difficulties}",
            color=0xFF0000
        )
        await ctx.send(embed=error_embed)
    else:
        challenge = random.choice(coding_challenges[difficulty])

        embed = discord.Embed(
            title=f"Coding Challenge ({difficulty.capitalize()})",
            description=challenge,
            color=0x5865F2
        )

        response = embed

        await ctx.send(embed=response)```
#

how can you make a hybrid command do the options like app commands normally do..?

#

for difficulty it would show easy, medium and hard, how to do that basically?

naive briar
unkempt canyonBOT
#

examples/app_commands/transformers.py lines 80 to 87

# In order to support choices, the library has a few ways of doing this.
# The first one is using a typing.Literal for basic choices.

# On Discord, this will show up as two choices, Buy and Sell.
# In the code, you will receive either 'Buy' or 'Sell' as a string.
@client.tree.command()
@app_commands.describe(action='The action to do in the shop', item='The target item')
async def shop(interaction: discord.Interaction, action: Literal['Buy', 'Sell'], item: str):```
vapid parcel
#

choices.

#

well ty

vale wing
unkempt canyonBOT
vale wing
vapid parcel
#

not reading all of that gonna be real

vale wing
#

That's not much of text

#

Just 211 symbols cmon

vapid linden
#

await member.remove_roles(role)

#

discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

#

my dc bot has admin perms and for some raeson it gives me an error

turbid condor
#

Your bot can't remove the role

vapid linden
#

yes why??

#

its admin

turbid condor
#

Check if the role you are trying to remove is higher in hierarchy than the bot or not

vapid parcel
# naive briar That is called `choices`, see the [example](https://github.com/Rapptz/discord.py...
class Difficulty(Enum):
    easy = 0
    medium = 1
    hard = 2


@bot.hybrid_command(name="codechallenge", description="Sends a random coding challenge with required difficulty")
@commands.guild_only()
async def codechallenge(ctx, difficulty: Difficulty):
    available_difficulties = ', '.join(coding_challenges.keys())

    if difficulty not in Difficulty:
        error_embed = discord.Embed(
            title="Error",
            description=f"Invalid difficulty level. Available levels: {available_difficulties}",
            color=0xFF0000
        )
        await ctx.send(embed=error_embed)
    else:

        difficulty_name = difficulty.name

        challenge = random.choice(coding_challenges[difficulty_name])

        embed = discord.Embed(
            title=f"Coding Challenge ({difficulty_name.capitalize()})",
            description=challenge,
            color=0x5865F2
        )

        response = embed

        await ctx.send(embed=response)```


Thank you for the help :)
turbid condor
#

In role settings check if your bot's role is lower then then role you are removing

turbid condor
#

Move it above the role you are removing

vapid linden
#

god that is so stupid how is that a thing??? like what it makes no sense

final iron
vapid parcel
#

ye

#

its kinda weird lol

shrewd fjord
ebon bluff
#

yall i have a problem. im tryna edit an embed with discord-webhook, but idk how to edit fields from the embed.

right now it keeps adding new fields to the embed each time it edits the message

#

do i send the code as a file or can i just send it all in a message

#

its 39 lines

buoyant quail
slate swan
shrewd fjord
#

whats the namespace for using large int as slash command option type

#

talking about dpy, in disnake its commands.LargeInt ;-;

shrewd apex
shrewd fjord
#

actully nvm 💀

shrewd apex
#

it did?

#

docs dosent show

#

oh wait disnake

shrewd fjord
#

ye

harsh orbit
#
@bot.command()
async def add(ctx, id, ammount):
    with open("bank.json", "r") as f:
        users = json.load(f)
    user = ctx.guild.get_member(int(id))
    if user == None:
        await ctx.reply("لا يمكنك إضافة عملات لشخص غير موجود في السيرفر")
    else:
        await open_account(user)
        users[str(user.id)]["wallet"] += int(ammount)
        await save(users)
        await ctx.send(f"تمت إضافة {ammount} عملات ل {user.mention} بنجاح !")


async def open_account(user):
    with open("bank.json", "r") as f:
        users = json.load(f)

        if str(user.id) in f:
            return False
        else:
            users[str(user.id)] = {}
            users[str(user.id)]["wallet"] = 0

    await save(users)
    return True


async def save(users):
    with open("bank.json", "w") as f:
        json.dump(users, f)

Why the data* is not saved in the json file

#

when I use add command

#

the wallet still 0

final iron
# harsh orbit ```py @bot.command() async def add(ctx, id, ammount): with open("bank.json",...

JSON is a convenient and easy-to-read data storage protocol that's widely accepted by most programming languages. However, we caution against its use for storing and retrieving data in an asynchronous environment like a Discord bot.

  • It's a file-based data storage, which makes it vulnerable to race conditions
  • You'll need to implement your own synchronization primitives to avoid corrupting data
  • If you're not careful, you could accidentally wipe your entire JSON file.

Solution? Use a database. Recommended schema are SQLite, PostgreSQL, and MongoDB.

  • Async libraries exist on pypi for each of these
    sqlite -- aiosqlite (or Danny's wrapper, ?tag asqlite)
    postgresql -- asyncpg
    mongodb -- motor
  • Databases organize your data into tables, and are fast at inserting, retrieving, and removing records
  • You can impose uniqueness constraints to ensure against duplication
  • The Python libraries enforce synchronization for you
  • The query language is intuitive, you can get running with simple queries in just a few hours!
#

JSON is pretty much widely accepted as a poor data storage medium for Discord bots. The only reason it’s still used is due to tutorials perpetuating the false idea that JSON is a valid choice

naive briar
#

Speaking of databases, PostgreSQL wasn't as hard as I thought

#

Should've tried a little earlier

final iron
#

Doesn’t it use a similar structure to JSON, or is that MongoDB

naive briar
#

MongoDB is

naive briar
shrewd fjord
#

what wacky syntax pithink

meager rock
#

INSERT INTO spooky

final iron
#

Wdym

#

Queue for what

cinder tulip
#
@tasks.loop(seconds=1)
async def send_potato_pics():

    send_potato_pics.stop()

    potato_links = [links]

    channel_id = priv

    channel = client.get_channel(channel_id)
    if channel:
        embed = discord.Embed(title="Random Potato Pic", description="Enjoy this distinguish potato!", colour=discord.Color.yellow())
        embed.set_image(url=random.choice(potato_links))
        await channel.send(embed=embed)

    new_interval = random.randint(10 * 60, 60 * 60)
    send_potato_pics.change_interval(seconds=new_interval)
    send_potato_pics.stop()
    send_potato_pics.start(interval=new_interval)

@client.event
async def on_ready():
         send_potato_pics.start()

Terminal:

2023-10-14 19:08:50 ERROR    discord.ext.tasks Unhandled exception in internal background task 'send_potato_pics'.
Traceback (most recent call last):
  File "C:\Users\-\AppData\Roaming\Python\Python310\site-packages\discord\ext\tasks\__init__.py", line 239, in _loop
    await self.coro(*args, **kwargs)
  File "c:\Users\-\Desktop\Vale\Scripts\Pepsi_Fish\main.py", line 136, 
in send_potato_pics
    send_potato_pics.start(interval=new_interval)
  File "C:\Users\-\AppData\Roaming\Python\Python310\site-packages\discord\ext\tasks\__init__.py", line 392, in start
    raise RuntimeError('Task is already launched and is not completed.')   
RuntimeError: Task is already launched and is not completed.

The message gets sent by the bot but idk why that thing appears

slate swan
cinder tulip
#

well i found a solution to it

#

and im stupid for not having thought about it, which is just putting:

    if send_potato_pics.is_running():
        return

lmao

shrewd fjord
#

spooky

desert kiln
slate swan
#

can anyone help my commands aint getting synced

#

`@bot.event
async def on_ready():
try:
await bot.change_presence(activity=discord.Game("JarRat-Builder by BotX"))
print(f'Logged in as {bot.user.name}')
except Exception as e:
print(f'Error in on_ready: {e}')

    await bot.tree.sync()

@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandError):
await ctx.send(f"An error occurred: {error}")
`

#

also im using @bot.command()

#

anyone??

slate swan
slate swan
slate swan
sage otter
#

inb4 just alt+tab

slate swan
sage otter
#

so serious though

#

it would be that easy

slate swan
#

its shift + tab ;)

sage otter
#

dammit

slate swan
#

@slate swan how do i fix it :/

tender knoll
#

how do you even make a discord bot?

#

and also like what level of experience in python is discord bot programming for?

desert kiln
burnt coral
tender knoll
burnt coral
tender knoll
burnt coral
#

yep

tender knoll
#

im mostly into gamedev anyway

burnt coral
#

basics, by my pov is a high level understanding of things like concurrency, apis, http, sockets, oop, etc..

#

if you know those, you're good to go imo

slate swan
tender knoll
#

ok then nevermind 😂

slate swan
tender knoll
sage otter
sick birch
slate swan
wicked atlas
sage otter
burnt coral
wicked atlas
#

But it's a good to know kinda thing

slate swan
sage otter
#

we were joking about that earlier because shift+tab is really all you have to do

#

you just have to unindent the part where you sync the tree

#

and it pulls it back into the function scope

tender knoll
burnt coral
#

FYI the things i mentioned earlier is not just specific to discord bots (not even python), these are things you'd likely come across as a game developer if you ever want to add multiplayer to your game

slate swan
tender knoll
desert kiln
sage otter
slate swan
#

stays here after ctrl^c

#

does not let me type anything

rancid ravine
#

i want to send a embed with link of a attachment on that same message that ive send, is it possible? if yes could you please send me the code? i use nextcord

slate swan
rancid ravine
final iron
#

Also, is the code written by ChatGPT or similar

rancid ravine
rancid ravine
final iron
rancid ravine
#

yes because my method using attachment://filename.suffix doesnt work

#

i dont want the image as thumbnail or image in the embed but as a hypelink in description if that possible

final iron
#

Also, you said you don’t want it to be an image in the ember, or a thumbnail but those are the 2 main ways to pass an image

rancid ravine
#

all i needed to know

vapid parcel
#

for an arguement for a hybrid can you make it have like a limit of how many letters can go in it or something?

#

idk how to explain what im asking lol

#

instead of saying letters lets say characters i guess.

vapid parcel
#

damn

golden portal
#

!d discord.ext.commands.Range

unkempt canyonBOT
#

class discord.ext.commands.Range```
A special converter that can be applied to a parameter to require a numeric or string type to fit within the range provided.

During type checking time this is equivalent to [`typing.Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) so type checkers understand the intent of the code.

Some example ranges...
naive briar
#

Oh, yes

#

I thought that was for ints and floats only

golden portal
#

cat moment

vapid parcel
bitter flare
#

i need help

naive briar
#

What is it?

bitter flare
#

how can i use a condition where i can break the loop if the message starts with a particular message only

#

is it possible to do so ? @naive briar

slate swan
#

What are you even trying to do

#

Your bot will just get rate limited and eventually banned if you send so many messages

fiery girder
#

which library can i use to make a DJ discord bot

bitter flare
fiery girder
#

it got to me with the purge command

#

i purge way to many messages some time

#

btw anyone know a good library to make a DJ bot

bitter flare
#

youtubedl ?

slate swan
#

!ytdl

unkempt canyonBOT
#
Our youtube-dl, or equivalents, policy

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
#

May be worth noting ^

bitter flare
#

lol

slate swan
#

Music bots these days shouldn't be made

fiery girder
#

why not i want a music bot

bitter flare
#

every music bot is getting banned 🥲

slate swan
#

It'll get sued by YouTube and deleted by Discord, but sure go ahead

fiery girder
#

but what about if i use spotify

#

or something

slate swan
#

It'll get sued by Spotify and deleted by Discord, but sure go ahead

bitter flare
#

;-;

fiery girder
#

well rip my time spent on making the logo for the bot

slate swan
bitter flare
#

isnt there any way to make a music bot without it getting banned ?

slate swan
#

Don't use a music provider service, and have the rights on the music

#

So you'd have to store the mp3 files (without downloading from YouTube, Spotify, etc.), and have the rights on the music

bitter flare
#

without using a music provider service , how can u do that

#

oh

slate swan
#

So it's not even worth it

bitter flare
#

whats the point if u cant download it from yt or spotify 🥲

#

damn

#

so music bots are a no go

slate swan
#

yepa

bitter flare
#

but what about hyra and chip ?

slate swan
#

Lucky, but their time will come sooner or later

bitter flare
#

shucks

turbid condor
#

As far as i know hydra got flagged once before too

slate swan
#

Not as popular as e.g. Rythm, so probably didn't catch YouTube's attention

turbid condor
#

Yeah so if you want to make a music bot just keep it to your server

bitter flare
slate swan
#

No it won't, unless YouTube realizes it at some point with logs or whatever

naive briar
slate swan
#

You just won't get caught that's about it

turbid condor
bitter flare
slate swan
#

But yeah just don't do it

slate swan
slate swan
bitter flare
slate swan
#

And if they catch you, unlucky

bitter flare
#

what r the consequences ?

naive briar
#

Copyright stuff

slate swan
#

Depends krShrug Court will eventually tell you

bitter flare
#

will u have to pay compensation money n stuff ?

#

or will they just delete the bot

turbid condor
#

That will happen

slate swan
#

As said, depends

bitter flare
#

hmm

turbid condor
#

U might even get an ip ban

bitter flare
#

;-;

slate swan
#

Rythm had to cease their actions within a short timespan, if they didn't then it probably goes higher e.g. you get sued and asked to go in court, then yeah you'll probably have to pay compensations

bitter flare
#

oh

#

but i heard sumthing about rythm making a comeback

slate swan
#

YouTube doesn't care if you delete your bot or not, they want you to stop your actions

naive briar
naive briar
#

To be honest, I still don't get why people would want to listen to music in Discord

turbid condor
#

Isn't SoundCloud api closed?

bitter flare
#

ive got no idea

slate swan
#

Any music provider with common sense disallows it

bitter flare
#

like ours we only recently got access to it

bitter flare
slate swan
slate swan
bitter flare
#

but yea who needs music bot when they got activities

turbid condor
#

You will need written permissions for streaming music

bitter flare
#

damn

#

well

#

ig no music bot for us den

#

XD

#

how can i remove the umm.

#

the brackets from the message ?

slate swan
#

use random.choice

bitter flare
#

i did ?

#

oh wait

#

ive set it up as a list

#

but how do i not get the brackets

slate swan
#

like i said use random.choice

bitter flare
#

but i have used it ?

slate swan
#

no you did not

#

!e ```py
import random

data = [1, 2, 3]

print(random.choices(data))
print(random.choice(data))

unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | [3]
002 | 1
bitter flare
#

OH

#

DAMN

#

thanks

slate swan
#

👍

bitter flare
#

still not fixed

slate swan
#

show how smile_names is defined

naive briar
bitter flare
bitter flare
slate swan
#

well it must be working 😂

#

print out to console smile_names before creating embed

bitter flare
#

how do i do that ;-;

slate swan
#

print(...) ?

bitter flare
#

print smile names ?

slate swan
#

yes

gleaming holly
#

is there a error in this code:
channel = bot.get_channel(int(CHANNEL_ID))

slate swan
#

!d discord.ext.commands.Bot.get_channel

unkempt canyonBOT
slate swan
#

it can return None if thats what you mean

#

prefered syntax would be channel = .get_channel(...) or await .fetch_channel(...) this way you make sure you receive the channel object

gleaming holly
#

ook ty

bitter flare
#

oh wait im dumb

#

🙂

#

IT WORKED

#

HOW

#

@slate swan could you please explain how it worked ?

#

printing it before embedding it worked

#

how tho

slate swan
#

because you didn't save

bitter flare
#

istg i did

#

i have auto save enabled

#

:').

slate swan
#

it proved you didn't

bitter flare
#

;-;

#

wat

#

im confusion

#

OH

#

CUZ THE BOT WAS RUNNING

#

to run the print statement i had to run it again

#

i see

slate swan
#

imagine not having hot reload Yawn

bitter flare
#

what is a hot reload ?

maiden fable
unkempt canyonBOT
#
Not in a million years.

No documentation found for the requested symbol.

maiden fable
#

!d discord.ext.commands.Bot.reload_extension

unkempt canyonBOT
#

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

Atomically reloads an extension.

This replaces the extension with the same extension, only refreshed. This is equivalent to a [`unload_extension()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.unload_extension) followed by a [`load_extension()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.load_extension) except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.
maiden fable
#

There ^

bitter flare
#

how do u use it ?

#

im very new to this so i dont really know much about it

final iron
bitter flare
#

like where do i put it in the code ?

#

im dumb >_< sorry

final iron
bitter flare
final iron
#

If you want.

bitter flare
#

can i dm ?

final iron
#

No.

bitter flare
#

🥲

slate swan
#

why do people want to randomly dm others, it's acting so weird

bitter flare
#

noo cuz i dont wanna make a fool outta myself

#

🥲

#

i trierd using the menthod from earlier ? but it didnt work for me or rather im not sure how to use it

#

🥲

slate swan
#

What on earth are you even doing

bitter flare
#

i dunno much about python

#

i recently got into it

#

so i dunno much 🥲

slate swan
#

d.py is not made for beginners

bitter flare
#

:').

#

still id like to learn

sinful surge
bitter flare
sinful surge
#

ohhh

#

I prefer py-cord (you could still call it discord.py)

bitter flare
#

py-cord sounds nice but discord.py is a lil easier to understand ?

#

meh its whatever

#

lol

sinful surge
#

I think py-cord is an active discord.py fork so pretty much the same thing but idk why I even use it

final iron
slate swan
#

^

sinful surge
#

ELABORATE

final iron
#

Their implementations are shit

sinful surge
#

for example

final iron
#

General code design, their implementation of slash commands, context menus etc make no sense

sinful surge
#

the slash commands are so easy to use what are you talking about

slate swan
#

implementation != usage

sinful surge
#

mah bad

final iron
#

Instead of actually formulating an implementation that makes sense

#

import discord

bot = discord.Bot()

we need to limit the guilds for testing purposes

so other users wouldn't see the command that we're testing

@bot.command(description="Sends the bot's latency.") # this decorator makes a slash command
async def ping(ctx): # a slash command will be created with the name "ping"
await ctx.respond(f"Pong! Latency is {bot.latency}")

bot.run("TOKEN")

#

Like, what is this

#

Why is there a separate Bot object for slash commands. Slash commands don’t receive context, so no clue why they’re using it

quick gust
sinful surge
quick gust
#

no wonder I heard so much stuff about pycord being shit

final iron
#

It makes literally no sense why they would do that

quick gust
#

i lost it when I saw context

final iron
sinful surge
#

how is it better? again im just curious

quick gust
#

because it makes more sense

sinful surge
#

that doesn't explain it to me

#

because you're more familiar with discord.py (probably) and im more familiar with pycord

quick gust
#

nah I dont use discordpy yet it makes more sense than what example penguin sent

sinful surge
#

ah okk thanks for explaining

sinful surge
#

disnake?

quick gust
#

yep

#

probably the best discordpy fork imo

sinful surge
#

Is there something objectively bad in pycord's slash command implementation though

final iron
# sinful surge how is it better? again im just curious

A command tree allows for better control with syncing and managing slash commands. Slash commands never receive context so it makes no sense for them to have it. Furthermore, having the exact same decorators, and using the same class just confuses the end user

vapid parcel
#

Okay so for discord dev portal, if you change the profile of the bot, does it actually update or do you have to make a new bot?

quick gust
#

it updates

sinful surge
#

yeah it does

vapid parcel
#

how long does it take

sinful surge
#

not very long

vapid parcel
#

like an ETA

quick gust
#

its instant im pretty sure

vapid parcel
#

its never worked for me

sinful surge
#

I'd say max 1 minute

quick gust
#

try restarting discord

sinful surge
vapid parcel
#

well im asking for a friend, but when ive done it, i think it was icon

#

not app icon

quick gust
#

theres 2 sections. General Information and Bot

#

you need to change the one in Bot

vapid parcel
#

yeah thats icon

#

not app icon

quick gust
#

well it is pretty much instant

sinful surge
#

@quick gust mind giving me a sales pitch to convert to disnakeism? everyone seems to hate pycord

naive briar
#

It's probably because of advertisement

quick gust
#

and honestly just switch to dpy

#

I'm still using disnake because im too lazy to switch

quick gust
sinful surge
#

isn't dpy discontinued?

quick gust
#

oh you might be slightly outdated

sinful surge
#

are they continuing it

slate swan
#

Since March 2022, yes

naive briar
#

Probably already a year or two ago at this point

#

Time flies

vapid parcel
sinful surge
#

lmao yeah im slightly outdated

quick gust
#

yeah just slightlyy outdated

vapid parcel
#

SLIGHTLY

sinful surge
#

I just make bots and py-cord works perfectly for me there's no reason to switch libraries so I havent been keeping up

#

sory python pepol

turbid condor
#

Nah there are still many believers of discontinuity of dpy

vapid parcel
naive briar
#

After all, it's your choice

vapid parcel
#

that was YEARS ago 😭

slate swan
#

tbh hikari looks noice

naive briar
turbid condor
#

💀

slate swan
naive briar
#

Every time I need to find something, I have to guess which super class have it

slate swan
#

They could definitely remake the docs though

naive briar
#

I guess it's familiarity thing

slate swan
#

Though I'm used to reading horrible documentations like Apple and Windows documentations

ashen river
#

what is the best way to handle multiples tasks in a discord bot so it don't disrupts the tasks of the other users?

slate swan
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

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

this you mean?

ashen river
#

i have a chat bot and i want to give access to it to other people, it generates response and send, but just to be on safe side i don't want it to brick when multiple people are trying to generate a message with it

#

more like a gpt bot but instead of openai it is a local llm

#

what will be the way to go with it? Add a user queue so they do it one at a time?

naive briar
#

Queues sounds nice

#

!d discord.ext.commands.max_concurrency - there's also this

unkempt canyonBOT
#

@discord.ext.commands.max_concurrency(number, per=discord.ext.commands.BucketType.default, *, wait=False)```
A decorator that adds a maximum concurrency to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command) or its subclasses.

This enables you to only allow a certain number of command invocations at the same time, for example if a command takes too long or if only one user can use it at a time. This differs from a cooldown in that there is no set waiting period or token bucket – only a set number of people can run the command.

New in version 1.3.
ashen river
naive briar
#

!d asyncio.Queue

unkempt canyonBOT
#

class asyncio.Queue(maxsize=0)```
A first in, first out (FIFO) queue.

If *maxsize* is less than or equal to zero, the queue size is infinite. If it is an integer greater than `0`, then `await put()` blocks when the queue reaches *maxsize* until an item is removed by [`get()`](https://docs.python.org/3/library/asyncio-queue.html#asyncio.Queue.get).

Unlike the standard library threading [`queue`](https://docs.python.org/3/library/queue.html#module-queue), the size of the queue is always known and can be returned by calling the [`qsize()`](https://docs.python.org/3/library/asyncio-queue.html#asyncio.Queue.qsize) method.

Changed in version 3.10: Removed the *loop* parameter.

This class is [not thread safe](https://docs.python.org/3/library/asyncio-dev.html#asyncio-multithreading).
naive briar
#

You can have the command put the request into the queue and have a task to process the request

ashen river
#

like users will be able to keep sending the commands and it will just put it in queue when one is done it moves to the next persons request

naive briar
#

Nope

naive briar
shrewd fjord
#

:3

ashen river
naive briar
ashen river
#

i am gonna check it out and see if i can implement it

final iron
#

How would I send a modal from a prefixed command?

#

Is it possible?

torn sail
sick birch
#

Buttons can open modals, though, so there's that

final iron
#

Yeah, I already made a paginator with em

#

I just don't use prefixed commands so

burnt coral
#

does discord.py offer a way to run synchronous code without blocking it's main event loop excluding threads? if not, what's the solution for doing it manually using asyncio? if that's not possible either, what's the best practice for spawning threads under an async event loop

sick birch
#

The executors can be process pool executors or threadpoolexecutors

burnt coral
hushed galleon
#

if its a short-lived task, await loop.run_in_executor(None, callback, ...) or await asyncio.to_thread(callback, ...) is fine, but for longer-lived workloads i would suggest creating the thread/process manually so you have more control over it's lifetime

burnt coral
#

alrighty, thanks!

cold oyster
#

[2023-10-15 13:30:58] [WARNING ] discord.http: We are being rate limited. PUT https://discord.com/api/v10/applications/987664938627653673/commands responded with 429. Retrying in 26.35 seconds.

Anyone know what this mean?

cold oyster
final iron
cold oyster
final iron
#

What

#

This is the question you asked. How do you not know what the question you asked means

hushed galleon
ashen river
# naive briar !d asyncio.Queue

i've tried adding it but there still seems to be some issue with it, it will not take into the request of second users response in and will show it as failed

cosmic python
#

Hello

slate swan
#

hi

lyric sigil
#

Do someone know how i can make my bot send a webhook when someone use a command ?

inland quailBOT
#
MemberJoinMonitoring:
  creation_time All commands related to the Creation time trigger.
​No Category:
  help          Shows this message

Type $help command for more info on a command.
You can also type $help category for more info on a category.
final iron
unkempt canyonBOT
#

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

Creates a webhook for this channel.

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

Changed in version 1.1: Added the `reason` keyword-only parameter.
final iron
#

!d discord.ext.commands.Context.channel

unkempt canyonBOT
young dagger
#

Is there any way to ban users marked with Unusual DM Activity (the new Automod feature)?

final iron
#

!d discord.Member

unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User).

x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User) instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User) instances too.

hash(x) Returns the member’s hash.

str(x) Returns the member’s handle (e.g. `name` or `name#discriminator`).
final iron
young dagger
final iron
#

I'd say it's not supported though

#

Especially recently, Discord doesn't have the best track record with that type of stuff

patent lark
#

does .get_guild() not work anymore?

turbid condor
#

!d discord.Client.get_guild

unkempt canyonBOT
#

get_guild(id, /)```
Returns a guild with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
turbid condor
patent lark
#

Right, im using it but my guild returns NoneType every time i reference it

turbid condor
#

Can you tell where you are using? Like in an event or command?

patent lark
#

I defined the guild globally, and i am referncing it the line directly below defining it

#
guild = bot.get_guild(MY ID IS HERE)
STAFF = get(guild.roles, name="TSK STAFF")```
turbid condor
#

So it isn't inside an event or command?

patent lark
#

No.

turbid condor
#

In that case the problem might be because it gets called even before your bot cache is ready

cold oyster
patent lark
#

I was thinking that, should i wait()?

cold oyster
patent lark
cold oyster
#

Alr

turbid condor
patent lark
#

What do you recommend?

cold oyster
#

What r u tryna do?

turbid condor
#

I'd say just recall the guild where you need it

cold oyster
#

find a role?

#

@patent lark THIS

patent lark
#

where it will be used

cold oyster
#

Oh

patent lark
#

Let me change up my code a bit

turbid condor
cold oyster
patent lark
#

And yeah i grabbed the role inside the function

#

Still returned NoneType

turbid condor
#

Hmm can you show the function

patent lark
#

Sure.

cold oyster
#

Wrong chat 😭

patent lark
#
@bot.listen("on_message")
async def on_message(message): # Called when a chat is sent
  if message.author.bot:
    return
  STAFF = get(guild.roles, name="TSK STAFF")
  if STAFF in message.author.roles:
    return
  if banned_msgs in message.content.lower():
    await message.delete()
    await message.channel.send("Message Moderated.")
#

Guild is defined at the top of my code. Returning NoneType

turbid condor
patent lark
#

The guild

#

AttributeError: 'NoneType' object has no attribute 'roles'

turbid condor
#

Fetch the guild inside the on message too

patent lark
#

Alright

turbid condor
#

Cuz the problem remains same the get_guild gets called before the on_ready if it's outside

#

Which results in the guild being none

patent lark
#

That fixed my problem.

#

Thank you, I figured if i just made the guild global i would be able to reference it in another scope

turbid condor
#

You need to wait for bot to have loaded cache inorder to use get

patent lark
#

Yo @turbid condor

#

Im also having another issue

#

I have a list of strings, and when this list of strings is referenced i get:

TypeError: 'in <string>' requires string as left operand, not bool

#

Not quite understanding it.

shrewd apex
#

!e True in ""

unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     True in ""
004 | TypeError: 'in <string>' requires string as left operand, not bool
patent lark
#

ah i fixed it

ashen river
# naive briar How did you implement it?

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')
    
    try:
        synced = await bot.tree.sync()
        print(f"Synced {synced} commands.")
    except Exception as e:
        print(e)

    # Start the queue manager as a background task
    asyncio.create_task(queue_manager())

async def queue_manager():
    while True:
        # Wait for a task in the queue
        interaction, input = await response_generation_queue.get()
        await process_response_generation(interaction, input)

@bot.tree.command(name="generate")
async def generate(interaction: discord.Interaction, input: str):
    if not interaction.response.is_done():
        await interaction.response.defer()

    user_data = {
        'interaction': interaction,
        'input': input}

    if not response_generation_queue.empty():
        await response_generation_queue.put(user_data)
        await interaction.followup.send(f"You're placed in queue. Current position: {response_generation_queue.qsize()}.")
        return

    asyncio.create_task(process_response_generation)
ashen river
#

and then a full error log of the interaction.defer()

naive briar
#

Did you get any tracebacks?

ashen river
# naive briar Did you get any tracebacks?
  File "/usr/local/lib/python3.10/dist-packages/discord/app_commands/commands.py", line 828, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "/workspace/bot.py", line 64, in convert
    await interaction.response.defer()
  File "/usr/local/lib/python3.10/dist-packages/discord/interactions.py", line 661, in defer
    await adapter.create_interaction_response(
  File "/usr/local/lib/python3.10/dist-packages/discord/webhook/async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

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

Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/usr/local/lib/python3.10/dist-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/usr/local/lib/python3.10/dist-packages/discord/app_commands/commands.py", line 846, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'generate' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
#
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/discord/app_commands/commands.py", line 828, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "/workspace/bot.py", line 64, in generate
    await interaction.response.defer()
  File "/usr/local/lib/python3.10/dist-packages/discord/interactions.py", line 661, in defer
    await adapter.create_interaction_response(
  File "/usr/local/lib/python3.10/dist-packages/discord/webhook/async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

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

Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/usr/local/lib/python3.10/dist-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/usr/local/lib/python3.10/dist-packages/discord/app_commands/commands.py", line 846, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'generate' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
naive briar
#

That's very weird

#

Does the process_response_generation have long blocking code (synchronous)?

ashen river
#

i think it impacts the interaction in a way that unless the GPU gets free it won't move to the next one right

shrewd apex
robust fulcrum
shrewd apex
#

no

#

u have to manually reload u can use reload_extension along with watchfiles

#

disnake has one inbuilt

#

!pypi cogwatch

unkempt canyonBOT
tender bobcat
#

What if I use auto-save with my IDE, would that just crash the bot?

polar skiff
#

Hello, what should I do if the library is not installed? discord-components. Help pls

turbid condor
polar skiff
#

I have an error in the bot, here is the code itself. He doesn't see the discord components and says to install them.Here is the code itself

import discord
from discord.ext import commands
from discord_components import DiscordComponents, Button

intents = discord.Intents.default()
intents.typing = False
intents.presences = False

bot = commands.Bot(command_prefix='!', intents=intents)
DiscordComponents(bot)

tickets = {}

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

@bot.command()
async def ticket(ctx):
    await ctx.send("Нажмите кнопку, чтобы открыть тикет.", 
                   components=[Button(style=1, label="Открыть тикет")])

@bot.event
async def on_button_click(interaction):
    if interaction.component.label == "Открыть тикет":
        guild = interaction.guild
        user = interaction.user
        channel = await guild.create_text_channel(name=f"ticket-{user.name}", 
                                                  category=guild.categories[0])
        await channel.set_permissions(user, read_messages=True, send_messages=True)
        tickets[channel.id] = user.id

        await interaction.respond(content="Ваш тикет был создан!", 
                                  ephemeral=True)
    elif interaction.component.label == "Закрыть тикет":
        channel_id = interaction.channel.id
        user_id = tickets.get(channel_id)
        if user_id:
            user = await bot.fetch_user(user_id)
            await interaction.respond(content=f"Тикет закрыт пользователем {user.name}!", 
                                      ephemeral=True)
        else:
            await interaction.respond(content="Тикет не найден!", 
                                      ephemeral=True)
        await interaction.channel.delete()

bot.run('YOUR_BOT_TOKEN')
turbid condor
polar skiff
#

Yes

turbid condor
polar skiff
#

Can you correct the code, or rather remove what is not needed? And make sure there are no mistakes

turbid condor
#

no

polar skiff
#

Okay, thank you for your help

ashen river
#

It can now handle multiple interactions at once but for some reason it does not send them a followup message of that they are in the queue

#
        await response_generation_queue.put(user_data)
        await interaction.followup.send(f"You're placed in queue. Current position: {response_generation_queue.qsize()}.")
        return```
naive briar
ashen river
naive briar
#

How did you put the first request if the queue would be empty then?

ashen river
#

do correct me if im wrong would appreciate the help

slate swan
#

can someone help me with my pip installation its saying this

    from discord_slash import SlashCommand
ModuleNotFoundError: No module named 'discord_slash'

slate swan