#discord-bots

1 messages · Page 251 of 1

slate swan
naive briar
#

Eh, yeah, probably just the posts

tawdry tundra
#

How i can make ping command when the client do not accept commands and bot Dont accept Latency

smoky sinew
#

why does the client not accept commands

tawdry tundra
#

I will send screenshot

tawdry tundra
smoky sinew
#

you're using a bot

tawdry tundra
#

I changed jt

#

Because

#

The bot donot accpet Latency

slate swan
#

!d discord.Client

unkempt canyonBOT
#

class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

async with x Asynchronously initialises the client and automatically cleans up.

New in version 2.0.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
tawdry tundra
#

I tried this

smoky sinew
#

don't try it

#

use bot, client doesn't have commands

tawdry tundra
#

So

#

How i can make ping command

smoky sinew
#

use a bot

tawdry tundra
#

Latency
Not working

#

I should replace it with somethi

#

?

smoky sinew
#

nothing to do with latency

smoky sinew
tawdry tundra
#

I use bot now

#

But how I can make ping command

smoky sinew
#

!d discord.ext.commands.Bot.latency

unkempt canyonBOT
#

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

This could be referred to as the Discord WebSocket protocol latency.
tawdry tundra
#

Its from the capital letter

#

Latency
latency

#

Im sorry

slate swan
tawdry tundra
#

`` import discord
from discord.ext import commands
import os
import random

intents=discord.Intents.all()

bot = discord.ext.commands.Bot("?", intents=intents)

@bot.command()
async def ping(ctx):
await ctx.send(f"the ping is {round(bot.latency * 1000)} ms ")

@bot.command(aliases=["8ball"])
async def _8ball(ctx, *, question):

responses = ["dumb", "nope", "uveu", "Bronze", "shit", "hit", "lana rhoades", "riely reid"]

ctx.send(f"Question: {question}\nanswe: {random.choice(responses)}")

@bot.event
async def on_ready():
print("Online !!")

token = os.environ['Token']
bot.run(token) ``

#

How I'm missing question

slate swan
tawdry tundra
#

Look at the code

slate swan
#

what does that have to do with code

tawdry tundra
#

I used question

slate swan
#

question has no default value so if you run command without passing question it will raise exception

tawdry tundra
#

Ok

#

How I run it correctly?

slate swan
#

!8ball question

tawdry tundra
slate swan
#

do you know what alias is?

tawdry tundra
#

Yes

#

And I'm use it in the code

#

@slate swan

tawdry tundra
slate swan
tawdry tundra
#

Nope

slate swan
#

error?

tawdry tundra
#

Yes

slate swan
#

show it then

tawdry tundra
#

Enable tracemalloc to get the object allocation traceback

naive briar
#

Await the ctx.send

#

The error should already be saying that

tawdry tundra
#

I miss await

naive briar
#

Anyway, it's probably just a warning

tawdry tundra
#

But also

#

Why i need to type question with command when i use alias

naive briar
#

Because you made it do so

tawdry tundra
#

?

#

Oh

#

I understand

#

Sorry for the stupid question

slate swan
#

okay guys

#

how do i make a request for response?

#

like how i do in scanf from C language

#

but by discord text input?

#

i'm planning to it request an input

#

in a button to press

smoky sinew
unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

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

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

This function returns the **first event that meets the requirements**...
smoky sinew
#

but if you're using a view you should open a modal instead, it's a better UX

#

!d discord.InteractionResponse.send_modal

unkempt canyonBOT
#

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

Responds to this interaction by sending a modal.
cedar lotus
#

@unkempt canyon

unkempt canyonBOT
#
Available tags


» args-kwargs
» async-await
» blocking
» botvar
» class
» classmethod
» codeblock
» comparison
» contribute
» customchecks
» customcooldown
» customhelp
» dashmpip
» decorators

slate swan
turbid condor
# slate swan okay, i thijnk i will need an example of how to use it
from discord import ui

class Questionnaire(ui.Modal, title='Questionnaire Response'):
    name = ui.TextInput(label='Name')
    answer = ui.TextInput(label='Answer', style=discord.TextStyle.paragraph)

    async def on_submit(self, interaction: discord.Interaction):
        await interaction.response.send_message(f'Thanks for your response, {self.name}!', ephemeral=True)

Docs : https://discordpy.readthedocs.io/en/latest/interactions/api.html?#discord.ui.Modal
Detailed example : https://github.com/Rapptz/discord.py/blob/master/examples/modals/basic.py

GitHub

An API wrapper for Discord written in Python. Contribute to Rapptz/discord.py development by creating an account on GitHub.

young dagger
#

How can I prevent this from happening?

#

There is a race condition in my code, even though I'm using queue.Queue

#
    if users_queue.qsize() <= 9:
        embed = discord.Embed(title=f"1 player is currently in the queue" if users_queue.qsize() == 1 else f'{users_queue.qsize()} players are currently in the queue', description=f'{member.mention} has joined the queue.', timestamp=datetime.datetime.now(), color=discord.Color.blue())
        await ctx.send(embed=embed)
        return```
potent spear
#

that'll lock the db when writing to it, so that fixes that problem I'd say..

slate swan
#

!d discord.ext.commands.max_concurrency

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 "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.
strange acorn
#

!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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

strange acorn
young dagger
slate swan
tacit canyon
slate swan
#

!d discord

unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

young dagger
young dagger
# slate swan Yeah should be good

How can I add the same logic for this code?

@client.event
async def on_voice_state_update(member, before, after):
    if (before.channel and before.channel.id in [712072729406472374]) and (after.channel is None or (after.channel and after.channel.id not in [712072729406472374])):

        # Check if the member is in the users_queue
        for user in users_queue.queue:
            if user['member'] == member:
                users_queue.queue.remove(user)
                channel = client.get_channel(712074759453671494)
                embed = discord.Embed(title=f"1 player is currently in the queue" if users_queue.qsize() == 1 else f'{users_queue.qsize()} players are currently in the queue',
                                      description=f'{member.mention} has left the queue.',
                                      timestamp=datetime.datetime.now(), color=discord.Color.red())
                await channel.send(embed=embed)
                return```
slate swan
#

Events cant be limited

young dagger
slate swan
#

Either limit it by yourself by storing data who and when to limit

young dagger
slate swan
#

Db or just dictionary in python?

#

If its data that you need only for small amount of time then can be dictionary

young dagger
#

I'm not sure what you mean

slate swan
#

I dont really know what you are trying to do exactly

hollow haven
#

How do I give another user's balance, I can't extract the member's id @

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

    @app_commands.command(name='solde', description="voir le solde")
    async def csolde(self, interaction: discord.Interaction, user: str = None):
        # Load the balance data from the file
        with open("balances.json", "r") as f:
            balances = json.load(f)
        
        if user:
            user_id = #####HERE
            user_balance = balances.get(user_id, 0)
            embed = discord.Embed(title="Solde", description=f"Solde de {user.id}: **{user_balance}**€",
                                  color=0x46a9f0)
        else:
            user_id = str(interaction.user.id)
            user_balance = balances.get(user_id, 0)
            embed = discord.Embed(title="Solde", description=f"Votre solde: **{user_balance}**€",
                                  color=0x46a9f0)
            
        await interaction.response.send_message(embed=embed, ephemeral=True)
young dagger
young dagger
#

"3 players are currently in the queue"

#

But it should be 3 and 4, right

slate swan
#

Is it possibly to sync commands to only be in guilds not dms

#

I don't want a specific guild just don't want commands in dms

potent spear
slate swan
#

🙏 Thank you

slate swan
summer jacinth
#

wait it is possibe to make a discord bot in python?

#

I dont know

#

it was more of a statement of disbelief

slate swan
#

You can make a discord bot in every language pretty much lol..

#

C++, C, JS, TS, Rust, Golang, C#, etc

summer jacinth
#

very cool, I did not know that, thanks

sick birch
#

But fundamentally, at the core, you're still making HTTP requests over the internet

summer jacinth
#

very cool, thank you

delicate summit
sick birch
delicate summit
#

gotcha

sick birch
#

Your browser has the capability to make HTTP requests. There are command line utilities like cURL that ship with most Windows and Linux distributions, there are also libraries in all sorts of languages to make HTTP requests (requests in Python, reqwest in Rust, axios in Node.js, etc..)

#

The only caveat is that at a large scale (like Discord) HTTP requests can be tricky and annoying to work with. Libraries like discord.py aim to simplify that by providing an interface native to your language

#

Writing your own discord API wrapper can be quite fun and educational, however is more of an advanced project

slate swan
#

Making a bot using the raw Discord API can be a fun challenge as opposed to using a library such as discord.py

full owl
#

Can discord bot record voice in voice channel?

sick birch
autumn granite
#

Hey

#

Can anyone help me with my code
I'm new to .py

