#discord-bots

1 messages Β· Page 173 of 1

crimson mauve
#

Still getting the same error?

#

neverminded, got caugh up on the thread.

buoyant quail
#

Where reference is stored in interaction? (in context it is context.message.reference)

buoyant quail
#

for slash commands

buoyant quail
shrewd apex
#

uses an Interaction message object

#

Represents the original interaction response message.

buoyant quail
#

ok, thanks

shrewd apex
#

This allows you to edit or delete the message associated with the interaction response. To retrieve this object see Interaction.original_response().

slate swan
#

do you have game ideas?

#

to play in a bot

#

be creative pls

shrewd apex
#

hmm simple ones or challenging ones

slate swan
#

both

crimson mauve
shrewd apex
#

is it for practice or do u plan to make it for a public bot

slate swan
#

very good

#

just tell

shrewd apex
#

need to know based on rate limit

slate swan
#

i dont really care about how hard

shrewd apex
#

u could make a platformer haven't seen that before

crimson mauve
shrewd apex
slate swan
#

hmmmmmmmmmmm

#

that's more challenging that it cant even be in discord

slate swan
crimson mauve
shrewd apex
#

making games is fun made a decent one recently its in my pfp made the website too but idk if it suits your taste aniblobsweat

slate swan
#

checking

crimson mauve
shrewd apex
#

TT_wjGirlteaSipOwO ic

shrewd apex
#

not yet

#

rewriting it for open source

#

prolly in few months gonna add a bunch of new features too

slate swan
#

what image manipulation lib did u use

shrewd apex
#

pillow brainmon

slate swan
#

give me access to repo? pithink

#

me want inspirations

#

totally not stealing code

shrewd apex
#

closed source rn only with a few friends sorry

slate swan
#

then add me to the friends yert

shrewd apex
#

u can join the server if you want to rn...

slate swan
#

sure

shrewd apex
#

ok i just met u today lol

young dagger
shrewd apex
#

in name add "\u200b" then in vakue f string it

#

value*

young dagger
shrewd apex
#
    embed.add_field(name=f"\u200b", value=f"**Reason:** {reason}", inline=True)
vocal snow
#

you can also do it all in the description if you want

#

man this syntax highlgihting is so bad

young dagger
shrewd apex
#

use on mobile that way u wont have expectations in first place

vocal snow
shrewd apex
#

no expectations == no dissapointment

vocal snow
#

true

young dagger
shrewd apex
young dagger
shrewd apex
#

u need \u200b

#

value cant be empty

young dagger
upbeat otter
young dagger
#

Thanks

upbeat otter
#

nice

fading pecan
#

My bot not working

upbeat otter
shrewd apex
supple ridge
#

can i update my bot config.json without restarting the script?

shrewd apex
#

nope

#

unless u are reloading it in ur code

upbeat otter
supple ridge
#

yea

#

i can reload just need to know how

shrewd apex
#

read the json using json.load

supple ridge
#

huuh

naive briar
#

!d json.load

unkempt canyonBOT
#

json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)```
Deserialize *fp* (a `.read()`-supporting [text file](https://docs.python.org/3/glossary.html#term-text-file) or [binary file](https://docs.python.org/3/glossary.html#term-binary-file) containing a JSON document) to a Python object using this [conversion table](https://docs.python.org/3/library/json.html#json-to-py-table).

*object\_hook* is an optional function that will be called with the result of any object literal decoded (a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict")). The return value of *object\_hook* will be used instead of the [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict"). This feature can be used to implement custom decoders (e.g. [JSON-RPC](https://www.jsonrpc.org) class hinting).

*object\_pairs\_hook* is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of *object\_pairs\_hook* will be used instead of the [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict"). This feature can be used to implement custom decoders. If *object\_hook* is also defined, the *object\_pairs\_hook* takes priority.
supple ridge
crimson mauve
supple ridge
#

figured it

supple ridge
#

i wanna do user customization and preferences

crimson mauve
supple ridge
#

one more doubt is there a way i can run multiple bots from same script?

crimson mauve
#

But why?

#

Oh, trying to make a bunch of NPCs or something

upbeat otter
crimson mauve
upbeat otter
crimson mauve
crimson mauve
#

Good luck figuring it out then.

supple ridge
crimson mauve
supple ridge
crimson mauve
supple ridge
crimson mauve
#

Now this is not want you want to hear, but you might be better off making a few small things to learn with rather than jumping in the deep end right off the bat before you know how to swim.

slate swan
#

!resources

unkempt canyonBOT
#
Resources

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

upbeat otter
supple ridge
#

okok

crimson mauve
supple ridge
crimson mauve
#

Not even the entire game of Blackjack, just the card dealer.

supple ridge
#

ah okay

spring summit
#

my bot literally started ignoring my commands for sum reason, anybody knows why? (intents are on)

crimson mauve
spring summit
crimson mauve
shrewd apex
unkempt canyonBOT
#

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

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

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

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

Note

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

Hi

shrewd apex
#

TH_02SmirkingHeh hello

slate swan
#

So the question I'm stuck on, how would this get the names/id's without me defining them in the top like i did before? i'm assuming the approach you're taking is calling the data using for loops right?

crimson mauve
#

You can populate dictionaries on the fly as long as you have defined them as dictionaries first.

a_dict={}
a_dict["User_One"]={"Name":"J. R. Bob Dobbs"}
print (a_dict)

So in this example there is a top level entry called User_One and the name : name pair is a child of it.

subtle jolt
#

getting this amazing error when trying to send the message, is this because its taking too long to respond?

TraceBack:
  File "C:\Users\Lenovo User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "c:\Users\Lenovo User\Desktop\LifeAsPy\Hypixel Api\BetterCocoa\main.py", line 40, in session
    await interaction.response.send_message(f'Session of `{username}`', file=discord.File(f"./database/{username}.png"))
  File "C:\Users\Lenovo User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 769, in send_message     
    await adapter.create_interaction_response(
  File "C:\Users\Lenovo User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 218, 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:
  File "C:\Users\Lenovo User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\Lenovo User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Lenovo User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'session' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
slate swan
crimson mauve
#

So using the list you would get from Guild.members you could fun a for loop and pull them out one by one.

for each in Guild.members:
    a_dict[each.id]={"name":each.name} 
slate swan
#

so i just put a for loop in the command at the top? i don't need to define the string i'm trying to obtain like I did?

crimson mauve
#

All depends on how you want it to work.

crimson mauve
#

First project?

#

Just a heads up, this is like trying to run before you can crawl.

#

Do it, I wonder who 381870129706958858 is. let us know.

vale wing
#

What the actual hell

crimson mauve
#

I know, I'm just wondering if it's the same as a 555phoone number.

paper sluice
#

bot = Client() πŸ˜”

vale wing
#

Are you making own wrapper or smth

crimson mauve
sick birch
paper sluice
vale wing
#

What the what

sick birch
#

FYI that is against discords terms of service

#

You are accessing the API in a way that is not supported

#

Or documented, for that matter

golden portal
#

its the one where it shows mobile status on bots by sending an identify payload as mobile to discord

paper sluice
#

ah ic

vale wing
#

That's some weird thing

#

Yeah one dude did

crimson mauve
#

nothing important, I remember something after I hit enter.

vale wing
#

It's open source isn't it

slate swan
crimson mauve
vale wing
slate swan
#
        for member in self.TheData.members:
            member[member.id]={"name":member.name} ```
paper sluice
#

member[member.id] here member is an instance of discord.Member not dict

crimson mauve
#

You need to define member as a dict

paper sluice
#

so you can't do that

crimson mauve
#
the_dict={}
        for member in self.TheData.members:
            the_dict[member.id]={"name":member.name} 
slate swan
#

ohhhh

crimson mauve
slate swan
crimson mauve
#

__init__ runs on startup(or just when that file/class is loaded)

@commands will run each time you call the command.

slate swan
#

so if it's a dictionary, it should grab the data when the command is ran incase things change. got it

crimson mauve
#

That and ctx will make it easy to get the guild/server

ionic moss
#

What is wrong with this piece of code?? ```py
inactive_channels = list(channel for channel in inactive_server.text_channels for inactive_server in bot.guilds)

`NameError: name 'inactive_server' is not defined`
crimson mauve
ionic moss
#

an iterator, for inactive_server in bot.guilds

#

inactive_server is (supposed to be) the discord.Guild object

slate swan
crimson mauve
ionic moss
#

it should be able to be read in the listcomp iterator

#

(it does for inactive_server in bot.guilds)

crimson mauve
crimson mauve
ionic moss
#
def inactive():
  q = list(w for w in inactive_server.text_channels for inactive_server in bot.guilds)
  w = list(w.last_message for w in q)
  
  e = w.map(lambda q: q.edited_at or q.created_at)
  r = sorted(e)

  return r, min(e), max(e)

inactive()
#

(without qeval at the start)

#

sure wait

#

Alright hold on
check DMs

crimson mauve
ionic moss
#

No, it should be a list of discord.TextChannel for each discord.Guild of bot.guilds defined as inactive_server

#

so let's say it should be something like ```py
def get_all_persons() -> dict[tuple[Person]]:
...

class Person:
name = ...
...

my_list = [person.name for person in persons.keys() for persons in get_all_persons()]

#

here it would say that persons is not defined

crimson mauve
#

Ya, because it's not being defined anywhere in this code.

ionic moss
crimson mauve
#

What documentation are you reading from? can you link it?

spring summit
#
role = discord.utils.get(message.guild.roles, name="Premium")
        await message.author.add_roles(role)```  'int' object is not iterable
ionic garden
#

is it possible to have multiple on_message listeners running @ the same time?

ionic moss
ionic garden
#

wb if there's

#
@bot.event
async def on_message(message: discord.Message) -> None:
    if message.author == bot.user or message.author.bot:
        return
    await bot.process_commands(message)
```this thing in the main file
crimson mauve
ionic moss
#

Correct.

crimson mauve
#

How much of the code did you write yourself and how much did you copy and paste?

ionic moss
#

I wrote it to iterate through all the channels of each guild the bot is in.

#

Nothing was copied nor was pasted.

unkempt canyonBOT
#

Hey @slate swan!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

crimson mauve
#

ok, then where are you defining inactive_server at?

unkempt canyonBOT
#

Hey @slate swan!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

ionic moss
#

Here: https://i.imgur.com/kZDUx30.png ```py
def inactive():
q = list(w for w in inactive_server.text_channels for inactive_server in bot.guilds)
w = list(w.last_message for w in q)

e = w.map(lambda q: q.edited_at or q.created_at)
r = sorted(e)

return r, min(e), max(e)

inactive()

unkempt canyonBOT
#

Hey @slate swan!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

#

Hey @slate swan!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

crimson mauve
#

read the bot, use paste bin.

crimson mauve
#

does it work?

#

Dude, this ain't even python.

#

You posted JavaScript.

ionic moss
#

@crimson mauve Alright, should it be written this way? ```py
def inactive() -> list:
channels = list(channel for server in bot.guilds for channel in server.text_channels)
...
...

#

it should be defined in this way now

crimson mauve
#

Not going to lie having const owners = ["1020440076024557628"]; is a red flag, makes me think you are putting in backdoors.

ionic moss
#

Alright.

crimson mauve
#

write it out the long way if you need to.

ionic moss
#

works as intended now.

crimson mauve
#

πŸ‘

slate swan
#

how'd u get a colorful border for screen scraping? o.o

crimson mauve
slate swan
crimson mauve
slate swan
#

sure! idc

spring summit
#

is it possible to give out roles with a command in a specific server?

slate swan
#

Yes

spring summit
#

how do i specify the guild

sick birch
unkempt canyonBOT
#

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

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.

You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
oblique fern
#

How can I make a command message "dismiss" right away before it"times out" when there is not supposed to be a message sent back so no interaction.response.send_message to make it go away

#

am I explaining that right

sick birch
#

Just so it doesn't time out?

oblique fern
#

yea, don't want a message to appear but I want the pop up to not time out, just disappear after the command is used.

#

the reason is because the command should be accepted in channel or via DM, but always DM the results to the user who used it

sick birch
#

!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...
oblique fern
#

ah, cool!

spring summit
sick birch
#

Do you want to be able to give roles to users in other servers?

spring summit
#

because i got a redeem command that gives ya a role when you redeem a key in dms, thats why i cant do juist guild

sick birch
spring summit
sick birch
#

And the full traceback, since this error is somewhere else

slate swan
#

I think you can also type hint a command parameter with discord.Guild and it'll attempt to convert an input into a Guild object. So inputting an ID or name would work. But your bot has to be able to 'see' the guild.

sick birch
#
@bot.command()
async def redeem(ctx: commands.Context, guild: discord.Guild, code: str) -> None:
  ...
spring summit
#

on_message/ the bot dms

sick birch
#

You aren't using the commands extension?

#

I would recommend that you do

#

Discord.py will handle the hard work of parsing for you

spring summit
#
@client.event
async def on_message(message):
    guild = client.get_guild(1060335114703339520)
    channellol = client.get_channel(1061293482188210217)
    channellol1 = client.get_channel(1061293482188210217)
    with open('key_codes_premium', 'r') as key_codes_premium:
        unredeemed = key_codes_premium.read()
    if (message.content == f'{unredeemed}'):
        dmchannel = await message.author.create_dm()
        embed = discord.Embed(title=f"{key_emoji} PREMIUM KEY (1 MONTH)",
                              description=f'``KEY REDEEMED SUCCESSFULLY.``', color=0x2F3136)

        await dmchannel.send(embed=embed)
        chars = string.ascii_letters + string.digits
        keysb = ('MH' + '-' + 'PREMIUM' + '-' + ''.join(random.choice(chars) for i in range(6)) + '-' + ''.join(
            random.choice(chars) for i in range(6)) + '-' + ''.join(
            random.choice(chars) for i in range(6)) + '-' + ''.join(random.choice(chars) for i in range(6)))
        with open('key_codes_premium', 'w') as premiumware:
            premiumware.write(keysb)
        with open('premium', 'w') as f:
            f.write(f"{str(message.author.id)}\n")
            f.close()
        await asyncio.sleep(2.5)
        embed2 = discord.Embed(title=f"{key_emoji}A PREMIUM KEY WAS REDEEMED!",
                               description=f'``REDEEMED BY {str(message.author)}.``',
                               color=0x2F3136)
        await channellol.send(embed=embed2)
        role = discord.utils.get(message.guild.roles, name="Premium")
        await message.author.add_roles(role)
    await client.process_commands(message)```
#

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

cold sonnet
#

you wanna do guild.roles not message.guild.roles

#

message.guild is None when the message is received in a dm

#

cuz it's not in a server

#

so you're basically doing None.roles

#

await message.author.add_roles(role) you won't be able to do that either

spring summit
#

so what should i replace it with

cold sonnet
#

get a member object from the guild you have with the message's author's id

#

member = guild.get_member(message.author.id) if you have your intents

#

basically binds the user to the guild if he's in the guild

#

the whole time I'm assuming you're sending the bot a message via dm

spring summit
cold sonnet
#

because if you dm the bot, message.author is a user

#

the user is not connected to the guild

#

if someone's not in a guild, you can't add roles to that person

#

you can only add roles to member

spring summit
#

well he is in that guild

#

im kinda lost rn

#

lmao