shrewd apex
autumn granite
shrewd apex
#

if so it will be @client.command

autumn granite
#

@shrewd apex

turbid condor
slate swan
#

what exactly does this want me to do

#

not this? ["694482209096204308", "694482209096204308"]

vocal snow
#

(insert as int, not string)

slate swan
vocal snow
#

probably

slate swan
#

it didn't work though

#

it says Command raised an exception: AttributeError: 'Bot' object has no attribute 'owners'

vocal snow
#

Well maybe it just doesn't have that attribute then

#

have you checked the documentation to see if the attribute is correct

slate swan
#

I see

#

you do it like int("694482209096204308")

vocal snow
#

that's the same as 694482209096204308

slate swan
#

well it's giving me a different response so I guess it worked?

#

Traceback (most recent call last):
File "/home/filledwithnothing/Downloads/cheeseburger-bot-master/index.py", line 30, in <module>
if json.load(meow)["debug"] == "no":
^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/json/init.py", line 293, in load
return loads(fp.read(),
^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/json/init.py", line 346, in loads
return _default_decoder.decode(s)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 8 column 17 (char 349)

#

gave me this

vocal snow
#

looks like your json is malformed

slate swan
#

guess the int not helping

vocal snow
#

int() is not a valid thing in json

#

that's a python function

slate swan
#

your first key as no value too if I'm looking at that right

#

I moved it

#

because no share bot token

#

oh right

#

no .env?

#

forgot this was json not python 😭

slate swan
polar dawn
#

How do I use MemberConverter().convert in interaction?
It requires me to pass in ctx as a argument, but I assume that you can't use ctx in interaction.

Here's what I tried so far:

# I tried using "interaction" as ctx, but it didn't worked out
await commands.MemberConverter().convert(ctx=interaction, argument=user.name)
vocal snow
polar dawn
vocal snow
#

!d discord.ext.commands.Context.from_interaction

unkempt canyonBOT
#

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

Creates a context from a [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"). This only works on application command based interactions, such as slash commands or context menus.

On slash command based interactions this creates a synthetic [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") that points to an ephemeral message that the command invoker has executed. This means that [`Context.author`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.author "discord.ext.commands.Context.author") returns the member that invoked the command.

In a message context menu based interaction, the [`Context.message`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.message "discord.ext.commands.Context.message") attribute is the message that the command is being executed on. This means that [`Context.author`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.author "discord.ext.commands.Context.author") returns the author of the message being targetted. To get the member that invoked the command then [`discord.Interaction.user`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.user "discord.Interaction.user") should be used instead.

New in version 2.0.
polar dawn
autumn granite
turbid condor
#

!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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

slate swan
#
    async def backup(self, ctx, include_all_channels=False):
        try:
            permissions = {}
            categories = ctx.guild.categories
            channels = ctx.guild.channels if include_all_channels else ctx.guild.text_channels

            for category in categories:
                permissions[category.name] = {
                    'id': category.id,
                    'type': 'category',
                    'overwrites': [
                        {
                            'id': str(target.id),
                            'name': str(target),
                            'type': str(type(target)),
                            'role_name': str(target.name) if isinstance(target, discord.Role) else None,
                            'permissions': permission_pair.to_dict()
                        } for target, permission_pair in category.overwrites.items()
                    ]
                }

            for channel in channels:
                permissions[channel.name] = {
                    'id': channel.id,
                    'category': channel.category.name if channel.category else None,
                    'type': str(channel.type),
                    'overwrites': [
                        {
                            'id': str(target.id),
                            'name': str(target),
                            'type': str(type(target)),
                            'role_name': str(target.name) if isinstance(target, discord.Role) else None,
                            'permissions': permission_pair.to_dict()
                        } for target, permission_pair in channel.overwrites.items()
                    ]
                }

         ```


Error: 
Something went wrong while backing up permissions: 'PermissionOverwrite' object has no attribute 'to_dict'
#

I have no idea what is causing "Command raised an exception: AttributeError: 'Bot' object has no attribute 'owners'"

#

I don't know if it's in the index file

lethal drift
upbeat otter
#

It doesn't exist

slate swan
upbeat otter
vocal snow
#

Different libraries perhaps?

lethal drift
#

I'm using Pycord so that's the only attributes that show up for me

upbeat otter
#

Dpy also has the same attrs

slate swan
#

their whole bot is this

lethal drift
slate swan
#

yeah it doesn't say

lethal drift
#

And what is it that you're attempting?

slate swan
upbeat otter
#

Use owner_ids instead of owners lmao
It'll work

slate swan
#
    async def backup(self, ctx, include_all_channels=False):
        try:
            permissions = {}
            categories = ctx.guild.categories
            channels = ctx.guild.channels if include_all_channels else ctx.guild.text_channels

            for category in categories:
                permissions[category.name] = {
                    'id': category.id,
                    'type': 'category',
                    'overwrites': [
                        {
                            'id': str(target.id),
                            'name': str(target),
                            'type': str(type(target)),
                            'role_name': str(target.name) if isinstance(target, discord.Role) else None,
                            'permissions': permission_pair.to_dict()
                        } for target, permission_pair in category.overwrites.items()
                    ]
                }

            for channel in channels:
                permissions[channel.name] = {
                    'id': channel.id,
                    'category': channel.category.name if channel.category else None,
                    'type': str(channel.type),
                    'overwrites': [
                        {
                            'id': str(target.id),
                            'name': str(target),
                            'type': str(type(target)),
                            'role_name': str(target.name) if isinstance(target, discord.Role) else None,
                            'permissions': permission_pair.to_dict()
                        } for target, permission_pair in channel.overwrites.items()
                    ]
                }

         ```


Error: 
Something went wrong while backing up permissions: 'PermissionOverwrite' object has no attribute 'to_dict'
slate swan
vocal snow
upbeat otter
vocal snow
#

so you cannot call permission_pair.to_dict()

lethal drift
slate swan
#

okay there is a config file

#

which you put everything in

upbeat otter
#

You have to use IDs for storing owners right
You cannot put User objects into the json

slate swan
#

it takes stuff from here

#

and uses it in the code

vocal snow
#

change the logging and make it log the whole traceback next time

lethal drift
#

change bot.owners to bot.owner_ids wherever the command is being called

slate swan
#

bot.owner_ids or bot.owner-ids?

upbeat otter
#

_

lethal drift
#

underscore

upbeat otter
#

I literally said the same thing 5 minutes ago

lethal drift
#

can you even use '-' in function names? thinkCat

upbeat otter
#

💀

#

Why not 😳

slate swan
lethal drift
vocal snow
upbeat otter
slate swan
lethal drift
slate swan
upbeat otter
slate swan
#

it's not my bot

vocal snow
upbeat otter
vocal snow
#

permission_pair is a PermissionOverwrite object which doesn't have a to_dict method

autumn granite
#

@WOLF 07#0007

lethal drift
#

This must be a bot that you found on github to use then?

slate swan
#

no

autumn granite
#

@turbid condor

lethal drift
#

I'm so confused then lmao

slate swan
#

they gave me the bot's code to host it myself

#

because of past events between us so we parted ways

turbid condor
#

?

autumn granite
#

Can u tell me what's this

lethal drift
autumn granite
turbid condor
#

the whole file

lethal drift
#

i don't know your code..

upbeat otter
turbid condor
#

!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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

autumn granite
turbid condor
#

paste it here and share the link

lethal drift
#

We can't help with what we can't see

lethal drift
#

no one is trying to steal your stuff

slate swan
#

remove the brackets from the bot.command decorator wawa

vocal snow
#

i am going to steal it 👿

turbid condor
#

we need to see what you are doing

lethal drift
#

Shhhh

sick birch
#

thought I was a magic electric rock wizard :(

naive briar
#

What is happening

vocal snow
lethal drift
sick birch
#

is all that matters

lethal drift
#

Also I finally got my slash commands working for my lil test package!

#

One step further to world domination

turbid condor
#

btw any one knows how to import a command from another file inside a cog?

sick birch
#

Or add the other command into a cog and load it from there

turbid condor
#

the cog is getting pretty big

#

with all the commands in the cog

sick birch
#

Did you already break up all the commands into individual cogs?

naive briar
#

All!?

sick birch
#

Or do you just have one big cog

naive briar
sick birch
#

Yeah it might be time to consider refactoring

lethal drift
#

Ah, the days before I knew python and was copying from github

slate swan
#

have 1 command per cog like me wawa

smoky sinew
sick birch
#

Though they're often used in conjunction

smoky sinew
#

files are loaded with extensions

smoky sinew
sick birch
#

Yeah the "one cog per extension" is maybe a bit too Java-ish for my liking

turbid condor
# sick birch Or do you just have one big cog

I have commands in different cogs but they all belong to same category so I was thinking if there is a way to somehow import the command inside a single heading like when I use help command it should show like

Fun Commads:
command1
command2

Moderation:
command3
command4
vocal snow
lethal drift
#

I never understood the difference from:
bot.add_cog
bot.load_exstention

#

I always used the first-

sick birch
#

An extension is a collection of cogs pretty much

#

And a cog is a collection of commands and listeners and state

vocal snow
#

extensions can be used without any cogs involved though

sick birch
turbid condor
#

yeah

sick birch
#

Mmm

slate swan
#

each command has a Cog attribute

turbid condor
#

i am thinking of making a select menu with the help command

sick birch
#

Yeah you should just break it down more

#

There shouldn't be any need for sub-sub-categories

lethal drift
#

I've always hated that default help embed-
every new bot instance

bot(help_command=None)

#

and just make my own-

slate swan
#

there was no bot.owners in the code

lethal drift
slate swan
#

nope

lethal drift
#

This seemed like the common factor to when it had an error

vocal snow
slate swan
#

yes that's the commad I am trying to use

lethal drift
#

What's the code for that command?

#

also when did discord start having tags like that? lmao

slate swan
sick birch
slate swan
#

no

sick birch
#

Hmmm

vocal snow
#

their code sets that attribute manually

lethal drift
#

If so I'll just go look at the github

slate swan
#

yes it's all on the github

#

the only thing you change is the config json

#

I believe they are using the same exact code?

#

so it works I guess

lethal drift
autumn granite
lethal drift
#

to print error

turbid condor
#

if we can't see the code

lethal drift
#

what's against tos?

autumn granite
#

@turbid condor check dm onc

turbid condor
#

zzz just share it here

slate swan
autumn granite
buoyant quail
#

Sharing your code is not against tos pithink

lethal drift
#

Bro, literally no one wants it that bad. Either you need help or not

autumn granite
lethal drift
#

What-

#

what are you trying to do

#

self-bot?

autumn granite
#

embeds are patched what use

buoyant quail
#

Ahh, understood

autumn granite
#

I'm making an automatic tool

#

for something can't tell

slate swan
slate swan
#

so why is it working for the owner

#

I am confused

autumn granite
#

@lethal drift @buoyant quail so could anyone of u help me?

buoyant quail
# autumn granite

Your bot is a GroupMixin object, is that expected? It's usually a client or a bot

lethal drift
#

@slate swan

slate swan
#

can I make client.owners exist in this?

naive briar
lethal drift
#

changed that

slate swan
#

okay I see

buoyant quail
#

You redefined it somewhere it seems

slate swan
naive briar
#

Disaster

slate swan
#

their client is a Bot object, it's just poorly-named

buoyant quail
#

It would say Client.command in the error then, or i am mistaken?

slate swan
#

I am just trying to use the fwtarchive command

lethal drift
#

just replace owners with owner_ids

slate swan
#

there is no owners in fwtarchive command

#

oh nevermind

#

so like this

#

I did not work 😢

#

okay I will try to define client.owners

#
    async def backup(self, ctx, include_all_channels=False):
        try:
            permissions = {}
            categories = ctx.guild.categories
            channels = ctx.guild.channels if include_all_channels else ctx.guild.text_channels

            for category in categories:
                permissions[category.name] = {
                    'id': category.id,
                    'type': 'category',
                    'overwrites': [
                        {
                            'id': str(target.id),
                            'name': str(target),
                            'type': str(type(target)),
                            'role_name': str(target.name) if isinstance(target, discord.Role) else None,
                            'permissions': permission_pair.to_dict()
                        } for target, permission_pair in category.overwrites.items()
                    ]
                }

            for channel in channels:
                permissions[channel.name] = {
                    'id': channel.id,
                    'category': channel.category.name if channel.category else None,
                    'type': str(channel.type),
                    'overwrites': [
                        {
                            'id': str(target.id),
                            'name': str(target),
                            'type': str(type(target)),
                            'role_name': str(target.name) if isinstance(target, discord.Role) else None,
                            'permissions': permission_pair.to_dict()
                        } for target, permission_pair in channel.overwrites.items()
                    ]
                }

         ```


Error: 
Something went wrong while backing up permissions: 'PermissionOverwrite' object has no attribute 'to_dict'
buoyant quail
#

It was already answered here.
You are doing permission_pair.to_dict()
But there is no such method, we don't know what you expect it to be

slate swan
#

I don't know how to define it 😭

smoky sinew
slate swan
#

I don't think that's how I was supposed to define owners

#

I changed client.owners to owner_id and it didn't respond when I said the command

smoky sinew
#

what do you need owners for at all

#

just do @commands.is_owner()

#

and override is_owner or something

smoky sinew
slate swan
#

what is this

#

muh id

slate swan
#

I just want to execute the command that's it

#

can I just delete that whole section?

smoky sinew
#

then why'd you include that part in the first place

slate swan
#

I said it's not my bot

#

I am just trying to use a specfic command of this bot

#

and I was given this code by the owner

slate swan
#

I'm just going to delete that section I guess

#

it's evil

#

not even responding to me now

vocal snow
#

that isn't valid python

slate swan
#

why was this in the code 😭

slate swan
#

WHAT 😭

#

now it's saying client is not defined

smoky sinew
#

they're two different things

slate swan
smoky sinew
#

yes

#

the __init__ function has a scope function so you cannot use variables defined in that function outside of it

slate swan
#

hmm

smoky sinew
#

what's confusing about it, the bot already uses self.client

shy basin
#
    @commands.command(hidden=True)
    async def update(self, ctx, key, *, value):
        with open("prices.json", "r") as f:
            data = json.load(f)
        data[str(key)] = str(value)
        with open("prices.json", "r+") as f:
            json.dump(data, f, indent=1)
        await ctx.reply(f"New data:\n{data[str(key)]}")

shorter example of prices.py

{
    "book": "3,000",
    "pen": "2,000"
}
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/bot.py", line 347, in invoke
    await ctx.command.invoke(ctx)
  File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 187, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an
exception: JSONDecodeError: Extra data: line 49 column 3 (char 1372)

i want to update an item price in different json files, first execution always making the json files a mess, so the second execution not gonna work, how i solve it?

slate swan
smoky sinew
#

just remove the entire line and use @commands.is_owner()

slate swan
#

I defined it the same way in other parts of the code

smoky sinew
slate swan
smoky sinew
#

again that's a different part of the code

slate swan
#

ah okay

smoky sinew
#

and delete the other owner lines in the command

slate swan
#

nope

#

there's just something wrong with client

smoky sinew
#

no there isn't

slate swan
#

I just like reset it and did what you said and it still gives the error

smoky sinew
#

show your code and the error

slate swan
smoky sinew
#

you replaced something else though

#

@commands.command(hidden=True) add this back

slate swan
smoky sinew
slate swan
#

oh well

smoky sinew
#

where did you get this code

slate swan
#

someone made it and gave me the code

#

they not good at this so it hs errors

#

there's a github link

smoky sinew
#

are you only trying to use one feature?

slate swan
#

yes

#

just the fwtarchive one

smoky sinew
#

what's that do

#

archive channel messages?

slate swan
#

yes deletes all of them

#

sends them in another server

smoky sinew
#

ah

slate swan
#

the thing is their bot is up right now

#

but for some reason their code isn't working for me

smoky sinew
#

one sec

slate swan
#

more errors

formal basin
#
async def rps(interaction: discord.Interaction, rps: str):``` how can i make an if statement so if rps isn't a certain word
#

e.g if rps is gun i want the bot to say you can only chose rock paper and scissors

smoky sinew
#
rps: Literal["rock", "paper", "scissors"]
#

imported from typing

formal basin
#

ok

#

thanks

formal basin
smoky sinew
#

wdym

#

it will raise an error

formal basin
#

oh ok

smoky sinew
#

actually i don't know if that applies for app commands

slate swan
#

I don't think the archive command could work on itself right

smoky sinew
#

it could

slate swan
#

oh okay

#

what do I change that to since discord limit is 25mb

#

what is this based on

smoky sinew
#

it's in bytes

slate swan
#

oh okay

smoky sinew
#

@slate swan check your dms

silent ridge
#

does anyone know how I can turn this off

#

that this pops up in my screen the whole time

formal basin
#
bot_answers = ["rock", "paper", "scissors"]
  user_answers= rps

  await interaction.send_message(random.choice(bot_answers))
  if bot_answers == "rock":
    if user_answers == "rock":
      await interaction.channel.send(f"{interaction.user.mention} we both used rock so it is a draw")``` what should the bot_answers be?
#

is it client?

onyx forge
silent ridge
onyx forge
silent ridge
#

its annoying, comes in my screen the whole time can't even see what I write as it stays on my screen

silent ridge
onyx forge
#

go to ide settings

#

and select editor | inspection

#

locate the inspection you want to disable

#

and clear the check mark

#

apply changes and boom ur done

silent ridge
onyx forge
silent ridge
#

got it

onyx forge
silent ridge
#

Still got it while I disabled python, hmm w8

onyx forge
#

go to file > settings

silent ridge
onyx forge
#

editor

#

smart keys

#

insert self or something i think

#

but i think

#

smart keys is in general now

#

search for it

silent ridge
#

yes got that

onyx forge
silent ridge
#

I have done it @onyx forge

#

thanks for your support <3

onyx forge
#

happy to help :)

shy basin
#
    @commands.command(hidden=True)
    async def update(self, ctx, key, *, value):
        with open("prices.json", "r") as f:
            data = json.load(f)
        data[str(key)] = str(value)
        with open("prices.json", "r+") as f:
            json.dump(data, f, indent=1)
        await ctx.reply(f"New data:\n{data[str(key)]}")
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/bot.py", line 347, in invoke
    await ctx.command.invoke(ctx)
  File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 187, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an
exception: JSONDecodeError: Extra data: line 49 column 3 (char 1372)

i want to update an item price in different json files, first execution will add an extra curly or existed key value pairs copy, so the second execution not gonna work, how i solve it?

slate swan
#

We don't need the shorter example, we need the line 49 column 3 as the error says

shy basin
# slate swan We don't need the shorter example, we need the line 49 column 3 as the error say...

{ "power_relic": "5,000 ~ 6,000", "nature_relic": "5,000 ~ 6,000", "fire_relic": "7,000 ~ 8,000", "damage_relic": "7,000 ~ 8,000", "leeching_relic": "4,000 ~ 5,000", "ice_relic": "3,000 ~ 4,000", "magic_ore": "3,5000 ~ 4,000", "crim_bar": "15,000 ~ 20,000", "mythan_bar": "60,000 ~ 80,000", "gold_bar": "600,000", "cobalt_bar": "80,000 ~ 90,000", "varax_bar": "120,000 ~ 140,000", "magic_bar": "50,000 ~ 55,000", "dclaw": "14m ~ 18m", "dhorn": "500,000 ~ 700,000", "deye": "18m ~ 20m", "rage_sliver": "8m", "disdain_sliver": "12m", "corrupt_sliver": "13m", "torment_sliver": "14", "nleg": "50m ~ 55m", "neye": "2m" } "disdain_sliver": "12m", "corrupt_sliver": "13m", "torment_sliver": "14", "nleg": "50m ~ 55m", "neye": "2m" }
before the first execution, there is no multiple "disdain"

sick coyote
#

is nextcord-ext-ipc fast and good for a discord dashboard, or should i use another one?

slate swan
#

There you go, now you see your JSON is invalid

shy basin
#

yeah, and that's because the command

#

there is something wrong in the command, i just doing !update dhorn 1m ~ 2m

slate swan
#

!pypi nextcord-ext-ipc

unkempt canyonBOT
vale wing
#

I think we just encountered real notepad user

hollow haven
#

Hello, how to retrieve the id of a person with his @?

stiff herald
#

why channel.connect never return?

 vc = ctx.voice_client
        
 if vc:
  if vc.channel.id == channel.id:
    return
  try:
   await vc.move_to(channel)
  except asyncio.TimeoutError:
    raise VoiceConnectionError(f"Moving to channel: <{channel}> timed out.")
            
  else:
  try:
    await channel.connect(self_mute=True)
  except asyncio.TimeoutError:
    raise VoiceConnectionError("f'Connecting to channel: <{channel}> timed out.")

await ctx.send(f'**Joined `{channel}`**')
``` (discord.py)
stiff herald
thin raft
keen moat
#

!e discord.Client

#

!e discord.Client

unkempt canyonBOT
#

@keen moat You've already got a job running - please wait for it to finish!

buoyant quail
#

You destroyed it

keen moat
#

bruh

buoyant quail
#

That's a wrong channel btw #bot-commands

keen moat
#

its not gonna stop

buoyant quail
#

yeah

keen moat
#

actually i wanted to search for discord.Client but then commands.Bot popped up in my head and i kinda mixed it WhenLifeGetsAtYou

buoyant quail
#

!d for search

#

!d discord.Client

unkempt canyonBOT
#

class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

async with x Asynchronously initialises the client and automatically cleans up.

New in version 2.0.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
#

Sorry, an unexpected error occurred. Please let us know!

TimeoutError:

wise jewel
#

seems like it timed out while trying to add the trashcan reaction

hollow osprey
#

!d discord.Client

unkempt canyonBOT
#

class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

async with x Asynchronously initialises the client and automatically cleans up.

New in version 2.0.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
hot cobalt
#

we'll chalk it up to cosmic rays

slate swan
#

how to delete messagez

unkempt canyonBOT
#

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

Deletes the message.

Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages").

Changed in version 1.1: Added the new `delay` keyword-only parameter.
verbal shuttle
#

Hi is there a rule somewhere that says the bot has to be running24-7-365?

verbal shuttle
#

yes, i have been told (not sure how true it is) that a bot can not be down and has to be running that time period.

potent spear
#

or else what?

verbal shuttle
#

was told that we could get in trouble with discord devs if its not running and that they can shut our accounts down ( not sure if the person was saying this as a scare tactic, not sure how much truth if any this holds)

slate swan
#

kek obviously completely wrong

potent spear
#

check your sources I'd say

verbal shuttle
#

glad I asked here, thank you for letting me know they were not being truthful.

potent spear
#

but yeah, this is blatantly false and doesn't even make sense
as when you're updating commands or whatever, your bot has to restart 🤷‍♂️

sick coyote
#

guys what is a role select menu

glad cradle
#

Well it's a select menu where users can select roles

sick coyote
naive briar
sick birch
#

!d discord.ui.RoleSelect

unkempt canyonBOT
#

class discord.ui.RoleSelect(*, custom_id=..., placeholder=None, min_values=1, max_values=1, disabled=False, row=None)```
Represents a UI select menu with a list of predefined options with the current roles of the guild.

Please note that if you use this in a private message with a user, no roles will be displayed to the user.

New in version 2.1.
glad cradle
#

no i fucked up 😞

sick birch
#

It uses all the roles in the current guild

#

Which is unfortunate

sick coyote
smoky sinew
#

send_modal(RoleView())

#

can you spot the problem here

sick coyote
#

ohhhh

#

yeah could be the problem

#

select as modal

smoky sinew
#

view as modal*

sick coyote
#

the role select is pretty nice

#

never seen someone using it

slate swan
#

I think most people use a regular select menu and just pass in role IDs themselves

formal basin
#

how can i space out stuff in an embed

slate swan
#

What do you mean by space stuff out

formal basin
#

like paragraphs

slate swan
#

Make use of embed fields

#

!d discord.Embed.add_field

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.
formal basin
# slate swan Make use of embed fields
 embed = discord.Embed(title="Here is some information about the bot", description="This bot can generate numbers. I have some of commands. Made by zagzag990#0482", color=discord.Color.random())
     embed.add_field(name= "member count:", value = f"```{len(client.users)}```") 
     embed.add_field(name= "server count:", value = f"```{len(client.guilds)}```")
     embed.add_field(name="", value="This bot can send random numbers using the random-number command you choose a from number to number e.g 1 10 would send a random number from 1 to 10")
     embed.add_field(name="", value="This bot has some moderation commands like kick and clear. kick kicks a member the command only shows for people with the kick member permission. Clear purges messages only shows for people with manage messages. mute and unmute which mutes/timeout users only shows for people with the manage messages permission")
     ``` on moblile theres no paragraphs
smoky sinew
#

can't you just use \n

formal basin
formal basin
smoky sinew
#

\n or /n

smoky sinew
sick coyote
#

does someone know how this emoji is called

formal basin
#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
slow fog
#

any clue on how you may scrap the message content from an embed

smoky sinew
#

and you cannot change it

smoky sinew
#

!d discord.Embed.description

unkempt canyonBOT
#

The description of the embed. This can be set during initialisation. Can only be up to 4096 characters.

sick coyote
#

thats why i needed it as an emoji

slow fog
formal basin
#
@client.tree.command(name="avatar", description="shows someone's avatar")
async def avatar(interaction: discord.Interaction, user: discord.Member=None):
  if user == None:
    user = interaction.author

  embed = discord.Embed(title=f"{user}'s avatar", url=user.avatar_url)
  await interaction.response.send_message(embed=embed)```
#
  File "/home/runner/zagzag/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/zagzag/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/zagzag/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 860, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'avatar' raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'```
#

how can i fix this

smoky sinew
#

like i just said

slow fog
#

that's why i'm asking

smoky sinew
formal basin
shrewd apex
#

display_avatar ideally

slow fog
#

is there a possible way to scrap its description or its fields

smoky sinew
shrewd apex
unkempt canyonBOT
smoky sinew
#

you can use message.embeds to get a list of embeds on the message

#

there can be up to 10 embeds i think

formal basin
slow fog
shrewd apex
shrewd apex
#

gives a list of embed objects if present

slow fog
smoky sinew
slow fog
#

yeah bruh

formal basin
#

how can i get the image to show on the embed?

smoky sinew
upbeat otter
unkempt canyonBOT
#

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

This function returns the class instance to allow for fluent-style chaining.
slate swan
young dagger
#

Which one should I use the first or second one?

member = ctx.author
users_queue.append({"member": member})```
1. ```python
        staff_ids = [710241598348329080, 710242627089596459, 727152007009271822, 849018401300938832]
        staff_members = [user['member'] for user in users_queue if
                         any(role.id in staff_ids for role in user['member'].roles)]
        if staff_members:
            lobby_creator = random.choice(staff_members).mention
        else:
            random_user = random.choice(users_queue)
            lobby_creator = random_user['member'].mention```
2. ```python
        staff_ids = [710241598348329080, 710242627089596459, 727152007009271822, 849018401300938832]
        staff_members = [member for member in users_queue if any(role.id in staff_ids for role in member['member'].roles)]
        if staff_members:
            lobby_creator = random.choice(staff_members)['member'].mention
        else:
            random_user = random.choice(users_queue)
            lobby_creator = random_user['member'].mention```
#

staff_members = [user['member'] for user in users_queue if any(role.id in staff_ids for role in user['member'].roles)] or staff_members = [member for member in users_queue if any(role.id in staff_ids for role in member['member'].roles)]

potent spear
young dagger
potent spear
#

also, make sure it's lobby_creator_mention

potent spear
young dagger
potent spear
#

you'd have no idea what a lobby_creator is without looking at its initialization

slate swan
#

So when I set a global variable in a form so it can appear in message that will be called later for person A, if Person B uses the bot at the same time they can change that global variable by filling out their form so person A accidentally receives person B results, how do I work around this so nothing gets mixed up

#
  1. Don't use global variables as they are shit
  2. Use max_concurrency
  3. Make some sort of dictionary global variable that maps user ID -> data
young dagger
slate swan
#

And that's what max_concurrency does, ggs

#

Either way don't use global variables, doesn't seem necessary for their use case either. And if you do, then choose a proper type for that global variable e.g. a dictionary which maps ID with data as you won't overwrite the data of the other users

slate swan
#

What about events?

young dagger
#

Sometimes it saying "3 players are currently in the queue" (x2) twice, when in reality there is 2 players in the queue

@client.event
async def on_voice_state_update(member, before, after):
    if (before.channel and before.channel.id in [712072729406472374]) and (after.channel is None or (after.channel and after.channel.id not in [712072729406472374])):

        # Check if the member is in the users_queue
        for user in users_queue:
            if user['member'] == member:
                users_queue.remove(user)
                channel = client.get_channel(712074759453671494)
                embed = discord.Embed(title=f"1 player is currently in the queue" if len(
                    users_queue) == 1 else f'{len(users_queue)} players are currently in the queue',
                                      description=f'{member.mention} has left the queue.',
                                      timestamp=datetime.datetime.now(), color=discord.Color.red())
                await channel.send(embed=embed)
                return```
#

When two users leave the queue simultaneously

slate swan
#

Sounds completely unrelated to their questions

swift gull
#

basically the logic is to transfer the audio from the website to the discord bot in the app's voice channel using selenium, ffmpeg and pydub in real time 24/7. most of the time i tried to run the code i got this error message:[WARNING ] discord.gateway: Shard ID None heartbeat blocked for more than 10 seconds.

slate swan
#

Because whatever you're doing is blocking the entire bot and not being run asynchronously

#

(For quite some time as it doesn't respond to heartbeat requests from Discord)

swift gull
#

im a beginner, do you have any tips?

glad cradle
#

!d asyncio.loop.run_in_executor you can use this to run blocking code

unkempt canyonBOT
#

awaitable loop.run_in_executor(executor, func, *args)```
Arrange for *func* to be called in the specified executor.

The *executor* argument should be an [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor "concurrent.futures.Executor") instance. The default executor is used if *executor* is `None`.

Example:
opal raft
#

can someone help me fix thispy @bot.command(name="blacklist_bots", description="Blacklists bots in a certain channel") async def blacklist_bots(ctx, channel: discord.TextChannel): if ctx.author.guild_permissions.administrator: bots = [member for member in channel.members if member.bot] default_role = ctx.guild.default_role for bot_member in bots: await bot_member.add_roles(default_role) await ctx.send(f"{len(bots)} bots have been blacklisted in {channel.mention}.") else: await ctx.send("You must be an administrator to use this command.")

young dagger
#

@slate swan Is it recommended to use asyncio.Lock on voice events?

slate swan
#

Don't know, don't use Python

slate swan
#

Why do you add the default role though, everyone already has it..

opal raft
slate swan
#

Well what you're doing doesn't make sense in the first place

#

You're adding the role @everyone to all bots

#

Although that role is already in fact given to everyone and can't be removed

opal raft
#

well i tied with a custom role aswell still sameproblem

#

tried*

slate swan
#

Then change your code to use a custom role, then come back with that code and potential errors, also add logging

opal raft
#

@bot.command(name="blacklist_bots", description="Blacklists bots in a certain channel")
async def blacklist_bots(ctx, channel: discord.TextChannel, role: discord.Role):
if ctx.author.guild_permissions.administrator:
bots = [member for member in channel.members if member.bot]
for bot_member in bots:
await bot_member.add_roles(role)
await ctx.send(f"{len(bots)} bots have been blacklisted in {channel.mention}.")
else:
await ctx.send("You must be an administrator to use this command.")

unkempt canyonBOT
#
Formatting code on discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

formal basin
#
  File "/home/runner/zag-bot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 842, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 118, in warn
    await open_account(user)
  File "main.py", line 177, in open_account
    db[str(user.id)]["warns"] = 0
  File "/home/runner/zag-bot/venv/lib/python3.10/site-packages/replit/database/database.py", line 439, in __getitem__
    raw_val = self.get_raw(key)
  File "/home/runner/zag-bot/venv/lib/python3.10/site-packages/replit/database/database.py", line 479, in get_raw
    raise KeyError(key)
KeyError: '852572272711303248'

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

Traceback (most recent call last):
  File "/home/runner/zag-bot/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/zag-bot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/zag-bot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 860, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'warn' raised an exception: KeyError: '852572272711303248'
#
async def open_account(user):

  if str(user.id) in db:
    return False
  else:
      db[str(user.id)]["warns"] = 0
      
      return True```
#

idk why it is raising this error

potent spear
#

seems like your user id isn't in the db

formal basin
#

so it checks

potent spear
#

which you think does what exactly?

formal basin
potent spear
#

it's english though

#

in short, I don't think you can add nested dicts in that db

#

maybe try

db[str(user.id)] = {"warns":0}```
instead
not sure, I don't work with (bad) hosts like replit
formal basin
#

ok

potent spear
#

gl hf

formal basin
#

what does that slang mean?

potent spear
#

good luck have fun

formal basin
#

oh ok

#

thanks btw

swift gull
# unkempt canyon

how do i use this, i tried it in different ways and i keep getting the same error

young dagger
#

Why am I getting this error and how do I fix it?
RuntimeError: Task <Task pending name='discord.py: on_voice_state_update' coro=<Client._run_event() running at C:\Users\Gamer\Downloads\blitzcrank\venv\lib\site-packages\discord\client.py:441>> got Future <Future pending> attached to a different loop

@client.event
async def on_voice_state_update(member, before, after):
    if (before.channel and before.channel.id in [712072729406472374]) and (after.channel is None or (after.channel and after.channel.id not in [712072729406472374])):

        # Check if the member is in the users_queue
        for user in users_queue:
            if user['member'] == member:
                await queue_lock.acquire()  # waits until the lock is unlocked, and locks it
                users_queue.remove(user)
                channel = client.get_channel(712074759453671494)
                embed = discord.Embed(title=f"1 player is currently in the queue" if len(users_queue) == 1 else f'{len(users_queue)} players are currently in the queue',
                                      description=f'{member.mention} has left the queue.',
                                      timestamp=datetime.datetime.now(), color=discord.Color.red())
                await channel.send(embed=embed)
                queue_lock.release()  # unlocks the lock
                return```
#

It's something with the lock

young dagger
formal basin
#

so its not a variable

young dagger
formal basin
#

so maybe why

young dagger
formal basin
#

where tho

#

its not in your code

#
@client.tree.command(name="warn", description="warn someone (moderator only)")
@discord.app_commands.checks.has_permissions(manage_messages=True)
@app_commands.default_permissions(manage_messages=True)
async def warn(interaction: discord.Interaction, user: discord.User):
  await open_account(user)


  warns_amt = db[str(user.id)]

  warns = 1


  db[str(user.id)] += warns

   
  

  await interaction.response.send_message(f"{user.mention} has been warned.")

  duration2 = datetime.timedelta(hours=2)
  duration = datetime.timedelta(hours=1)
  embed = discord.Embed(title="User muted", description=f" {user.mention} has been muted", color=discord.Color.blue())
  embed.add_field(name = "Reason",value = f"Got {warns_amt} warnings")
  embed.add_field(name = "Mute duration",value = "1 hour")
  embed2 = discord.Embed(title="User muted", description=f" {user.mention} has been muted", color=discord.Color.blue())
  embed2.add_field(name = "Reason",value = f"Got {warns_amt} warnings")
  embed2.add_field(name = "Mute duration",value = "2 hours")
  serverlog = client.get_channel(993925329901068391)
  

  if warns_amt == 3:
    await user.timeout(duration)
    await serverlog.send(embed=embed)

  if warns_amt == 6:
    await user.timeout(duration2)
    await serverlog.send(embed=embed2)

  if warns_amt > 6:
    await user.timeout(duration2)
    await serverlog.send(embed=embed2)

``` the if statements on the bottom like e.g the first one saying if warns_amt is 3 but it only triggers at 4 and in the embed it says 3
swift gull
potent spear
lost lichen
#

Hi, im having an issue where my bot connects to the voice channel, but then hangs immediately..

    @commands.slash_command(description="Join a voice channel and speak the text")
    async def speak(self, inter, voice:Voices, text: str):
        await inter.response.defer(ephemeral=False)
        voice_channel = inter.author.voice.channel
        if voice_channel is None:
            await inter.response.send_message("You are not connected to any voice channel.")
            return
        print(f'user is in voice channel {voice_channel.name}')
        print(f"Connecting to voice channel: {voice_channel.name}")
        vc = await voice_channel.connect()
        print(f"Connected to voice channel: {voice_channel.name}")
        print(f"Setting voice to: {voice}")
        self.speech_config.speech_synthesis_voice_name = voice
        print(f"Voice set to: {voice}")

The console prints user is in voice channel General and Connecting to voice channel: General, but then doesnt print anything else, im super stumped as to why, the bot has all permissions (I even granted administrator just in case) the application has the connect and speak scopes enabled, and the bot successfully connects to the voice channel, but doesnt do anything else..

#

i have PyNaCl installed, as well as FFmpeg

lost lichen
#

no, all other commands still function

#

i also put a try except block around the connection, but it doesnt raise anything

potent spear
#

sorry, I can't really answer if it's about forked libraries of dpy

#

as I'm not using any of those

lost lichen
#

hmm ok, been meaning to migrate to dpy, will do that and see if the issue still persists

swift gull
# potent spear what are we looking at here?

the bot is not playing the audio from the radio, selenium fulfills its role and plays the audio only for me, there is some problem when the audio stream must be sent to the discord server

#

i tried pydub and ytbdl

slate swan
#

yes i have found my people, except im very new to this since the last bot i coded was 2018

quaint epoch
#

Mhm

#

Last one for me was before the mandatory slash commands

slate swan
#

so im making a bot with commands and the commands ran fine before i implemented cogs to keep my code looking cleaner

quaint epoch
#

!traceback

unkempt canyonBOT
#
Traceback

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

A full traceback could look like:

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

If the traceback is long, use our pastebin.

slate swan
#

okay let me rerun my command in my server rq

#
import discord
from discord.ext import commands, tasks
from itertools import cycle
import os
import asyncio


from keep_alive import keep_alive
keep_alive()

client = commands.Bot(command_prefix=",", intents=discord.Intents.all(), help_command=None)


bot_status = cycle(["mercy", "and", "lucki", "run", "this", "shit"])

async def load():
  for filename in os.listdir("./cogs"):
    if filename.endswith(".py"):
        await  client.load_extension(f"cogs.{filename[: -3]}")

async def main():
  async with client:
    await load()
    await client.start("your_token")


@client.event
async def on_ready():
    print("/SwatSec is ready.")
    change_status.start()

@tasks.loop(seconds=2)
async def change_status():
    await client.change_presence(activity=discord.Game(next(bot_status)), status=discord.Status.dnd)

@client.event
async def on_member_join(member):
    print(f"Member joined: {member}")

    welcome_channel_id = 1116923452918607894  # Replace with your welcome channel ID
    welcome_channel = client.get_channel(welcome_channel_id)
    
    embed = discord.Embed(title="+1", description=f"welcome to comm {member.mention}")
    embed.set_thumbnail(url=member.avatar_url)
    embed.add_field(name="", value=":emoji1:")
    embed.add_field(name="", value=":emoji2:")

    await welcome_channel.send(embed=embed)```
#

i broke it @quaint epoch

turbid condor
#

Instead change it after 5 or 10 min

slate swan
twilit grotto
#

and also, its client.run, i dont know 100% if .start exists, never used it or seen it before but i may be wrong

wispy geode
#

Been a while since ive made a bot

#

Running this code and I get this error

#

bot = commands.Bot(command_prefix="!")
TypeError: init() missing 1 required keyword-only argument: 'intents'

twilit grotto
slate swan
twilit grotto
#

then you aren't running your main function, use asyncio to run your main function

slate swan
#

how would i go about that

twilit grotto
#

use the asyncio module which you've already imported

turbid condor
#

!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 "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 "discord.Client").

New in version 1.5.
swift gull
#

im not able to transmit the audio stream from the radio website to the bot to play on discord, I've already tried using pydub and youtube_dl, I'm tired of trying with chatgpt/google/stackoverflow I can't take it anymore, anyone heeeeelp meeeeeeeeeeee

slate swan
twilit grotto
unkempt canyonBOT
#

asyncio.run(coro, *, debug=None)```
Execute the [coroutine](https://docs.python.org/3/glossary.html#term-coroutine) *coro* and return the result.

This function runs the passed coroutine, taking care of managing the asyncio event loop, *finalizing asynchronous generators*, and closing the threadpool.

This function cannot be called when another asyncio event loop is running in the same thread.

If *debug* is `True`, the event loop will be run in debug mode. `False` disables debug mode explicitly. `None` is used to respect the global [Debug Mode](https://docs.python.org/3/library/asyncio-dev.html#asyncio-debug-mode) settings.

This function always creates a new event loop and closes it at the end. It should be used as a main entry point for asyncio programs, and should ideally only be called once.

Example...
slate swan
slate swan
twilit grotto
turbid condor
#

What is the rate limit of changing the channel name??

#

I know for messages it's 50 per second

sick birch
turbid condor
#

Hmm

slate swan
#

RuntimeWarning: coroutine 'sleep' was never awaited
asyncio.sleep(3)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

#

FGIX?

twilit grotto
slate swan
vale wing
sick birch
vale wing
slate swan
#

Was gonna say, 50 messages per second seems way too high

vale wing
#

Youtubers when they make everyone ping in general chat of 100k+ server and accidentally cause API latency jump to 60 seconds

slate swan
#

i need some help combining code togethter

#

Who can give a hand

turbid condor
formal basin
#
@client.tree.command(name="warn", description="warn someone (moderator only)")
@discord.app_commands.checks.has_permissions(manage_messages=True)
@app_commands.default_permissions(manage_messages=True)
async def warn(interaction: discord.Interaction, user: discord.User):
  await open_account(user)
  warns_amt = db[str(user.id)]
  warns = 1
  db[str(user.id)] += warns
  await interaction.response.send_message(f"{user.mention} has been warned.")

  duration2 = datetime.timedelta(hours=2)
  duration = datetime.timedelta(hours=1)
  embed = discord.Embed(title="User muted", description=f" {user.mention} has been muted", color=discord.Color.blue())
  embed.add_field(name = "Reason",value = f"Got {warns_amt} warnings")
  embed.add_field(name = "Mute duration",value = "1 hour")
  embed2 = discord.Embed(title="User muted", description=f" {user.mention} has been muted", color=discord.Color.blue())
  embed2.add_field(name = "Reason",value = f"Got {warns_amt} warnings")
  embed2.add_field(name = "Mute duration",value = "2 hours")
  serverlog = client.get_channel(993925329901068391)
  if warns_amt == 3:
    await user.timeout(duration)
    await serverlog.send(embed=embed)

  if warns_amt == 6:
    await user.timeout(duration2)
    await serverlog.send(embed=embed2)

  if warns_amt > 6:
    await user.timeout(duration2)
    await serverlog.send(embed=embed2)```
#

the if statements on the bottom like e.g the first one saying if warns_amt is 3 but it only triggers at 4 and in the embed it says 3

wide vigil
#

Can anyone help ? When I click in the button it edited message but it doesn't play music.

wide vigil
#

I used discord.ui.button function

formal basin
wide vigil
#

yes

slate swan
#

Why use self.ctx when it's not a thing for buttons

#

Use interaction.something

wide vigil
#

Oh

#

Thanks, I will try

slate swan
#

Would be nice if you could remove those unnecessary blank lines, makes it harder to read

wide vigil
#

Tried but does nothing

slate swan
#

Doesn't help much if you don't share anything besides "not working"

wide vigil
#

Anyawy thanks

formal basin
#
@client.tree.command(name="warn", description="warn someone (moderator only)")
@discord.app_commands.checks.has_permissions(manage_messages=True)
@app_commands.default_permissions(manage_messages=True)
async def warn(interaction: discord.Interaction, user: discord.User):
  await open_account(user)
  warns_amt = db[str(user.id)]
  warns = 1
  db[str(user.id)] += warns
  await interaction.response.send_message(f"{user.mention} has been warned.")

  duration2 = datetime.timedelta(hours=2)
  duration = datetime.timedelta(hours=1)
  embed = discord.Embed(title="User muted", description=f" {user.mention} has been muted", color=discord.Color.blue())
  embed.add_field(name = "Reason",value = f"Got {warns_amt} warnings")
  embed.add_field(name = "Mute duration",value = "1 hour")
  embed2 = discord.Embed(title="User muted", description=f" {user.mention} has been muted", color=discord.Color.blue())
  embed2.add_field(name = "Reason",value = f"Got {warns_amt} warnings")
  embed2.add_field(name = "Mute duration",value = "2 hours")
  serverlog = client.get_channel(993925329901068391)
  if warns_amt == 3:
    await user.timeout(duration)
    await serverlog.send(embed=embed)

  if warns_amt == 6:
    await user.timeout(duration2)
    await serverlog.send(embed=embed2)

  if warns_amt > 6:
    await user.timeout(duration2)
    await serverlog.send(embed=embed2)```
#

the if statements on the bottom like e.g the first one saying if warns_amt is 3 but it only triggers at 4 and in the embed it says 3

#
async def open_account(user):

  if str(user.id) in db:
    return False
  else:
      db[str(user.id)] = 0
      
      return True
#

thats the open account thing

shy basin
#
    @commands.command(hidden=True)
    async def insert(self, ctx, tabel, kolom, value):
        self.cursor.execute(f"INSERT INTO {tabel} ({kolom}) VALUES ('{value}')")
        self.con.commit()
        self.con.close()
        await ctx.reply("Ok")
        
    @commands.command(hidden=True)
    async def select(self, ctx, table, column):
        data = self.cursor.execute(f"SELECT {column} FROM {table}")
        self.con.commit()
        for i in data:
            d = i
        await ctx.reply(d)
        self.con.close()

help? after i use the insert command then i use the select command

sqlite3.ProgrammingError: Cannot operate on a closed database.
#

is the close() method needed?

buoyant quail
#

If you are closing connection, then you need to create a new one

slate swan
#

Tell me you lock these commands to be owner-only and not just "hidden", especially whenever they're prone to SQLi

slate swan
unkempt canyonBOT
#
SQL & f-strings

Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.

Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.

For example, the sqlite3 package supports using ? as a placeholder:

query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)

Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.

See Also
Python sqlite3 docs - How to use placeholders to bind values in SQL queries
PEP-249 - A specification of how database libraries in Python should work

shy basin
#

that's was helpful

#

ty

lone robin
#

Hey guys !

So currently I’m having issues with trying to have my bot hosted through NovoNode. In my Main.Py file Import Interactions is tossing an error along with a few other things.

Have any of you used NovoNode in the past ? Do you recommend any other hosts ? Any information would be appreciated dearly !

slate swan
lone robin
#

@slate swan I haven’t no, I’m still learning python / was given bot files from a friend to tinker around with.

But that friend didn’t make them nor knows anything about Python/Bots

slate swan
#

try to locate terminal or command line on your host and install needed dependencies

warped vale
#

how to take a rss feed

#

and post it on my discord server

#

do I need a bot for that?

hollow haven
#

how i get url of person's avatar with id with bot?

buoyant quail
unkempt canyonBOT
buoyant quail
#

!d discord.User.avatar

unkempt canyonBOT
#

property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the user has.

If the user has not uploaded a global avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar "discord.User.display_avatar").
hollow haven
buoyant quail
#

no
you need to get the user with first method
and then his avatar.url attribute

hollow haven
#

how?

buoyant quail
#
bot.get_user(1046837060557873182).avatar.url
upbeat otter
#

that could raise errors
either NoneType has no attr url or NoneType has not attr avatar

#

since get_user and avatar atrrs can return None

slate swan
warm forum
#

anybody know how can i install ffmpeg on replit

turbid condor
#

U can check in packages if it's available there

upbeat gust
upbeat gust
upbeat otter
#

oh nvm 💀

thin raft
stark nexus
#

Anyone could help me with my bot?
It will come to vc when i enter command
Other also all worked fine
But it can't play music

merry cliff
#

!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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

stark nexus
polar hill
#

Does anyone know if I can get on python users connections info (for example my twitch name account shown in the image)

slate swan
#

No

#

hi

#

I had a bot made time ago, and now i had to update the constructor with something called intents. Idk what are the exactly, but i had to do weird things.

#
intents.members = True
intents.typing = True
intents.presences = True
intents.message_content = True```
#

Idk exactly what are they for

#

If i untick these options, my bot stops working

#

tho my bot is only on my server, so idk why

fluid rapids
hushed galleon
# slate swan I had a bot made time ago, and now i had to update the constructor with somethin...

https://discordpy.readthedocs.io/en/stable/intents.html#do-i-need-privileged-intents

An intent basically allows a bot to subscribe to specific buckets of events. The events that correspond to each intent is documented in the individual attribute of the Intents documentation.
for example if your bot tells discord that it wants to use the invites intent, discord will send an event anytime an invite is created/deleted
see also discord API's docs:
https://discord.com/developers/docs/topics/gateway#gateway-intents

slate swan
#

yeah so, idk what does this have to do with my bot

#

it only posts embed msgs

formal basin
#

how can stop errors from happineng in an event

slate swan
#

nothing else

hushed galleon
#

if you're using prefix commands (i.e. !hello-world or similar), then you typically need messages + message_content in order for it to work

formal basin
#

and msg content

slate swan
#

this is how i defined my methods

#

async def get(ctx: cmds.Context):

hushed galleon
#

i wouldnt bother setting members and presences in your case

slate swan
#

idk, i copied from stack XD

hushed galleon
slate swan
#

but why do i need the options on the discord portal? they are meant for "big" bots

#

mine isnt

hushed galleon
#

they're not meant for big bots at all

#

any bot that needs the events/data provided by those privileged intents will need to enable them

slate swan
#
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed```
hushed galleon
#

can you show the entire traceback(s)?

#

that error message is a common bug with windows, but the real error is somewhere above that

slate swan
#

maybe this

discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000002B1CDF0FD30>
Traceback (most recent call last):```
hushed galleon
#

and now its explained in the error message what you have to do

slate swan
#

yeah but, why exactly?

#

and how do i know which intents does my bot need?

hushed galleon
#

you disabled it in the dev portal, but your code is still asking for members/presences/message content intents: py intents.members = True intents.presences = True intents.message_content = True

slate swan
#
intents.typing = True
intents.message_content = True```
hushed galleon
#

typing is part of the default intents btw

slate swan
#

I removed the ones i sayed, but, why do i need this intents? cuz my bot wants to write? and embed = msg_content?

#

oh i think i remember sending embed on previous version was still something special, perhaps?

hushed galleon
#

its needed for your bot to see the content of most messages

#

if my bot cant read the content and i type !hello-world, it wont know that i tried using a command

#

(although discord will still provide content if you're DMing the bot or mentioning it)

slate swan
#

okey, so why isnt message_content true by default?

hushed galleon
#

because its a privileged intent

#

discord isnt guaranteed to allow your bot to use it
(or rather, discord disallows those intents by default until you enable it in the dev portal)

slate swan
#

but, why/what will a bot who cant read do? 😮

hushed galleon
#

they can still register slash commands

slate swan
#

intents.message_content = True is to allow the bot reading msgs, right?

slate swan
#

okey so i only need the third option, the msg content privilege

#

i get 2 info warnings
INFO discord.client logging in using static token INFO discord.gateway Shard ID None has connected to Gateway.

#

i believe the first one is cuz my bot token is on the py file, right?

winter hare
#

those are not warnings

#

its saying ur bot is online

slate swan
#

oh

#

nice 🙂

winter hare
#

u can have it print "bot is online" or something like that for u to know

slate swan
#

what should i overwrite?

winter hare
#

im not that knowledgeable in python so..

smoky sinew
#

it says "info"

winter hare
#

i want this command to be voice channel required meaning a user has to be in a vc in order for the command to work and if there not i want it to send a message saying they need to be in a vc for the command to work (dont judge me)

@client.tree.command(name='invite', description='Sends edited embed for people to join')
async def invite(interaction: discord.Interaction):
     voice_channel = interaction.user.voice.channel
     if voice_channel is None:
            await interaction.response.send_message("You are not connected to any voice channel.")
            return
     await interaction.response.send_modal(crow())```
slate swan
#

okey, thanks guys

torpid frigate
#

hey everyone

#

I have a question was wondering if anyone could figure out why its not working for me. Im writing some code for a "jinx" bot. it sees if two people on the server have said jinx within 10 secs and keeps track of results. ```import discord
from discord.ext import commands
import asyncio
from collections import defaultdict

intents = discord.Intents.default()
intents.messages = True

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

jinx_messages = defaultdict(list)
scoreboard = defaultdict(int)

@bot.event
async def on_ready():
print(f'{bot.user} has connected to Discord!')

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

content = message.content.lower()
if 'jinx' in content:
    jinx_messages[message.channel.id].append((message.author.id, message.created_at))

    # Check for jinx within the last 10 seconds
    for jinx_message in jinx_messages[message.channel.id]:
        if (message.created_at - jinx_message[1]).total_seconds() <= 10 and message.author.id != jinx_message[0]:
            scoreboard[jinx_message[0]] += 1
            await message.channel.send(f'{message.author.mention} was jinxed by <@{jinx_message[0]}>! Score: {scoreboard[jinx_message[0]]}')
            break

    # Remove messages older than 10 seconds
    jinx_messages[message.channel.id] = [(author_id, timestamp) for author_id, timestamp in jinx_messages[message.channel.id] if (message.created_at - timestamp).total_seconds() <= 10]

await bot.process_commands(message)

@bot.command(name='score')
async def show_score(ctx, user: discord.Member = None):
if user:
await ctx.send(f"{user.display_name}'s score: {scoreboard[user.id]}")
else:
scores = '\n'.join([f'<@{user_id}>: {score}' for user, score in scoreboard.items()])
await ctx.send(f'Scoreboard:\n{scores}')

bot.run('token')

potent spear
torpid frigate
#

This is my code but sadly its not working and im getting no feedback from the bobt in the server

potent spear
#

you need message_content intents

#

!intents

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.

potent spear
#

gl hf

torpid frigate
#

ty will look into it :)

slate swan
#

where are the docs about how to make the bot react with emojis to its own msgs and when certain number of reactions occur something else happens?

torpid frigate
#

it worked!

#

tysm @potent spear

potent spear
#

nvm, that's not really needed in your case, as it's only relevant for 10 seconds

potent spear
#

bot your code is pretty clean, keep it up
keep using official documentation and examples to learn discord py
avoid YT tutorials

slate swan
#
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.reactions = True

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

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

@bot.command()
async def post_embed(ctx):
    embed = discord.Embed(title="My Embed", description="This is my embed message.")
    message = await ctx.send(embed=embed)

    await message.add_reaction("emoji1")
    await message.add_reaction("emoji2")

@bot.event
async def on_reaction_add(reaction, user):
    if user == bot.user:
        return

    message = reaction.message

    if message.author == bot.user and message.embeds:
        embed = message.embeds[0]
        if reaction.emoji == "emoji1":
            # Reacted with emoji1
            if reaction.count >= 3:
                # Perform action when emoji1 has 3 or more reactions
                await message.channel.send("Emoji1 has 3 or more reactions!")
        elif reaction.emoji == "emoji2":
            # Reacted with emoji2
            if reaction.count >= 3:
                # Perform action when emoji2 has 3 or more reactions
                await message.channel.send("Emoji2 has 3 or more reactions!")

bot.run('YOUR_BOT_TOKEN')

Is this how to make a bot react to its own msg and then do things based on number of reactions?

winter hare
slate swan
#

no error no reaction xD

winter hare
#

do u know the format for emojis?

slate swan
#

:regional_reaction_letter:

#

no?

winter hare
slate swan
#

huh

#

what is ✔️

#

#

shouldnt i write

winter hare
#

write what

slate swan
#

await message.add_reaction(':white_check_mark:')

#

?

winter hare
#

u can try idk if it works

#

i think what i sent was for custom emojis

slate swan
#

how did u do it? cuz it isnt working for me

winter hare
slate swan
#
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In emoji_id: Value "" is not snowflake.```
#

wut

winter hare
#

idk if its the same with other emojis but it worked for the check mark one

slate swan
#

yeah, i tried adding the slash and same error mmm

winter hare
#

you should end up with the check mark as a reaction

#

.post_embed

#

oop

#

the only thing that doesnt work is the messages after a certain amount of reactions and for that ur gonna have to get more professional help cuz im still a beginner

slate swan
#

okey i made it with the unicode value

#

\u2716

turbid condor
#

whats the difference between commands.Bot and AutoShardedBot?

smoky sinew
turbid condor
#

I see now i get it why Stat bots works fine

#

So except this there is no big difference between them like some privelges

dull terrace
#

makes me sad my bot basically died without ads as i've stopped paying attention to it and just kept it running

#

this ended up being the retention

#

5% of people who engaged with the bot spent 2+ hours using it

#

7.5% spent 1+ hour

austere vale
#
  #ban command  
  @nextcord.slash_command(description="Bans a user. Please specify the reason.")
  @application_checks.has_permissions(administrator=True)
  async def ban(self,interaction, user: nextcord.User, *, reason=None):
    try:
      await user.send(f'You have been banned from {user.guild} because of: \n {reason}.')
      await interaction.guild.ban(user = user, reason=reason)
    except Exception:
      await interaction.send("Failed to DM the user, oh well.")
      await interaction.guild.ban(user = user, reason=reason)
    embed=nextcord.Embed(title="Banned User", description=f"I have successfully banned `{user}` for the reason of: `{reason}`", color=0xfd9fa1)
    await interaction.send(embed=embed)

im getting this error, does anyone know why? the ban does go through but the embed response isnt sent

dull terrace
#

you need to send a response

#

interaction.response.send_message

primal token
dull terrace
#

doge_kek it is a almost perfect exponential

primal token
#

Yep

rare briar
#

can someone help me with structure of my bot?

#

here is my structure

slate swan
#

No uppercase in folders

rare briar
#

only one problem?

slate swan
#

Especially not KeyBoard it's always written as Keyboard either way

#

Then the rest depends on what your handlers do and why you need a keyboard folder for a single file

rare briar
#

okay but what about structure?

slate swan
#

bot_token.txt is not really something we like to see, consider using environment variables

#

Then the rest seems fine if the files are actually what they do and it's not over-engineered (too many files for junk code)

rare briar
#

thanks anything else?

slate swan
#

Hey, i made a command that delete people when pining someone that his id is in the json file but not working

import nextcord, colorama, aiohttp, requests, json
from nextcord.ext import commands, tasks


with open('./cache/dontpingmeids.json', 'r') as f:
    ids = json.load(f)

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

    @commands.Cog.listener()
    async def on_message(self, message):
        print(message)
        try:
            if message.mentions:
                mentioned_ids = [mention.id for mention in message.mentions]
                if any(str(user_id) in mentioned_ids for user_id in ids):
                    await message.delete()
                    await message.channel.send("**Désolé, mais la personne que vous avez mentionnée n'aime vraiment pas ça. :pray:**")
        except Exception as e:
            embed = nextcord.Embed(title="Une erreur est survenue :vhrisk60:")
            embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/1028693898635251724/1080766112733593620/pngfind.com-warning-icon-png-2681594.png")
            embed.add_field(name="L'erreur en question : ", value=f"\n`{e}`")
            await interaction.response.send_message(embed=embed)

def setup(bot):
    bot.add_cog(DontPingMe(bot))

No error

slate swan
potent spear
#

seems like you haven't debugged your code, as if that was the case, you could point out exactly which if statement had unexpected behaviour for you

slate swan
#

yeap

buoyant quail
#

Do you get a message in console? (which you print in the begginning)
Do you get an error message?
Are the ids actually strings in the file?

Try to print out mentioned_ids and ids

potent spear
slate swan
# potent spear and you're checking this how exactly?
def cogsload():
    for folder in ["commands", "events"]:
        for filename in os.listdir(folder):
            if filename.endswith(".py"):
                print(botloading + f"{filename[:-3]} a été chargé avec succès")
                bot.load_extension(f"{folder}.{filename[:-3]}")```
#

it says that the file "ping" where i coded the things is loaded

potent spear
#

most likely
if any(str(user_id) in mentioned_ids for user_id in ids):
this will be False

potent spear
slate swan
#

wdym

potent spear
#

you could check by printing something specific in the cog itself, but yeah

slate swan
#

oh yeah

#

i tried printing message.content

#

and it's printing it