cold sonnet
#

the difference between a User and a Member is that a User is just a profile

#

a Member is a profile in a server

spring summit
#
member = guild.get_member(message.author.id)
        role = discord.utils.get(guild.roles, name="Premium")
        await member.add_roles(role)```does that work
cold sonnet
#

a User could be in many servers with the bot, the bot wouldn't know which server you're talking about

cedar estuary
#

how can you do a bot that if you send a message to x channel it will delete the message and send the message that was deleted to channel y in the same server? with on_message yes but what after it?

cold sonnet
#

so you attach the User to a server

spring summit
#

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

cold sonnet
#

you're lucky I'm a compiler

#

the bot didn't find a role in that server that's named Premium

#

Ashley's writing a book

#

Ashley stopped writing the book

slate swan
#

🐊

cold sonnet
#

she's at it again

slate swan
faint echo
#

What are some of the reasons as to why I could be getting Unknown interaction for my View?

  • The bot is online.
  • The bot has the correct permissions.
  • The command was working as of yesterday.
  • I did not modify the code

The error happens exactly on this line of code:
await interaction.response.edit_message(view=self)

#
@discord.ui.button(label="Confirm", style=discord.ButtonStyle.green, emoji=":white_check_mark:", custom_id="utility_confirm")
    async def callback(self, interaction: discord.Interaction, button):
        try:
            ## Lots of stuff happening here but no modification to interaction
        except Exception as err:
            btn.label = "Err!"
            await interaction.response.edit_message(content="blabla", view=self)
        else:
            await interaction.response.edit_message(view=self)  # Error happening here.. Unknown interaction
#

Ignore the button parameter there.

fading marlin
#

you're not responding fast enough. What are you doing inside your try block?

faint echo
#

I'm setting data inside MongoDB, and then creating a voice channel based on that data.

Overall, the timeout is set to 120 seconds, shouldn't it be waiting for an input ?

fading marlin
#

that's probably taking more than 3 seconds, consider deferring the interaction first and then sending a followup

faint echo
#

Gotcha

#

definitely is taking more than 3 seconds, I'll try that approach

upbeat otter
#

"use it as an example"

upbeat otter
fading marlin
#

you're taking too long to respond to the application's command interaction

upbeat otter
#

You don't seem to be in a class (judging from the indentation), apparently you're still using self

#

you're still using self

#

wot

#

if you want to use self then pass the bot instance to the function while calling it

upbeat otter
#
await set_emoji_quiz(self, 234567654321, 1256787654321, 1678987654321)
#

assuming you're within a cog

#

the ids smh

#

whatever you pass into them

#

bro

#

guild_id
message_id
channel_id
whatever_and_whatnot

winged coral
#

It's your code? You should know what args you need

upbeat otter
#

^

cedar estuary
#

AttributeError: 'Bot' object has no attribute 'x'
what does this error mean

#

or how do i fix it

slate swan
#

It means exactly what it says. What are you trying to do?

upbeat otter
#

"learn to use classes and objects"

primal token
#

Just learn OOP overall

upbeat otter
#

ok okimii

cold sonnet
#

what

#

no way

cedar estuary
#

why does my client.event block my commands?
i have on_message and then its the only thing that works but not the commands anymore?

quick gust
#

use @bot.listen

#

or process the commands

#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.11)").

Example...
quick gust
#

!d discord.ext.commands.Bot.process_commands

unkempt canyonBOT
#

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

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

By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.

This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").

This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.

Changed in version 2.0: `message` parameter is now positional-only.
cedar estuary
# quick gust use @bot.listen

umm maybe a dumb question but what does bot and client have in difference, or is client.listen just the same thing?

#

don't kinda get it

fading marlin
#

they're just variable names

cedar estuary
#

so its the same thing

#

basically

fading marlin
#

you should probably name it bot when it's a commands.Bot instance, and client when it's a discord.Client instance

slate swan
#

how did you play an audio file in vc?

@client.command()
async def say(ctx, *, text=""):
    if text == "":
        await ctx.send("You must provide some text for me to say out loud!")
        return

    voice_client = get(ctx.bot.voice_clients, guild=ctx.guild)
    if voice_client is None:
        await ctx.send("I'm not in a voice channel...")
        return

    if ctx.author.voice:
        tts_engine.save_to_file(text, 'src/assets/voice.mp3')
        
        tts_engine.runAndWait()

        os.system("rm src/assets/voice.mp3")
    else:
        await ctx.send("please join a voice channel then bring me in there!")```
#

thats what ive got, i just have to figure out how to make the file play qwq
im on linux, if that matters

fading marlin
#

!d discord.VoiceClient.play

unkempt canyonBOT
#

play(source, *, after=None)```
Plays an [`AudioSource`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AudioSource "discord.AudioSource").

The finalizer, `after` is called after the source has been exhausted or an error occurred.

If an error happens while the audio player is running, the exception is caught and the audio player is then stopped. If no after callback is passed, any caught exception will be logged using the library logger.

Changed in version 2.0: Instead of writing to `sys.stderr`, the library’s logger is used.
fading marlin
#

and then take a look at the various audio sources

slate swan
#

the source kills me

#

they all use ffmpeg.exe

#

idk how that looks on linux aaa

cedar estuary
#

how much latency in a bot is "bad"?

slate swan
#

i alr have it installed too

#

which path do i put in even

pliant gulch
#

Otherwise if you cannot notice it, keep it as is

slate swan
#

also where is .play()

#

oh nvm

pliant gulch
#

Average sudo enjoyers: πŸ˜”
Average doas enjoyers: 😏

slate swan
pliant gulch
#

You need to construct first

#

Otherwise you'd need to pass an instance

#

So VoiceClient()

slate swan
#

ah

pliant gulch
#

Actually ignore that part

#

You usually don't wanna create a VoiceClient manually

#

You get a VoiceClient object by using .connect on a VoiceChannel

#

!d discord.VoiceChannel.connect

unkempt canyonBOT
#

await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, self_deaf=False, self_mute=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceClient "discord.VoiceClient") to establish your connection to the voice server.

This requires [`voice_states`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.voice_states "discord.Intents.voice_states").
pliant gulch
#

You can get this from like, member.channel

slate swan
#

my join command is somewhere else bweheline

pliant gulch
#

What is voice_client here?

slate swan
#
 voice_client = get(ctx.bot.voice_clients, guild=ctx.guild)
    if voice_client is None:
        await ctx.send("I'm not in a voice channel...")
        return```
pliant gulch
#

Well, since your join command is separated I guess you could do a dictionary

#

Let's say you start off with an empty dictionary called voice_channels like this {}

#

When your join command is called, make a new key-value pair like {user_id: await channel.connect()}

#

Then in you're other command where you play the file, get the VoiceClient via voice_channels[user_id]

slate swan
#

God damn

#

I'll just morph the 2 commands

#

I just dont know how to check if the bot is alr in vc

#

so It doesn't try to connect twice

pliant gulch
#

Get channels.members

#

Then check for bot.user in channels.members

slate swan
#

jeez

crimson mauve
# slate swan jeez

If your bot is already in that channel it will toss up a ClientException – You are already connected to a voice channel. error. You can wrap it in a try/except and just pass it.

slate swan
#

ah true

crimson mauve
#

Damn, I want to work on other peoples stuff more than my own today.

unkempt canyonBOT
#

Contribute to Python Discord's Open Source Projects
Looking to contribute to Open Source Projects for the first time? Want to add a feature or fix a bug on the bots on this server? We have on-going projects that people can contribute to, even if you've never contributed to open source before!

Projects to Contribute to
β€’ Sir Lancebot - our fun, beginner-friendly bot
β€’ Python - our utility & moderation bot
β€’ Site - resources, guides, and more

Where to start

  1. Read our contribution guide
  2. Chat with us in #dev-contrib if you're ready to jump in or have any questions
  3. Open an issue or ask to be assigned to an issue to work on
glad cradle
ionic garden
#

do people still use prefix commands these days
i want discord to do some input validation for me

mental panther
#

hello, i have a slight issue?
cogs seem to be loading but no commands are showing from the cogs themselves on the help command

crimson mauve
cedar estuary
#

how do you get date and time when message in discord is sended , in own timezone

#

because message.created_at doesn't give my own timeozones time

lofty cedar
#

My client.event s are working but my client.command() s are not, any ideas?

merry cliff
#

is client discord.ext.commands.Bot()?

lofty cedar
merry cliff
#

did you do something like py bot = commands.Bot(command_prefix='>', case_insensitive=True, intents=intents)

lofty cedar
#

I have

client = commands.Bot(command_prefix = 'ED: ')
merry cliff
#

you need the message intent, which is not a default intent

lofty cedar
#

I don't know what that means but I have another discord bot that has exactly the same code and it works

merry cliff
#

to add it, go to the dev page and turnon the message intent on your dashboard, then use this:py intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix='PREFIX', case_insensitive=True, intents=intents)

lofty cedar
#

Just doing it now

merry cliff
#

ok

lofty cedar
#

AttributeError: 'Intents' object has no attribute 'message_content'

merry cliff
lofty cedar
#

not sure

merry cliff
#

is it the latest one?

lofty cedar
#

I installed it a while ago so maybe not

merry cliff
#

when did you install it?

lofty cedar
#

Easily a year ago likely more, not 100% sure

merry cliff
#

ok, can you run pip freeze in your terminal and send the version of discord.py

lofty cedar
#

1.7.3

merry cliff
#

there's the problem.

lofty cedar
#

How do I update it?

merry cliff
#

the latest is 2.0.1

lofty cedar
#

also why does it work with my other code if it's outdated there too?

merry cliff
#

update using pip install --upgrade discord.py

slate swan
merry cliff
#

is your other code hosted on a different device?

slate swan
#

Unknown interaction error !

lofty cedar
merry cliff
#

virtual env?

lofty cedar
#

It's all run off my pc written in idle

merry cliff
#

hmm i have no idea then

lofty cedar
#

Just being dodgy ig haha

slate swan
merry cliff
#

well I;m just letting you n=know that if you do update, there are a few breaking changes and a new way to start the bot, so head over to the docs to see them all

merry cliff
merry cliff
#

yeah

slate swan
merry cliff
#

can i see how you defined your callback?

slate swan
merry cliff
#

ok so the buttons show up but when they are clicked they throw an error

slate swan
#

i defer them all

#

but same error

slate swan
merry cliff
#

it looks like one of the buttonstyles are throwing an error too

#

gimm a few mins to test

slate swan
slate swan
merry cliff
#

ok try adding a thinking=True inside the defer() funca

merry cliff
#

that way you use the followup in your code instead of trying to send a response

slate swan
merry cliff
#

np

slate swan
#

i just added the thinking you said about , and edited the time.sleep by asyncio.sleep

merry cliff
#

nice

slate swan
#

is it possible to send a message that is visible to a specific members ?

slate swan
#

or using ephemeral without response

#
mods = ['1047266960519467057']

def check_Mod(ctx):
    if ctx.author.id in mods:
        IsMod = True
    else:
        IsMod = False
    return IsMod


@bot.command()
async def bought(ctx,id=None,item=None):
    IsMod = check_Mod(ctx)
    if IsMod == False:
        return await ctx.send("Your not a mod.", delete_after=10)
    if id == None:
        return await ctx.send(".bought <id> <item>", delete_after=10)
    if item == None:
        return await ctx.send(".bought <id> <item>", delete_after=10)
    query.execute("""INSERT INTO LOGS (USER_ID, ITEM) VALUES (?, ?)""",(id, item,))
    return await ctx.send("Sent to logs.")

keeps returning that im not a mod , any thoughts

naive briar
unkempt canyonBOT
civic fractal
#

why not check their roles rather than hardcoding a list of users?

#
def check_mod(ctx):
    return any(role.name == "Moderator" for role in ctx.author.roles)```
slate swan
slate swan
#

UnboundLocalError: local variable 'uptime' referenced before assignment

#

I dont get it... can you guys help ?

somber imp
#

Because you are calling that in the 4th uncommented line

#

But that is also being stored on a variable named uptime

severe mural
#

problem nothing help, error message code giveaway commands is python code.

#

sigh :/

somber imp
slate swan
#

import discord
from discord.ext import tasks
import datetime

client = discord.Client(intents=discord.Intents.default())

Replace YOUR_TOKEN_HERE with your Discord bot token

TOKEN = 'xxxx'

Replace YOUR_CHANNEL_ID with the ID of the channel you want to send the message to

CHANNEL_ID = 'xxxxx'

@tasks.loop(minutes=5)
async def send_uptime_message():
# Get the current time
current_time = datetime.datetime.utcnow()
# Check if the computer has been turned on within the last 5 minutes
# You may need to adjust this time depending on the performance of your computer
uptime = datetime.datetime.fromtimestamp(uptime()).strftime('%Y-%m-%d %H:%M:%S')

if current_time - datetime.timedelta(minutes=5) < uptime:
    # If the computer has been turned on within the last 5 minutes, send a message to the Discord channel
    channel = client.get_channel(CHANNEL_ID)
    await channel.send('Your computer has been turned on!')

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

client.run(TOKEN)

severe mural
#

no solution commands message error giveaway and also image problem.

somber imp
#

1st of all
A variable can't reference itself if it hasn't been assigned a value previously

2ndly you can't call a variable

slate swan
real badger
#

What are some top commands for discord bots?

slate swan
#

I keep getting this error with my help command: Traceback (most recent call last): File "/root/bot/akro.py", line 14, in <module> async def help(ctx, *args): File "/usr/local/lib/python3.10/dist-packages/discord/ext/commands/core.py", line 1513, in decorator self.add_command(result) File "/usr/local/lib/python3.10/dist-packages/discord/ext/commands/bot.py", line 245, in add_command super().add_command(command) File "/usr/local/lib/python3.10/dist-packages/discord/ext/commands/core.py", line 1348, in add_command raise CommandRegistrationError(command.name) discord.ext.commands.errors.CommandRegistrationError: The command help is already an existing command or alias. but i do not have a other help command in my code any reasons why this could happen?

somber imp
real badger
somber imp
slate swan
somber imp
#

Tbh if you want a help command, don't remove the default one. Rather subclass it

#

But that's the choice of one own

slate swan
#

Whenever i put the help_command = None i get the same error

naive briar
#

Put it in the bot instance constructor

real badger
slate swan
#

i use client = commands.Bot

#

it would be the same just with client at the start right?

real badger
#
client = commands.Bot(help_command = None)
slate swan
#

thank you

naive briar
real badger
#

How do I make a member get a dm when they join a server?

slate swan
naive briar
#

!d discord.on_member_join

unkempt canyonBOT
#

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

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

how do I use it and how do I dm a user

civic fractal
#

kinda like that

slate swan
#
async def on_member_join(member):
    # Send the DM to the member
    await member.send("```
#

or @bot.event

#

i think i've only ever used client

real badger
#

on my slash bot I use client

#

it makes everything more confusing

slate swan
#

Thanks jonah, this has also helped me with my code as well

real badger
#

It works well, but how do I put the user's name without the discriminator?

civic fractal
#

you mean

#

user.name

real badger
#

possibly

#

ok thanks that works

real badger
#

What are some useful commands to add to my bot?

slate swan
#

ban, unmute, mute, warn, help, unban, kick, ticket system, xp system

naive briar
#

Discord already have most of those built in

slate swan
#

Its makes it more convenient for me when i have it in my bot

#

instead of having to go to there profile and doing it manually

viral stump
#

How can i reach my guild's member name in server? (server username)

            list = ""
            for victim_user_id, percentage in targeted_victims:
                idlist = await bot.fetch_user(victim_user_id)
                guildlist = await bot.fetch_guild(victim_user_id)
                chance = (percentage * 100)
                list += (f"Server username: \"{guildlist.name}\", username: \"{idlist.name}\" ve %{chance:.0f} chance got.\n")
            await message.channel.send(f"msg")```
robust fulcrum
#

Guys how can i make a !d commands like @unkempt canyon in my discord.py bot
I actually the saw the command code but was not able to understand so can anyone help me?

desert heart
rare echo
#

u don’t have to do it manually, it’s a slash cmd by default

robust fulcrum
slate swan
naive briar
#

Really useful

desert heart
desert heart
#

What's your question?

viral stump
desert heart
#

You need to get the guild first, and then get the member object in that guild

guild = bot.get_guild(guild_id)
member = guild.get_member(victim_user_id)
nickname = member.name
if member.nick is not None:
  nickname = member.nick```
#

Ah, you can simplify that logic by just using member.display_name

viral stump
#

why dont we use fetch instead of get?

quick gust
#

fetch makes a request to the API, get gets it from the bot's cache

viral stump
#

so i got this error

#
                idlist = await discord.Guild.get_member(victim_user_id)```
desert heart
#

get_member needs to be called on an instance of a Guild. This is why my example uses get_guild() first. Furthermore, get_member is not a coroutine function and does not need to be awaited. Notice how my example does not use await.

viral stump
desert heart
#

You're still not calling get_member on an instance of a Guild. You'll get the same error you showed earlier.

#

If you can already get a Guild instance from last_message.guild, then you do not need to use get_guild

desert heart
#

discord.Guild is a type. You need an instance of this type because get_member() is an instance method rather than a static or class method. One way to get an instance of it is to use get_guild() - it returns an instance of discord.Guild.

viral stump
desert heart
#

It looks like last_message.guild already returns an instance of a Guild, so you don't need get_guild - it's redundant in this case.

#
member = last_message.guild.get_member(victim_user_id)
if member is not None:
  name = member.display_name
else:
  # member doesn't exist in the guild - handle this case somehow...
viral stump
#

but if i dont got a last mesaage guild, how would it be?

pulsar ibex
#

How can I make a discord bot?

cunning pasture
slate swan
vocal snow
#

--> self.TheData = {}

#

--> self.TheData.members

#

dictionaries don't have a .members attribute which is what the error tells you

slate swan
#

i forgot to redefine the ctx.guild x.x

#

ok... now AttributeError: 'DataGrab' object has no attribute 'create_embed'

vocal snow
#

I can't see a create_embed method in the code you sent

shrewd apex
#

its simple and can be overwritten however u want it

slate swan
slate swan
shrewd apex
#

its in disnake tho u have to make it discord in those places

#

also u can remove the on_error thats for my exception handler

slate swan
shrewd apex
#

just replace disnake with discord and u will be fine

shrewd apex
#

yeah lol that was in mine

#

if u have a custom exception handler then u can use it with ur own custom exception

#

otherwise remove it

slate swan
#

gotcha.

tough fern
slate swan
#

one last question, so where do i define my dict?

#

the ClassicPaginator __init__ ?

tough fern
tough fern
shrewd apex
shrewd apex
#

nah above average

shrewd apex
tough fern
shrewd apex
#

are u sure ur error handler is not eating up the error?

#

@huntMob.error
async def huntMobError(ctx, error: app_commands.AppCommandError):
    if isinstance(error, app_commands.CommandOnCooldown):
        em = discord.Embed(title=f"Don't Genocide!", description=f"The mobs need time to detect your existence, check again in {error.retry_after:.2f}s.",
                           color=ctx.author.color)
        await ctx.send(embed=em)
#

u dont have an else

tough fern
#

i see, thanks

tough fern
#

updated:

@huntMob.error
async def huntMobError(ctx, error: app_commands.AppCommandError):
    if isinstance(error, app_commands.CommandOnCooldown):
        em = discord.Embed(title=f"Don't Genocide!", description=f"The mobs need time to detect your existence, check again in {error.retry_after:.2f}s.",
                           color=ctx.author.color)
        await ctx.send(embed=em)
    else:
        print(error)```
#

what is the type of the error? is it not app_commands.CommandOnCooldown

slate swan
#

hybrid commands raise a commands.commandoncooldown

shrewd apex
#

also not sure app commands have ctx in error

maiden fable
#

They have interaction

shrewd apex
#

its most probably an interaction

slate swan
#

Hybrid command raised an error: You are on cooldown. Try again in 58.08s
hybrids have context...

maiden fable
#

I was talking about app commands, not hybrid

#

I never used hybrid so can't comment on that

slate swan
#

πŸ€”

shrewd apex
maiden fable
#

Oh hm

tough fern
# slate swan hybrid commands raise a commands.commandoncooldown

updated:

@huntMob.error
async def huntMobError(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        em = discord.Embed(title=f"Don't Genocide!", description=f"The mobs need time to detect your existence, check again in {error.retry_after:.2f}s.",
                           color=ctx.author.color)
        await ctx.send(embed=em)
    else:
        print(error)``` still can't
slate swan
#

no error in terminal?

tough fern
tough fern
slate swan
slate swan
tough fern
slate swan
#

they work the same way

#

just replace app_commands with commands

tough fern
#

what thing that replace the "key" arg

naive briar
#

Exact same, but commands is for commands.Context and app_commands is for discord.Interaction

slate swan
#

!d discord.ext.commands.BucketType.user

unkempt canyonBOT
slate swan
#

you need a bucket there

#

given that you just use the author id as key, this should be fine

tough fern
tough fern
slate swan
# shrewd apex what for tho?
for member in ctx.guild.members:
            self.DataPost[f"Member: {member.name} Member.ID {member.id}\n"] = None
            print(f"Data from DataPost: {self.DataPost.keys()}\n")

        for role in ctx.guild.roles:
            self.DataPost[f"Role: {role.name} Role.ID {role.id}\n"] = None
            print(f"Data from DataPost: {self.DataPost.keys()}\n")

        for category in ctx.guild.categories:
            self.DataPost[f"Category: {category.name} Category.ID {category.id}\n"] = None
            print(f"Data from DataPost: {self.DataPost.keys()}\n")

        for channel in ctx.guild.channels:
            self.DataPost[f"Channel: {channel.name} Channel.ID {channel.id}\n"] = None
            print(f"Data from DataPost: {self.DataPost.keys()}\n")
slate swan
#

which init LUL

#

wdym which, each class has only one init

lament mesa
slate swan
#

their are two __init__'s in the code if you looked at the code he sent before you answered, you would of known that. LUL

short silo
#

how do we reference channels in embeds, meaning actually click on em to be redirected.
Current code

info=""
        text_channels=[channel for channel in guild.text_channels if ('view_channel',True) in channel.permissions_for(guild.get_role(1061579212349263933))]
        text_channel_description=[text_channel.topic for text_channel in text_channels]
        for i in range (0,len(text_channels)):
            info=info+f"#{text_channels[i]} -> {text_channel_description[i]}\n\n"
        embed = Embed(title="Server Guide",colour=discord.Color.purple(),description=info)
        
short silo
merry cliff
#

Can you send a message into a text channel from the on_ready event?

steep wedge
#

await [channel here].send('message here')

slate swan
#

You shouldn't really be doing anything inside of on_ready

steep wedge
merry cliff
#

yeah thanks

upbeat otter
steep wedge
upbeat otter
#

ok

merry cliff
#

then where should I want to put a background task?

#

that runs while the bot does

#

wait can you literally just call a task outside of an event/command

loud junco
#

someone help ;-;

slate swan
#

good afternoon. please tell me. I study the documentation and often meet such functions. what to do to call them?

merry cliff
#

events?

loud junco
#

hi ash

merry cliff
#

also dont use light mode, it attracts bugs

#

hehehe

upbeat otter
upbeat otter
upbeat otter
# loud junco

error says it as much
progress.items is not a package

merry cliff
#
class TwitchStuff(commands.Cog):
    def __init__(self):
        self.live_notifs_loop.start()``` raises```py
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.twitch' raised an error: TypeError: TwitchStuff.__init__() takes 1 positional argument but 2 were given``` im so confused
upbeat otter
merry cliff
#

thanks it worked

loud junco
#

but how do i even import it correctly

#

i thought thats how u import stuff

#

from file name import something

pulsar kettle
#

Running this command:

@bot.tree.command(name='ttsjoin', description='Connects bot to vc for tts')
async def ttsjoin(interaction: discord.Interaction, *, channel: discord.VoiceChannel=None):
    
    if not channel:
        try:
            channel = interaction.author.voice.channel
        except AttributeError:
            await interaction.response.send_message('No channel to join. Please either specify a valid channel or join one.')

    vc = interaction.voice_client

    if vc:
        if vc.channel.id == channel.id:
            return
        try:
            await vc.move_to(channel)
        except asyncio.TimeoutError:
            raise interaction.response.send_message(f'Moving to channel: <{channel}> timed out.')
    else:
        try:
            await channel.connect()
        except asyncio.TimeoutError:
            raise interaction.response.send_message(f'Connecting to channel: <{channel}> timed out.')

    await interaction.response.send_message(f'Connected to: **{channel}**', delete_after=20)```
raises
```discord.app_commands.errors.CommandInvokeError: Command 'ttsjoin' raised an exception: AttributeError: 'Interaction' object has no attribute 'voice_bot'```

Can anyone help please?
merry cliff
#

it has to be ctx.voice_bot usually

pulsar kettle
#

So vc = ctx.voice_bot?

merry cliff
#

just try channel.join()

#

you only need voice client for actually playing the file

pulsar kettle
merry cliff
#

wait u already have channel.connect so u dont need it

#

just delete the voce_client bits from ur code it should automatically switch vcs

pulsar kettle
#

I assume move_to is incorrect

merry cliff
#

yeah just connect()

#

I'm really sorry but i have to go to bed

pulsar kettle
#

All good

slate swan
#

!d discord.Member.move_to

merry cliff
#

bye

unkempt canyonBOT
#

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

Moves a member to a new voice channel (they must be connected first).

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

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").

Changed in version 1.1: Can now pass `None` to kick a member from voice.
slate swan
#

its a method of member object

merry cliff
#

no they want to bot to move to the user's vc

slate swan
slate swan
merry cliff
#

i guess yeah but to use that you would need perms

slate swan
merry cliff
#

which would be unnecessary if you just connect to vc

pulsar kettle
slate swan
#

you cannot connect again if you're already in a vc

merry cliff
slate swan
merry cliff
#

oh ok it should be fine then

slate swan
#

!d discord.VoiceClient this should generally be used to control voice protocols in dpy tho

unkempt canyonBOT
#

class discord.VoiceClient```
Represents a Discord voice connection.

You do not create these, you typically get them from e.g. [`VoiceChannel.connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.connect "discord.VoiceChannel.connect").

Warning

In order to use PCM based AudioSources, you must have the opus library installed on your system and loaded through [`opus.load_opus()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.opus.load_opus "discord.opus.load_opus"). Otherwise, your AudioSources must be opus encoded (e.g. using [`FFmpegOpusAudio`](https://discordpy.readthedocs.io/en/latest/api.html#discord.FFmpegOpusAudio "discord.FFmpegOpusAudio")) or the library will not be able to transmit audio.
slate swan
#

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

slate swan
#

you need to provide intents

vale wing
#

What about reading

crimson mauve
#

Is there any downfall to using Intents.all() everywhere?

vale wing
#

When you provide only required intents, gateway already filters the unneeded ones out, in other case you filter them and spend computing power and network bandwidth

solid orbit
#

why does this not import bot? i literally have a file called 'bot'

vale wing
#

Move it out from venv

#

And the rest of files except lib and bin

crimson mauve
vale wing
#

Probably except pyvenv.cfg too

crimson mauve
#

Cool, was just wondering if the API would hate me.

solid orbit
#

i am new to coding btw

vale wing
# crimson mauve So I'll be fine as long as I'm not running it on a 5602.

I mean imagine a situation when your bot is on 3 servers, each has 100k members and every second 1k members changes their status (that's unrealistic but potentially may happen). You would receive 1k events, that would affect bandwidth certainly, and depending on how lib processes events, it would take computing powers as well

vale wing
vale wing
solid orbit
#

and how?

vale wing
#

venv is like autogenerated folder you shouldn't be touching

vale wing
crimson mauve
solid orbit
#

oh

#

but its seems so fun Xd

#

with what should i start then?

crimson mauve
#

It is, but so is swimming if you know how to swim.

#

Something small, something like a little script that deals out a deck of cards.

vale wing
solid orbit
vale wing
#

Need funcs and OOP

crimson mauve
#

And after that, classes.

solid orbit
#

fuctions i also know

#

classes i know a little

vale wing
vale wing
crimson mauve
solid orbit
#

i did this once as practice:

#

and then some other code in another file

vale wing
#

could've used dataclass

solid orbit
vale wing
#

That's pretty quick learning

#

Nice, haven't seen such people here for a while

shrewd apex
solid orbit
shrewd apex
#

also typehints if slash commands

vale wing
pulsar kettle
#

Hiya, I was just wondering if there's a way I can code a /commandslist slash command and have it list the name and description for every command in the .py file.
So for example, for the ban command it would grab the name and description from the async def line and put it into a text message and repeat that for every command:

@bot.tree.command(name='ban', description='Bans a member from the server')
@has_permissions(ban_members=True)
async def ban(interaction: discord.Interaction, member: discord.Member, reason: str=None):
    guild = interaction.guild
    await member.send(f"You have been banned from: ***{guild.name}*** | {reason}")
    await member.ban(reason=reason)
    embed = discord.Embed(title=(f'***{member} has been banned*** | {reason}'), color=0xf6ff00)
    await interaction.response.send_message(embed=embed)```
Is this possible? And if so how can I implement it into my code? (I am a beginner to coding so I may not understand some things sorry)
vale wing
#

Like I did πŸ€“

naive briar
#

Being quick doesn't mean you learned enough about it to be somewhat useful

shrewd apex
robust fulcrum
shrewd apex
vale wing
#

@solid orbit you can develop bots ig, this will help you to improve current knowledge and gain new

vale wing
shrewd apex
#

hmm fair enough ojito

vale wing
#

It's just a thing that has to be in every async app and has some methods for async stuff

naive briar
unkempt canyonBOT
#

for ... in walk_commands()```
An iterator that recursively walks through all commands and subcommands.

Changed in version 1.4: Duplicates due to aliases are no longer returned
vale wing
#

Idk how it works

vale wing
naive briar
#

It's a property

crimson mauve
#

What are you trying to do with it?

naive briar
#

Don't call it

crimson mauve
#

message.author.id will give you their user ID

naive briar
#

Check?

crimson mauve
#
if ThisID == ThatID:
#

Does it work?

naive briar
#

That's not from that line of code you just sent

#

Also author.id is an int

crimson mauve
#

Your "ID" is a string

pulsar kettle
#

Experimenting with different help commands and came across this one which only gets the bot to send the message: help
How can I edit the code and get it to work for every command + show the description? (i.e. It goes through every command, grabs the name and description and puts them into a single message)
Help code:

@bot.tree.command(name="help", description="Returns all commands available")
async def help(interaction: discord.Interaction):
    helptext = "(tildetildetilde)"
    for command in bot.commands:
        helptext+=f"{command}\n"
    helptext+="(tildetildetilde)"
    await interaction.response.send_message(helptext)```
Sample code (other command):
```python
@bot.tree.command(name='nick', description='Changes the nickname of a member')
@has_permissions(manage_nicknames=True)
async def nick(interaction: discord.Interaction, member: discord.Member, nick: str=None):
    if nick == None:
        await member.edit(nick=nick)
        embed = discord.Embed(title=(f"Reset {member}'s nickname"), color=0xf6ff00)
        await interaction.response.send_message(embed=embed)
    else:
        await member.edit(nick=nick)
        embed = discord.Embed(title=(f"Changed {member}'s nickname to {nick}"), color=0xf6ff00)
        await interaction.response.send_message(embed=embed)```
#

(btw the (tildetildetilde) is so Discord markdown doesn't break, normally there's 3 consecutive tildes there)

hushed galleon
#

but regardless you're likely only seeing help because you're iterating through prefix commands rather than the commands registered on your command tree

#

!d discord.app_commands.CommandTree.get_commands

unkempt canyonBOT
pulsar kettle
hushed galleon
#

if you think a guide is worth it then thats fine ig

young dagger
#

How do I insert the current date and time in Sweden instead?

import datetime

# Get the current UTC time
timestamp = datetime.datetime.utcnow()

# Insert the document into the collection
warnings_collection.insert_one({"user_id": member.id, "reason": actual_reason, "moderator_id": ctx.author.id, "timestamp": timestamp})```
crimson mauve
cedar estuary
#

can you check that how many reactions a message has? like when a message has 2 x reaction it sends a message

#

because i can't do with client.wait_for("reaction_add") because the bot puts automatically 2 different type of reactions so it would trigger the event instant

slate swan
#

Hello I have this error someone can help me?

naive briar
#

!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 does not have a traditional 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").
slate swan
naive briar
#

!d discord.Asset.url

unkempt canyonBOT
slate swan
#

page is empty

#

i can't see nothing

pulsar kettle
#

Working on the first part of an afk command, however I think I accidentally made it so you can add [AFK] to anybody's name when provided the option. How can I edit it so a user can only change THEIR OWN afk status?

@bot.tree.command(name='afk', description='Sets an AFK status to display when you are mentioned by another member')
async def afk(interaction: discord.Interaction, member: discord.Member, reason: str=None):
    if member.nick == None:
        await member.edit(nick=(f'[AFK] {member.name}'))
        embed = discord.Embed(title=(f"Changed your status to AFK | {reason}"), color=0xf6ff00)
        await interaction.response.send_message(embed=embed)
    else:
        await member.edit(nick=(f'[AFK] {member.nick}'))
        embed = discord.Embed(title=(f"Changed your status to AFK | {reason}"), color=0xf6ff00)
        await interaction.response.send_message(embed=embed)```
slate swan
hushed galleon
crimson mauve
unkempt canyonBOT
#
Noooooo!!

No documentation found for the requested symbol.

hushed galleon
crimson mauve
#

It will give you a list of the reactions in a message, subtract 2 because the bot adds some already.

hushed galleon
pulsar kettle
#

Working on handling errors with my bot, specifically the MissingPermissions one, however I cannot get the code to work. What can I do to fix it?

bot.tree.command(name='kick', description='Kicks a member from the server')
@has_permissions(kick_members=True)
async def kick(interaction: discord.Interaction, member: discord.Member, reason: str=None):
    guild = interaction.guild
    await member.send(f"You have been kicked from: ***{guild.name}*** | {reason}")
    await member.kick(reason=reason)
    embed = discord.Embed(title=(f'***{member} has been kicked*** | {reason}'), color=0xf6ff00)
    await interaction.response.send_message(embed=embed)

@bot.listen()
async def on_command_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send(":redTick: You don't have permission to kick members.")
    else:
        raise error```
#

Ideally I want the @bot.listen() to work for every command, not just the kick one I sampled

crimson mauve
pulsar kettle
crimson mauve
#
@has_permissions(kick_members=True)
@commands.command()
async def kick(interaction: discord.Interaction, member: discord.Member, reason: str=None):
#

Oh wait, you are using tree.

quick gust
#

isnt there a on_application_command_error for slash commands or something?

crimson mauve
naive briar
#

!d discord.app_commands.CommandTree.error

unkempt canyonBOT
#

@error(coro)```
A decorator that registers a coroutine as a local error handler.

This must match the signature of the [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.on_error "discord.app_commands.CommandTree.on_error") callback.

The error passed will be derived from [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError "discord.app_commands.AppCommandError").
pulsar kettle
dense merlin
#

discord.app_commands.errors.CommandInvokeError: Command 'get_blook_info' raised an exception: AttributeError: 'str' object has no attribute 'to_dict'
Halp
(example json):

"Aid_Blook": {"Desc": "A cool guy", "Img": "aid.png", "Rarity": "Uncommon"},

pythton:

async def get_blook_info(interaction:discord.Interaction,choice: Choice[int]):
  await interaction.response.defer()
  with open('blook.json') as f:
    blooks = json.load(f)
  blooks[choice.name]
  em = discord.Embed(title=choice.name, description=f'{blooks[choice.name]["Desc"]}\n\nRarity: {blooks[choice.name]["Rarity"]}')
  img = blooks[choice.name]['Img']
  await interaction.followup.send(embed=em, file=img)
#

why

timid spade
#

can a bot make a user join a vc on an interaction

#

sounds dumb but someone said it is possible

crimson mauve
unkempt canyonBOT
#

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

Moves a member to a new voice channel (they must be connected first).

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

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").

Changed in version 1.1: Can now pass `None` to kick a member from voice.
cedar estuary
#

i have a bot which sends a message to another channel when user sends the message, and when the message sended from the bot gets x amount of reactions it should dm the user who sent the message. But how do i get it inside the another event/function?

timid spade
crimson mauve
crimson mauve
cedar estuary
cedar estuary
#

wait a sec

#
@client.listen()
async def on_message(message):
     sender = message.author
    #and code

@client.listen() 
async def on_reaction_add(reaction, message):
     ## and here i want to use the sender variable```
#

i don't get it how it works, to pass the functions

crimson mauve
#

ohhh, one sec

#
@client.listen()
async def on_message(message):
     sender = message.author
    #and code

@client.listen() 
async def on_reaction_add(reaction, message):
     sender = message.author

on_reaction_add has the same exact message object as on_message

#

!d discord.Message

unkempt canyonBOT
#

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

x == y Checks if two messages are equal.

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

hash(x) Returns the message’s hash.
cedar estuary
#

so it's not the same message.author

upbeat otter
#

and store the message author id and stuff when you delete the message and send it to another channel

crimson mauve
#

Lol, looking at it again, on_reaction_add does not have message, that's supposed to be user.

#

And To get the Message being reacted, access it via Reaction.message.

#

From there you get message.author

cedar estuary
crimson mauve
#

Sorry, you lost me there. It's doing what?

#

It's the what the bot can see avatars part I'm getting lost on.

#

Oh, you want to pick one random user from that list and display they pic?

#

Let's start with just showing one random user and work up from there.

#

That's why I'm here

#

random.choice(list) is going to be your friend here.

#

Ah, that's because it's not a list, it returns a bunch of members objects, just not in a list.

#

what you want is guild.members

#

It's not going to be from ever single server the bot is a part of, only the server the command is being run in.

#

depends entirely on how you write your code.

ionic garden
#

how do i change an embed description after creating it

crimson mauve
ionic garden
#

no like

#

i've a discord.Embed(title='x')

#

and i want to change the description later

cedar estuary
crimson mauve
ionic garden
#

no

solid orbit
#

does somebody know what i have to do with this error message?:

unkempt canyonBOT
#

Hey @solid orbit!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

crimson mauve
#
TheEmbed=discord.Embed(title='x')
TheEmbed.title="Something new"
``` I think that will work.
ionic garden
#

and same for .description, i presume?

crimson mauve
light violet
#

Hey i have a conceptual question in myh mind. Like discord limits are 50 req per second btw suppose if a nuker is using ddos tool +threads to make 1m request a second then can it cuz more than 50 valid reqs??

light violet
#

Whats the login behind it

crimson mauve
#

Well, kinda.

light violet
#

Logic*

#

Discord apis may to be too fast to block all of them

crimson mauve
light violet
#

@crimson mauve its not 1k its 1m

#

So can the nuker cuz 2k bans a second

#

??

crimson mauve
light violet
#

.

crimson mauve
crimson mauve
# light violet .

So you are trying to make an anti-nuke bot that can handle 1,000,000+ attacks a second?

slate swan
#

wtf?

light violet
#

@crimson mauve thinking of

#

Btw unfortunately cant handle 50 bans only it is stopping the nuker at 75 now

#

Discor increased the limit i think so

crimson mauve
#

Anti-nukers are on the same level as antivirus software. If you are at that point you have already mess up.

slate swan
#

yea

slate swan
#

also you cant stop it if the bot just hits prune members lmao

light violet
#

Lmao

#

Cant i ban that bot in milliseconds

crimson mauve
#

Before or after it shots its shot?

slate swan
#

u can ban the bot sure but it wont stop the member pruning

light violet
#

pithink pithink just when he banned a member

#

Yes i k

slate swan
light violet
#

Btw currently my plan is to make the fastest antiban

light violet
#

Cux the nuker is using taskpool io to make 110 reqs per seconds

crimson mauve
light violet
#

Lmao the main prob is that i dont know how to talk with random people

#

Nvm

crimson mauve
#

It's good to make body armor, it's better to train people not to be in the way of the bullet.

light violet
#

I dont undertsand btw thank you for your time

crimson mauve
#

Could your bot stop my bot?

slate swan
#

if ur making anti nuke bot

#

have u patched the community spam ?

light violet
slate swan
#

that discord refuses to patch themselves lol

crimson mauve
light violet
slate swan
#

because it doesn't show in audit logs who is doing it.

light violet
#

I wil by tommorow

crimson mauve
light violet
#

Bruh i also want to learn it how do u bypass the audit log i tried every method

#

@crimson mauve howw i k that u r making requestss to the api

#

Btw i tried it to evrything got logged

crimson mauve
#

So it will log the damage done?

light violet
#

Yes it was

#

Now lemme clarify ur confusion

#

It only works in new servers

#

Btw in older servers everything gets logged

#

I tried it on my older server

#

If u need to test it there then come dm

#

I will be providing u invite of that server

young dagger
#

What is wrong with this code?

@client.command()
async def warn(ctx, member: discord.Member, *, reason: str):

    # Get the URL of the warned user's avatar
    avatar_url = member.avatar_url

    embed.set_author(name=f"Warn β€’ {member.name}#{member.discriminator}", icon_url=avatar_url)

    # Send the embed to the channel
    await channel.send(embed=embed)```
young dagger
#

Yes

torn sail
young dagger
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'url'

fading marlin
#

!d discord.Member.display_avatar consider using this instead of avatar

unkempt canyonBOT
#

property display_avatar```
Returns the member’s display avatar.

For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.

New in version 2.0.
torn sail
young dagger
#

Still doesn't work:

    # Get the URL of the warned user's avatar
    avatar_url = member.display_avatar_url

    embed.set_author(name=f"Warn β€’ {member.name}#{member.discriminator}", icon_url=avatar_url)

    # Send the embed to the channel
    await channel.send(embed=embed)```
#

Neither does avatar_url = discord.Member.display_avatar

cloud dawn
cloud dawn
#

Meaning; member.display_avatar_url has to be member.display_avatar.url

#

Since you are accessing the properties of the class discord.Asset

young dagger
#

Thank you

crimson mauve
cloud dawn
# young dagger Still doesn't work: ```python # Get the URL of the warned user's avatar ...

Also quick tip, since member is a discord.Member object the __str__ cast function will return the username and the discriminator. Meaning ```py
# Get the URL of the warned user's avatar
avatar_url = member.display_avatar_url

embed.set_author(name=f"Warn β€’ {member.name}#{member.discriminator}", icon_url=avatar_url)```

I the same as:

embed.set_author(name=f"Warn β€’ {member}", icon_url=member.display_avatar.url)
crimson mauve
#

wait, I scrolled up higher.

young dagger
crimson mauve
#

And you are passing the full mention like @young dagger when you run the command?

cloud dawn
#

Anything will do.

#

Member id, member name, member name+disc

crimson mauve
#

Huh, when did that change?

young dagger
torn sail
cloud dawn
crimson mauve
#

Β―_(ツ)_/Β―

cloud dawn
unkempt canyonBOT
#

class discord.ext.commands.MemberConverter(*args, **kwargs)```
Converts to a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member").

All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.

The lookup strategy is as follows (in order)...
torn sail
#

Lucas videos tell you can typehinting with discord.Member only accepts mentions but MemberConverter accepts ids and stuff

crimson mauve
#

I could just never get it to work with anything but mentions.

cloud dawn
torn sail
cloud dawn
torn sail
#

naming Bot as client, "json database", iterating over every banned member in unban command

cloud dawn
#

Yep..

abstract owl
#

have a code that works on user input from the bot

there's a command in it that basically sets the value as true or false

now, when i do

@client.command()
async def config_xyz(ctx, arg1):
with open('json.json', 'w') as f:
config = json.load(f)

config['xyz'] = bool(arg1)
outfile = open("json.json", "w")
json.dump(config, outfile)
await ctx.send('done')β€Š

this code somehow only changes the value for true that is if the xyz is set to false it changes that to true however doesnt do it for false. Any suggestions?

sick birch
sick birch
#

Good old Discord
Can you fix up the indents real fast?

abstract owl
#

i would but im on phone rn πŸ˜Άβ€πŸŒ«οΈ

slate swan
#

i never get tilde keys to work on phone ;.;

sick birch
#
@client.command()
async def config_xyz(ctx, arg1):
  with open('json.json', 'w') as f:
    config = json.load(f)

  config['xyz'] = bool(arg1)
  outfile = open("json.json", "w")
  json.dump(config, outfile)
  await ctx.send('done')β€Š

Does this look right?

sick birch
abstract owl
#

yep it does

#

so, what's wrong in it?

sick birch
#

!e

print(bool("True"))
print(bool("False"))
unkempt canyonBOT
#

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

001 | True
002 | True
abstract owl
#

omg what

sick birch
#

Reason being bool(str) checks if the str is truthy/falsy
It's only false when it's an empty string

#

So it doesn't do what you expect it to do

#

!e print(bool(""))

unkempt canyonBOT
#

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

False
abstract owl
#

i-wow

sick birch
#

Fortunately it's got a simple fix

abstract owl
#

what is it

sick birch
#
@client.command()
async def config_xyz(ctx, arg1: bool):
  ...
#

Discord.py will appropriately convert it to a boolean for you

abstract owl
#

ohh, so i wont have to deal with that empty string bs?

sick birch
#

No. "True" becomes True and "False" becomes False

slate swan
sick birch
#

Also things like "On", "Off", "0" and "1"