#discord-bots

1 messages · Page 653 of 1

untold token
#

instead of using .get, just use the ID and get the role object

weary gale
#

still nope

#
from discord.ext import commands

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

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

@bot.listen()
async def on_member_join(member):
    @bot.listen()
async def on_member_join(member):
    role = member.guild.get_role(123456789)
    await member.add_roles(role)
    print("AUTOROLE TEST")```
untold token
#

DUDE

weary gale
#

WHAT

#

I DID WHAT U SAID

#

oh

untold token
#

I have no words

weary gale
#

LMFAOAOO

boreal ravine
weary gale
#

sorry sorry that was an accident

boreal ravine
#

wait can you even put deco's inside a function

#

!e

def func(func):
  func()

@func
def b():
  @func
  def a():
    print(1)
  return b
b()
slate swan
#
 display_name = for member in guild.members:

How do i do this

weary gale
#
from discord.ext import commands

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

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

@bot.listen()
async def on_member_join(member):
    role = member.guild.get_role(123456789)
    await member.add_roles(role)
    print("AUTOROLE TEST")```
#

still doessnt work

boreal ravine
#

eh

maiden fable
boreal ravine
boreal ravine
untold token
unkempt canyonBOT
#

@boreal ravine :x: Your eval job has completed with return code 1.

001 | 1
002 | Traceback (most recent call last):
003 |   File "<string>", line 5, in <module>
004 |   File "<string>", line 2, in func
005 |   File "<string>", line 9, in b
006 | NameError: name 'b' is not defined
weary gale
#
from discord.ext import commands

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

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

@bot.listen()
async def on_member_join(member):
    role = member.guild.get_role(123456789)
    await member.add_roles(role)
    print("AUTOROLE TEST")```
untold token
#

That's a list comprehension

weary gale
#

what why no work

boreal ravine
untold token
#

you have two files

#

Which file are you running

weary gale
#

it runs both

untold token
#

No

slate swan
untold token
#

Not both

weary gale
#

what

boreal ravine
untold token
#

yes

weary gale
slate swan
untold token
slate swan
#

😤

untold token
#

You are still depending on cache

boreal ravine
weary gale
slate swan
untold token
slate swan
untold token
#

that tells what repl what field to run

untold token
#

If you really want a reliable one, use fetch

weary gale
boreal ravine
boreal ravine
untold token
#

then add this there

weary gale
#

right

boreal ravine
#

how are you that dumb though, just click the button??

untold token
#
language="Python"
run="python3 autorole.py"
#

if the code is in autorole file

slate swan
boreal ravine
untold token
weary gale
boreal ravine
#

yes

untold token
#

w h a t

weary gale
#

is that not what u just said

slate swan
#

😤😤😤

boreal ravine
#

nice

untold token
#

But I don't really care

weary gale
#

comes up with this and i cant run anything

boreal ravine
#

have patience

slate swan
#

cringe member.guild vs the chad getattr(member, "guild")

boreal ravine
weary gale
untold token
#

Please don't go off topic here

#

and to the fact, no one gives a shit how are you getting the Guild object

slate swan
#

wrong chat

untold token
#

So no need flex because no one cares

slate swan
untold token
#

Moving on

slate swan
#

!ot

unkempt canyonBOT
untold token
weary gale
untold token
#

Good

#

Now hit run

weary gale
#

it doesnt work

untold token
#

The big green button

weary gale
#

yes

untold token
weary gale
#

yeah

untold token
#

Show it

weary gale
#

wdym?

#
from discord.ext import commands

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

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

@bot.listen()
async def on_member_join(member):
    role = member.guild.get_role(8932912395942)
    await member.add_roles(role)
    print("AUTOROLE TEST")```
untold token
weary gale
#

yes

weary gale
untold token
#

bot.run("token")

weary gale
#

i cant run

#

LMFAOOO

untold token
#

you didn't even add the run method at the end

weary gale
#

ISTG IM SO SMART

untold token
wary ice
#

good morning the command with what you send screenshot how it is what I have circled

untold token
#

What

#

I don't your understand your question

#

Please elaborate

wary ice
#

When I send a photo I want the bot to send it as it is command?

untold token
#

Um

#

So you want send a bot a picture and the bot will send that image in an embed?

wary ice
#

yes

untold token
#

Then you need to read the attachment of the message and send it an embed use the
Embed.set_image() method

#

So

#

!d discord.Message.attachments

unkempt canyonBOT
untold token
#

!d discord.Embed.set_image

unkempt canyonBOT
#

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

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

Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
wary ice
#

ok to ask something else on_message made an error

#
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\user\OneDrive\Υπολογιστής\Bots\main.py", line 112, in on_message
    await message.channel.send(embed=emb)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_components\dpy_overrides.py", line 350, in send_override
    return await send(channel, *args, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_components\dpy_overrides.py", line 325, in send      
    data = await state.http.send_message(
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 248, in request
    raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access```
untold token
#

Code?

wary ice
#
async def on_message(message):
    channel = bot.get_channel('916945441696911371')
    emb = discord.Embed(title=f"{message.content}", description=f"", timestamp=datetime.datetime.utcnow(),color=0xffffff)
    emb.set_footer(text='Test', icon_url="https://cdn.discordapp.com/attachments/904787287857045504/916061762388914206/logo-advertising-image-marketing-brand-png-favpng-TRmTVi08NnDGxE9Pi3TsdhZbW.jpg%22")
    emb.set_author(name=f"{message.author.name}",
    icon_url=f"{message.author.avatar_url}")
    await message.channel.send(embed=emb)
    await message.delete()
untold token
wary ice
#

ok now?

untold token
#

second, it's trying to send a message to a channel where the bot cannot send the message

#

That's why its raising an missing access error

untold token
#

Yes it will spam

#

Because it's a message event

#

Every time someone sends a message the bot is also going to send the message

#

So yeah

weary gale
#

wtf

untold token
#

So

wary ice
#

yes

untold token
#
@bot.listen()
async def on_message(message):
    if message author == bot.user:
   return  # this statement is important so that the bot doesn't respond to it's own messages 
#

!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/master/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.9)").

Example...
wary ice
#
async def on_message(message):```
#

here?

untold token
#

and you could create a command using the commands framework instead of use message events to make commands

#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
untold token
#

There are examples in the documentation

#

That you can refer too

weary gale
#

WAIT

#

oh

wary ice
#
async def on_message(message):
    channel = bot.get_channel('916945441696911371')
    emb = discord.Embed(title=f"{message.content}", description=f"", timestamp=datetime.datetime.utcnow(),color=0xffffff)
    emb.set_footer(text='Test', icon_url="https://cdn.discordapp.com/attachments/904787287857045504/916061762388914206/logo-advertising-image-marketing-brand-png-favpng-TRmTVi08NnDGxE9Pi3TsdhZbW.jpg%22")
    emb.set_author(name=f"{message.author.name}",
    icon_url=f"{message.author.avatar_url}")
    await message.channel.send(embed=emb)
    await message.delete()```
#

this? @untold token

weary gale
#

@untold token

shadow wraith
#

whats da issue heer

weary gale
#

it wont run

untold token
shadow wraith
weary gale
# shadow wraith code which you think is causing the error
from discord.ext import commands
import os

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

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

@bot.listen()
async def on_member_join(member):
    role = member.guild.get_role(8932970013213218975422295942)
    await member.add_roles(role)
    print("AUTOROLE TEST")```
shadow wraith
#

🤔

wary ice
#

@untold token 2 probs

shadow wraith
#

bro why do you have your command_prefix like that

shadow wraith
#

its the same prefix defined twice in a list wtf?????

untold token
#

Lol

shadow wraith
#

also its member: discord.Member not just member

weary gale
shadow wraith
untold token
#

Will not affect the code

shadow wraith
untold token
#

O

shadow wraith
#

🤔

shadow wraith
wary ice
#

@untold token know?

untold token
#

you are missing a .

weary gale
#

doesnt run

untold token
#

message.author

untold token
#

Is the bot online?

weary gale
#

yeah

#

it just

#

didnt print

#

and the status isnt working anymore

#

idek why

untold token
#

You need to learn basic python

weary gale
#

ive just ruined my bot

#

for a code that doesnt even work

untold token
#

Hmm

weary gale
#

WAIT IT WORKS

#

NO WAY

untold token
#

Good

weary gale
#

but everything else doesnt

#

like literally all of my other commands dont work

untold token
weary gale
#

oh do i just copy the line and add main.py

#

i can run both right

#

@untold token the way ive done it doesnt work

#

how do i run both? im sorry for all this btw

#

such a pain

#
run="python3 autorole.py"
run="python3 main.py"```
untold token
#

You can't run both, create a single file and add all of your code in it

#

That won't work bruh

weary gale
#

oh

untold token
#

and then it will work

weary gale
#

ok

untold token
#

Make sure you only add the event

#

not other stuff

#

like the commands.Bot() and the imports

weary gale
#

ye ik

#

if i were that dumb, jeez

untold token
#

Works

weary gale
#

ges

untold token
#

?

weary gale
#

yes

untold token
#

Good job

weary gale
#

tysm

untold token
#

Now learn basic python

weary gale
#

will do

untold token
#

Because you did make me loose brain cells today

weary gale
#

lmaooo

untold token
#

But its fine

#

Atleast you learnt something

weary gale
#

i feel accomplished

gaunt ice
velvet tinsel
#

hi ! a

gaunt ice
#

halp i got rate limited

velvet tinsel
#

....

#

you got ratelimited. you went above the ratelimit

gaunt ice
#

wuts ratelimit.......

#

am noob so dont get angwy

velvet tinsel
#

its basically when discord receives too many requests i think

gaunt ice
#

ohh

velvet tinsel
#

and so they do that to stop spam

#

so their servers wont crash

gaunt ice
#

how can i fixx this now

velvet tinsel
#

put a limit to your code

#

show me your code ;-;

gaunt ice
#

oki

#

i mean its big

velvet tinsel
#

not whole code

#

just the function

gaunt ice
#

u mean the events?

velvet tinsel
#

vents?

gaunt ice
#

oh wait the commands

velvet tinsel
#

no like

@client.command()
async def foo(ctx):
  await ctx.send("foo")
#

that function
or command ig

#

or event

gaunt ice
#

i have a lot of commands

#

like a lot

velvet tinsel
#

just that one command

gaunt ice
#

that which command

velvet tinsel
#

300 I think

#

line 300?

#

the one that's causing the error

gaunt ice
#

oki

velvet tinsel
#

data = await...

gaunt ice
#

i.........

velvet tinsel
#

maybe...someone spammed the command?

#

idt thats causing the error tbh

gaunt ice
#

oh

velvet tinsel
#

oh wai

#

your bot is blocked ;-;

gaunt ice
#

whaaa

#

wha shud i do

#

):

#

umm that member is sus

#

so...

#

um

#

it is

#

llol

brave ravine
#

im trying to implement my hangman game into my bot and i dont know how to read a user input through discord to act as the letter guessed

untold token
#
message = await bot.wait_for("message", timeout=60)
message_content = message.content
brave ravine
#

thank you

untold token
#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). 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.9)") 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.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
untold token
#

Bruh the docs use message events as commands

brave ravine
#

how would i ctx.send() something the same way i would print(letters, end = "")

maiden fable
brave ravine
maiden fable
#

!join

unkempt canyonBOT
#

Joining Iterables

If you want to display a list (or some other iterable), you can write:

colors = ['red', 'green', 'blue', 'yellow']
output = ""
separator = ", "
for color in colors:
    output += color + separator
print(output)
# Prints 'red, green, blue, yellow, '

However, the separator is still added to the last element, and it is relatively slow.

A better solution is to use str.join.

colors = ['red', 'green', 'blue', 'yellow']
separator = ", "
print(separator.join(colors))
# Prints 'red, green, blue, yellow'

An important thing to note is that you can only str.join strings. For a list of ints,
you must convert each element to a string before joining.

integers = [1, 3, 6, 10, 15]
print(", ".join(str(e) for e in integers))
# Prints '1, 3, 6, 10, 15'
brave ravine
#

thank you

untold token
maiden fable
#

Ah hmm

heavy folio
#
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 351, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\user\Desktop\theBot\cogs\afk.py", line 111, in on_message
    for id in self.afk.keys():
RuntimeError: dictionary changed size during iteration```how do i prevent his from happening?
#
        for id in self.afk.keys():
            await asyncio.sleep(1)
            if message.author.id == id:
                del self.afk[id]

                embed = discord.Embed(
                    description=f"{self.bot.tick_emoji} Welcome back **{message.author.display_name}**! I have removed your afk.",
                )

                return await message.channel.send(f"{message.author.mention}", embed=embed)
```code (on_ready)
#

ignore self.bot.tick_emoji just some bot var

#
    @commands.command(aliases=['afk'])
    async def awayfromkeyboard(self, ctx, message="AFK"):
        self.afk[ctx.author.id] = message

        self.bot.afk_time = datetime.datetime.now().timestamp()

        embed = discord.Embed(
            description=f"{self.bot.tick_emoji} **{ctx.author.display_name}**'s AFK: {message}",
            color=ctx.author.color
        )
        await ctx.reply(f"{ctx.author.mention}", embed=embed)```code (command)
brave ravine
#

thank you to everyone that helped me, my game is working as it should now

#

funny this is, i originally wrote the game in java for a homework assignment and then translated it into python

boreal ravine
#

ah nice

boreal ravine
# heavy folio ```py Ignoring exception in on_message Traceback (most recent call last): File...

I think the error means when the bot was trying to iterate through the dict (self.afk.keys) it changed sizes. I looked at https://stackoverflow.com/questions/11941817/how-to-avoid-runtimeerror-dictionary-changed-size-during-iteration-error and it says you can cast the dict self.afk.keys to a list to prevent this from happening but I'm not really sure lol

full valley
#

Holy mother of if statements:

if any(ctx.author.id in each_list for each_list in team1_ids.values()) is True and outcome in win_outcome or any(ctx.author.id in each_list for each_list in team2_ids.values()) is True and outcome in loss_outcome:
slate swan
#

w

#

t

#

f

vocal plover
#

there's no need for the is True parts of that, since any() and in will return truthy or falsy (or in this case just True or False) values anyway

heavy folio
slate swan
vocal plover
#

yeah pretty much

#

for example "str" is truthy because it's a string with characters, whereas "" is falsy because its empty

jade tartan
#

Ohh change the name each time you mean? If that’s the case makes more sense

#

But am letting the bot give autorole to the member joins the server if that make sense hence why am using the client.get_guild

boreal ravine
#

hm

#

well they key doesnt exist

#

try going afk first?

heavy folio
slate swan
#

hi can someone help me i have this problem how can i make it so that the names go into one embed this is my code ```py

@commands.has_permissions(ban_members=True)
@commands.command()
async def banlist(self,ctx,):
    banlist = await ctx.guild.bans()
    for ban in banlist:
        user = ban.user.name + "#" + ban.user.discriminator
        embed = discord.Embed(title = "Users Banned", description=user,color=0x910707)
        await ctx.send(embed=embed)
boreal ravine
forest lion
#

hey kayle

#

Guess who fixed it

boreal ravine
#

!e

banned_users = ["kayle", "night"]
print(", ".join(banned_users))
``` ^
boreal ravine
unkempt canyonBOT
#

@boreal ravine :white_check_mark: Your eval job has completed with return code 0.

kayle, night
slate swan
#

that makes more sense thx so much : )

boreal ravine
#

👍

forest lion
#

just a little someone I know 😎

boreal ravine
#

ah cool

forest lion
#

Took me forever and a half to figure out

#

but I ended up going this route

#

user = queue[0]
queued = get(self.client.get_all_members(), id=user)
if queued != None:
await queued.send("Hello! Please prepare yourself, your trade it about to begin.")

#

indents are off from copy and paste but yeah

slate swan
#

but its not a list i dont think

boreal ravine
#

you use it on a list

boreal ravine
# heavy folio ^

check if the id is in there, if it isnt, use the return keyword

heavy folio
slate swan
heavy folio
#

why not use add field

boreal ravine
slate swan
boreal ravine
#

fields have a max limit

heavy folio
#

no not field

#

i mean the uh

boreal ravine
#

what

heavy folio
#

use the description

slate swan
heavy folio
#

you didnt

boreal ravine
slate swan
#
            embed = discord.Embed(title = "Users Banned", description=user,color=0x910707)
boreal ravine
#

^^

heavy folio
#

i mean for each banned user

boreal ravine
#

hes using the description to do that

heavy folio
boreal ravine
#

^^ move it outside the loop

heavy folio
#

yh

slate swan
#

ohh ok let me try

boreal ravine
slate swan
#

i only get 1 person who is banned

#

that’s not a database?

boreal ravine
#

iterate through ctx.guild.bans, append the users to the list, use join on the list

prisma spoke
slate swan
#

i did something new ```py
user = [ban.user.name + "#" + ban.user.discriminator for ban in banlist]

boreal ravine
boreal ravine
#

just append ban to a list

#

and join it somewhere

#

something like this~ ```py
ban = await ctx.guild.bans()
list = []

for user in ban:
list.append(user)

prisma spoke
#

DBbrowser for sqlite

boreal ravine
#

sqlite, sqlite3, asqlite, etc is a database

heavy folio
#

sql is structured query language

boreal ravine
#

^

heavy folio
#

sqlite is a db

prisma spoke
#

sry mb

#

SQlite

boreal ravine
#

if you wanna know if its a language, do this because discord can detect almost every language I think and if its highlighted that means its a language

prisma spoke
#

And i think i solved it also that issue of yesterday

boreal ravine
#

oh cool

prisma spoke
prisma spoke
boreal ravine
#

I mean

prisma spoke
#

dogs is also a language

boreal ravine
#

JSON is a database, but it isn't at the same time

prisma spoke
#

tiget is also a language

boreal ravine
prisma spoke
#

cobra is also a language

prisma spoke
boreal ravine
prisma spoke
#

used for config files

prisma spoke
#

it isnt ded

boreal ravine
prisma spoke
#

ppl still use it

boreal ravine
prisma spoke
#

zebra is also a language

boreal ravine
#

dude

prisma spoke
#

every animal name is mostly a language

slate swan
#

how do i get every message within a channel from specific user, i thought it would be this.. but didnt work


async for x in channel.history(limit=None, oldest_first=True, check=lambda e: x.author.id == 1290381039813209):
  #etc
boreal ravine
#

why are you listing every language 70% of people have never heard of

slate swan
#

Juliayert Is a lot similar to python

boreal ravine
#

and also author doesnt have an id attribute

slate swan
prisma spoke
#

i mean if C is a language then D must be to..

boreal ravine
prisma spoke
slate swan
spring flax
boreal ravine
prisma spoke
#

its wavelength in sound terms

boreal ravine
prisma spoke
#

..

boreal ravine
#

Bruh

boreal ravine
#

since x returns a discord.Message object, you could check for the member's id

boreal ravine
prisma spoke
boreal ravine
#

i cant tell you everything that i cant explain well

prisma spoke
#

whats the use of it?

boreal ravine
visual island
#

shorten your code

boreal ravine
#

smh

prisma spoke
spring flax
#

!d lambda

unkempt canyonBOT
#

An anonymous inline function consisting of a single expression which is evaluated when the function is called. The syntax to create a lambda function is lambda [parameters]: expression

prisma spoke
#

its smthn like pass

boreal ravine
#

no it isnt

prisma spoke
prisma spoke
boreal ravine
#
prisma spoke
#

and how to make a title of an embed as hyperlink?

boreal ravine
boreal ravine
boreal ravine
unkempt canyonBOT
prisma spoke
#

alr

boreal ravine
#

👍

jade tartan
#

Wait am confused

#

Lol

velvet tinsel
#

Hai kayle 🙂

slate swan
#

when recieving an embed, it has returned back 16685769 for its colour, is that hex or what?

verbal cairn
#

If I want to get like API data from a json link every 5 minutes I use tasks right

verbal cairn
#

Yep idfk how to do that

upbeat otter
#

code?

#

and output?

slate swan
#

nevermind it returned the decimal value, i figured it out

upbeat otter
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

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

So if I like

@tasks.loop
Async def some_name(minutes=5.0)
   bz = requests.get(url).json()
#

Is bz the global variable

upbeat otter
#

you need to global it

#

!d global

unkempt canyonBOT
#

7.12. The global statement


global_stmt ::=  "global" identifier ("," identifier)*
``` The [`global`](https://docs.python.org/3/reference/simple_stmts.html#global) statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without `global`, although free variables may refer to globals without being declared global.

Names listed in a [`global`](https://docs.python.org/3/reference/simple_stmts.html#global) statement must not be used in the same code block textually preceding that `global` statement.

Names listed in a [`global`](https://docs.python.org/3/reference/simple_stmts.html#global) statement must not be defined as formal parameters, or as targets in [`with`](https://docs.python.org/3/reference/compound_stmts.html#with) statements or [`except`](https://docs.python.org/3/reference/compound_stmts.html#except) clauses, or in a [`for`](https://docs.python.org/3/reference/compound_stmts.html#for) target list, [`class`](https://docs.python.org/3/reference/compound_stmts.html#class) definition, function definition, [`import`](https://docs.python.org/3/reference/simple_stmts.html#import) statement, or variable annotation.
upbeat otter
#
global bz
#

^

#

like this

visual island
#

!botvar or this is easier

unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

upbeat otter
#

oh I see

heavy folio
#

botvars are better

verbal cairn
#

Im lost now

#

So do I global bz or how

heavy folio
#

no

heavy folio
maiden fable
#

!global will explain u why

unkempt canyonBOT
#

When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.

Instead of writing

def update_score():
    global score, roll
    score = score + roll
update_score()

do this instead

def update_score(score, roll):
    return score + roll
score = update_score(score, roll)

For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.

verbal cairn
#

Ok but which version is better

#

The bot version or just setting the variable when calling the function

slate swan
#

just got done using alot of globals B)

boreal ravine
slate swan
#

!d help

unkempt canyonBOT
#

help([object])```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).

This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
slate swan
#

!d help fun

unkempt canyonBOT
#

help([object])```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).

This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
velvet tinsel
slate swan
#

!d user ping

unkempt canyonBOT
#

NumPy user guide

This guide is an overview and explains the important features; details are found in Command Reference...

velvet tinsel
maiden fable
#

!d discord.Client.latency

unkempt canyonBOT
#

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

This could be referred to as the Discord WebSocket protocol latency.
proven aurora
#

is there a voicechat mute function?

slate swan
#

servermute

maiden fable
unkempt canyonBOT
#

await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the member’s data.

Depending on the parameter passed, this requires different permissions listed below...
proven aurora
#

the mute

maiden fable
#

Yea the mute kwarg, set it to True

proven aurora
#

ohh alright thanks

crimson tendon
#

How do I remove the "answer to" with discord-py-slash-commands ?

proven aurora
#

wait no

vocal plover
#

slash commands use replies, there's no way to not do so

proven aurora
#

its for something else

proven aurora
#

wait nvm

#

my bad

crimson tendon
vocal plover
#

Welcome to 'discord thinks they know what devs want better than the devs'

crimson tendon
#

and in DM's, it works without doing a reply...

Nice job discord 😭

proven aurora
#

it worked thanks

slate swan
maiden fable
slate swan
manic wing
#

!d discord.Member.mention

unkempt canyonBOT
maiden fable
#

Ah that

velvet tinsel
#

hi hunter and Caeden

proven aurora
#

how do I get the people that are in a voicechat

#

lets say these

red blade
#
        if user is None:
            create_level_account(ctx.author, ctx.guild, ctx.message)
            data = get_data()
            level = data[str(ctx.guild.id)]["users"][str(ctx.author.id)]["level"]
            await ctx.send(f"You are level {level}")
        elif not user is None:
            create_level_account(ctx.author, ctx.guild, ctx.message)
            data = get_data()
            level = data[str(ctx.guild.id)]["users"][str(user.id)]["level"]
            await ctx.send(f"You are level {level}")``` why is the `if` working but the `else` raises a key error?
#

its literally the same

manic wing
unkempt canyonBOT
manic wing
proven aurora
#

doesn't make sense

red blade
#

i tried else aswell

manic wing
red blade
#

ye it does not after the if checks if that is NOT the case

manic wing
#

!e py x = 1 if not x is None: print('...')

unkempt canyonBOT
#

@manic wing :white_check_mark: Your eval job has completed with return code 0.

...
manic wing
#

works fine.

velvet tinsel
#

it's funny how Python does not include grammar

manic wing
#

!e py x = 1 if not x is not None: print('...')

unkempt canyonBOT
#

@manic wing :warning: Your eval job has completed with return code 0.

[No output]
velvet tinsel
#
if you is not None:

should be

if you are not None:
boreal ravine
#

Am I dumb? it's giving me a syntax error for some reason

velvet tinsel
#

seems like you indented it wrong

velvet tinsel
#

or actually you put an extra bracket

manic wing
red blade
manic wing
#

but yeah the indentation is wrong.

boreal ravine
# manic wing funnily enough, you covered the line before which we need to see.

        for image_id, link, name, owner in zip(image_ids, links, names, owners):
            embeds.append(
                disnake.Embed(
                    description=f"Displaying `{name}` by <@{owner}> (ID: {image_id})",
                    color=disnake.Color.blurple(),
                ).set_image(url=link)
        
        await ctx.send(
            embed=disnake.Embed(
                title=f"{member}'s Profile",
                description=f"Images: {image_ids}",
                color=disnake.Color.blurple()
                ), view=EmbedPaginator(
                    ctx, embeds
                    )
                    )
``` ^^^
boreal ravine
manic wing
slate swan
boreal ravine
red blade
#

its the EXACT same code just a different member given

boreal ravine
#

thanks carrot

slate swan
#

👍

boreal ravine
#

useless print statements always making me delete stuff that doesnt need to be deleted smh

upbeat otter
#

you are creating a new account for the user in both the cases, even when the user if in the data, it cant create 2 accounts for the same id

velvet tinsel
#

I thought you were a beginner for a second Kayle

velvet tinsel
#

I am really disappointed.

upbeat otter
velvet tinsel
velvet tinsel
#

*undisappoints myself*

slate swan
velvet tinsel
#

:)

red blade
# upbeat otter <@!477483698795839492>
            create_level_account(ctx.author, ctx.guild, ctx.message)
            data = get_data()
            level = data[str(ctx.guild.id)]["users"][str(ctx.author.id)]["level"]
            await ctx.send(f"You are level {level}")
        else:
            create_level_account(user, ctx.guild, ctx.message)
            data = get_data()
            level = data[str(ctx.guild.id)]["users"][str(user.id)]["level"]
            await ctx.send(f"You are level {level}")
        ``` wtf this still doesnt work!?
upbeat otter
velvet tinsel
#

Eevee do be roasting though

upbeat otter
#

smh sorry

upbeat otter
# red blade ``` if user is None: create_level_account(ctx.author, ctx.gui...
if user is None:
            create_level_account(ctx.author, ctx.guild, ctx.message)
            data = get_data()
            level = data[str(ctx.guild.id)]["users"][str(ctx.author.id)]["level"]
            await ctx.send(f"You are level {level}")
else:

            data = get_data()
            level = data[str(ctx.guild.id)]["users"][str(user.id)]["level"]
            await ctx.send(f"You are level {level}")
upbeat otter
#

see the indents

velvet tinsel
#

happy eevee

upbeat otter
#

xD

velvet tinsel
#
if active:
                                                      print("lovely indents")
proven aurora
untold token
#

Hm

velvet tinsel
#

how to air

upbeat otter
velvet tinsel
#

wait really

untold token
velvet tinsel
#

wtf
I thought he was an expert

proven aurora
manic wing
#

no.

proven aurora
#

how do I use this

velvet tinsel
proven aurora
#

😐

velvet tinsel
proven aurora
velvet tinsel
#

i mean there are docs

proven aurora
untold token
#

Uhm

velvet tinsel
#

they do help

maiden fable
#

@proven aurora what happened?

#

Calm down

upbeat otter
velvet tinsel
#

I love the docs

manic wing
# unkempt canyon

voice_channel_members = voice_channel.members where voice_channel is an instance of discord.VoiceChannel

proven aurora
#

how do i use discord.VoiceChannel.members

maiden fable
proven aurora
#

ohhh

untold token
#

Yeah that's what I told

maiden fable
#

guild.get_channel(id).members

proven aurora
#

okay thank you

untold token
#
channel = guild.get_channel(ID)
members = channel.members
velvet tinsel
#

Caeden

untold token
velvet tinsel
#

when did you start learning Python

proven aurora
#

so..

proven aurora
#

I AM CONFUSED.

upbeat otter
velvet tinsel
boreal ravine
#

nice

manic wing
upbeat otter
boreal ravine
#

python is sooo easy

untold token
velvet tinsel
#

look

upbeat otter
untold token
#

If you want to get the names of the members then jus loop through the list

#

and get it

velvet tinsel
#
make a game
proven aurora
#
for i in ctx.author.voice_channel.members:
  print(i)```
velvet tinsel
#

done I coded python

proven aurora
#

i cant do this?

upbeat otter
velvet tinsel
#

yeah
I made a cool game ima call it Minecraft

boreal ravine
#

ghost pinged

untold token
upbeat otter
#

oof

untold token
#

!d discord.VoiceState

unkempt canyonBOT
upbeat otter
#

cheap Minecraft otherwise

untold token
#

so like

velvet tinsel
upbeat otter
untold token
#
members = ctx.author.voice.members
names = [member.name for member in members]
#

@proven aurora

proven aurora
#

🙂

untold token
#

VoiceState returns a lot of data about a Members state

#

Like the voice channel they joined

#

Channel ID, are they deaf, are they afk

#

Etc etc

#

It has attributes that you can use to your will

velvet tinsel
#

how to air

proven aurora
#

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

untold token
#

!d discord.VoiceState

unkempt canyonBOT
velvet tinsel
#

if you're a certified discord dev why are you not googling stuff 🤔

proven aurora
untold token
#

My bad

manic wing
untold token
#

Huh?

#

I just made a simple mistake

#

I have used dpy for a long time

velvet tinsel
#

quietly leaves the room

untold token
#

!d discord.VoiceState.channel

unkempt canyonBOT
#

The voice channel that the user is currently connected to. None if the user is not currently in a voice channel.

proven aurora
#

it worked

untold token
#

There you are

proven aurora
#

yea

velvet tinsel
#

enters the room

proven aurora
#

thank you

unkempt jewel
#

can i boost this server

manic wing
#

no.

unkempt jewel
#

ok

untold token
#

Moving on

boreal ravine
#

!e None

upbeat otter
velvet tinsel
#

!d None

unkempt canyonBOT
#

None```
An object frequently used to represent the absence of a value, as when default arguments are not passed to a function. Assignments to `None` are illegal and raise a [`SyntaxError`](https://docs.python.org/3/library/exceptions.html#SyntaxError "SyntaxError"). `None` is the sole instance of the `NoneType` type.
boreal ravine
velvet tinsel
upbeat otter
#

lmao

boreal ravine
#

i just wanted to see what it returned

velvet tinsel
#

!e

None
unkempt canyonBOT
#

@velvet tinsel :warning: Your eval job has completed with return code 0.

[No output]
velvet tinsel
#

see
😛

untold token
#

#bot-commands lol

#

Don't go off topic here

velvet tinsel
#

goddammit ! a

boreal ravine
untold token
#

Nice name

velvet tinsel
#

bonbons

#

😳

boreal ravine
modern fiber
#

Hm, why am I getting this error guys?

velvet tinsel
#

1 million dank memer coins :kek:

proven aurora
#

you cant send messages to the bot?

boreal ravine
proven aurora
modern fiber
modern fiber
velvet tinsel
#

actually 5

upbeat otter
velvet tinsel
#

code

upbeat otter
proven aurora
velvet tinsel
#

!ot

unkempt canyonBOT
maiden fable
#

Me who doesn't use dank memer

velvet tinsel
#

GOT THERE BEFORE YOU HUNTER

#

TAKE THAT
AHAHAHHAHAHHA

untold token
#

Um

modern fiber
maiden fable
upbeat otter
velvet tinsel
upbeat otter
velvet tinsel
#

send code here.

maiden fable
untold token
#

Send it here

upbeat otter
#

smh

maiden fable
velvet tinsel
#
def code():
  """this is a code"""
velvet tinsel
#

I breathe carbon dioxide

manic wing
untold token
#

Don't make this channel off topic

velvet tinsel
velvet tinsel
unkempt canyonBOT
maiden fable
#

!ot @velvet tinsel @manic wing

velvet tinsel
#

:)

maiden fable
#

I don't really care

untold token
#

Pinging mods would work though

velvet tinsel
#

is it ok if I call you hth

maiden fable
#

Facts

velvet tinsel
untold token
#

No

#

And lets move on now

maiden fable
#

Can ya stop this? @velvet tinsel

velvet tinsel
#

ok

maiden fable
#

Let's keep this on topic

velvet tinsel
untold token
velvet tinsel
#

ok
discord bots
I like discord bots

slate swan
#

async def _gstart(self,ctx,timee,winners:typing.Optional[str],*,message):
message is a required argument that is missing.

upbeat otter
#

,-,

maiden fable
untold token
#

pep 8....

slate swan
slate swan
upbeat otter
slate swan
maiden fable
manic wing
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.9)"). 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.9)") 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.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.

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

k ty

upbeat otter
maiden fable
#

?

upbeat otter
maiden fable
#

I just told a simple answer to them

slate swan
slate swan
#

should i just format it like time message winners

untold token
#
async def _gstart(self, ctx: commands.Context, timee, winners: typing.Optional[str], *, message: str=None):

Pass something default to make it optional

In this case, if you don't pass a message anything the message arg, it will defaulted to None

upbeat otter
maiden fable
#

Don't blame me

slate swan
#

this server is way better than dpy

upbeat otter
slate swan
#

and mods here are more mature

untold token
#

Less toxic

slate swan
slate swan
slate swan
#

lets not talk about that

slate swan
#

ok

untold token
#

Yes

#

Let's not rant here about other Servers

slate swan
#

kk

maiden fable
#

Yea lets not make this OT again. I'mma be shut 🤐

untold token
#

If you didn't pass anything then it is None by default

slate swan
#

hmmm

untold token
#

!e
def func(a: str, *, b: str = None):
print(f"{a}, {b}")

func(a="hello")

slate swan
#

yea

untold token
#

!e

def func(a: str, *, b: str = None):
   print(f"{a}, {b}")

func(a="hello")
unkempt canyonBOT
#

@untold token :white_check_mark: Your eval job has completed with return code 0.

hello, None
untold token
#

See, I didn't pass anything on the B argument, so its None

#

now

modern fiber
#

Im getting this one again

boreal ravine
#

How do I get something that isn't defined yet? like is it possible```py
class A(discord.ui.View):
def init(self, msg):
...

#somewehre else

await ctx.send(content="Test", view=A(...)) #i want this send function to be the argument in A

slate swan
#

how would i make it so that i could do the message first instead of the winners then

untold token
#

!e

def func(a: str, *, b: str = None):
   print(f"{a}, {b}")

func(a="hello", b="world")
unkempt canyonBOT
#

@untold token :white_check_mark: Your eval job has completed with return code 0.

hello, world
untold token
#

See

boreal ravine
tacit token
#

How can I do language packs on my Discord Bot? 😄

maiden fable
slate swan
boreal ravine
#

Not knowing enough python there can be.. 😬

maiden fable
#

I guess just use a translator module?

tacit token
#

i want people to choose their language and it will go with the stick

mint salmon
#

i want to create a image manipulation command. which takes user's pfp and make sth like this. idk how to get this effect. its not blur filter, may be speed filter idk

maiden fable
#

U wanna pass the message u gonna send, to A right?

mint salmon
#

sry to barge in in middle

boreal ravine
#

ah man :(

unkempt canyonBOT
maiden fable
#

!pypi pillow

unkempt canyonBOT
maiden fable
#

This one, use this ^^^

#

Not PIL

mint salmon
# maiden fable !pypi PIL

ik that
just dont know wow to get that specific filter
kinda in need of google search query for that

boreal ravine
#

it doesnt look like a filter

#

more like another image, even if it is a filter thats some impressive code lol

tacit token
#

so. There would be a panel like in mee6 to change the language of the bot. When I write, for example, he will write in German.

boreal ravine
#

i think you gotta do that manually

maiden fable
boreal ravine
#

or that

mint salmon
maiden fable
#

Type all the text in a single file and just translate those before sending to the channel

tacit token
#

how?

#

I also tried that when I click on the inv link, the bot is on the page in several languages, and so on. So far, the English and Hungarian are ready.

maiden fable
# tacit token how?

Make a file something named

#constants.py
ALL THE TEXTS OF ALL THE COMMANDS AND STUFF

And before passing those to a command, just translate all that text into another language

#

Don't manually write all those translations u gonna get bored in a day

tacit token
#

if I wrote everything in it so I could swap it for those texts? I tried yesterday but did not recognize the texts in main.py

maiden fable
#

Wym

tacit token
#

what

slate swan
#

its used in @unkempt canyon

#

sure in the constants file

unkempt canyonBOT
#

bot/constants.py lines 247 to 255

class Colours(metaclass=YAMLGetter):
    section = "style"
    subsection = "colours"

    blue: int
    bright_green: int
    orange: int
    pink: int
    purple: int```
burnt inlet
#

@client.command(aliases = ['purge', 'delete']) async def clear(ctx, amount: int = 1): await ctx.channel.purge(limit = amount)

#

why this not work

slate swan
#

!code

unkempt canyonBOT
#

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.

burnt inlet
#

no error

#

i can run this

slate swan
#

sure run it

burnt inlet
#

and its not work

#

client = commands.Bot(command_prefix = "#", intents=intents)

#

i just need type #clear 5

#

but its clear nothing

velvet tinsel
#

Oh

#

I see

#

Remove the int

#

And add await ctx.purge(limit = int(amount))

#

So like async def clear(ctx, amount):

#

Try that see if it works

burnt inlet
#

thats not work

#

@client.command(aliases = ['purge', 'delete'])
async def clear(ctx, amount):
await ctx.purge(limit = int(amount))

#

you meant like this?

maiden fable
untold token
#

how come it's not raising an error though

gaunt ice
#
@commands.cooldown(1, 6, commands.BucketType.user)
@commands.has_permissions(manage_roles=True)
async def delete(ctx, limit: int): 
 await ctx.channel.purge(limit=limit+1)
 purgeMessage = await ctx.send(f"Purged {limit} messasges ")
 await asyncio.sleep(3)
 await purgeMessage.delete()```
maiden fable
untold token
#

Oh hmm

maiden fable
#

Since commands.Context subclasses abc.Messageable too

untold token
#

Ouh yeah

boreal ravine
#
Ignoring exception in on_message
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/disnake/client.py", line 505, in _run_event
    await coro(*args, **kwargs)
  File "/home/runner/bonbons-1/cogs/fun.py", line 73, in on_message
    if not mention_data["reason"]:
KeyError: 'reason'
``` I'm using `not`, why is it giving a keyerror
lament mesa
boreal ravine
lament mesa
#

Nope, not only flips the boolean value

shadow wraith
velvet tinsel
#

😦

#

:depress:

shadow wraith
#

it just autoindents it.

velvet tinsel
#

Where is Myxi

#

@sullen shoal I miss you

boreal ravine
lament mesa
velvet tinsel
#

@slate swan I miss you 😦

sullen shoal
lament mesa
#

!d dict.get

unkempt canyonBOT
#

get(key[, default])```
Return the value for *key* if *key* is in the dictionary, else *default*. If *default* is not given, it defaults to `None`, so that this method never raises a [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError "KeyError").
velvet tinsel
#

YOURE BACK ❤️

boreal ravine
sullen shoal
#

yep

velvet tinsel
#

What happened

#

You were inactive for about a week

sullen shoal
#

not inactive, im trying new stuff

velvet tinsel
#

Ok

#

miss you 😢

shadow wraith
#

like what im starting to get bored with coding

#

i do wanna check out nextcord and stuff 🤔

velvet tinsel
#

In the shadows

boreal ravine
# lament mesa That key doesn't exist
        if message.mentions:
            for member in message.mentions:
                mention_data = await afk_db.find_one({"_id": member.id})
                if mention_data:
                    if member.id == mention_data["_id"]:
                        if not mention_data["reason"]:
                            await message.channel.send(
                                embed=disnake.Embed(
                                    description=f"{member.mention} is AFK. Since <t:{mention_data['timestamp']}:R>"
                                ),
                                allowed_mentions=disnake.AllowedMentions(
                                    everyone=False, users=False, roles=False
                                ),
                            )

                        else:
                            await message.channel.send(
                                embed=disnake.Embed(
                                    description=f"{member.mention} is AFK: `{mention_data['reason']}` <t:{mention_data['timestamp']}:R>",
                                    color=message.author.top_role.color,
                                ),
                                allowed_mentions=disnake.AllowedMentions(
                                    everyone=False, users=False, roles=False
                                ),
                            )
                    else:
                        break
                else:
``` hmm how do I fix this then
sullen shoal
velvet tinsel
#

Sh 🍝 code

shadow wraith
lament mesa
velvet tinsel
boreal ravine
velvet tinsel
#

Nvm

boreal ravine
sullen shoal
unkempt canyonBOT
#

getattr(object, name[, default])```
Return the value of the named attribute of *object*. *name* must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, `getattr(x, 'foobar')` is equivalent to `x.foobar`. If the named attribute does not exist, *default* is returned if provided, otherwise [`AttributeError`](https://docs.python.org/3/library/exceptions.html#AttributeError "AttributeError") is raised.

Note

Since [private name mangling](https://docs.python.org/3/reference/expressions.html#private-name-mangling) happens at compilation time, one must manually mangle a private attribute’s (attributes with two leading underscores) name in order to retrieve it with [`getattr()`](https://docs.python.org/3/library/functions.html#getattr "getattr").
velvet tinsel
#

Myxi is going god mode

lament mesa
lament mesa
#

It seems like a dict like object so it should have a get method

sullen shoal
#

if not, getattr should work

boreal ravine
#

dunno if find is the same has get

boreal ravine
sullen shoal
gaunt ice
#

guys i want to make a leaderboard command for my server for the economy commands , its basically the ppl who has the most coins, shud come at the top

slate swan
#
    @commands.command()
    @commands.guild_only()
    @commands.cooldown(1, 2, commands.BucketType.member)
    async def help(self, ctx,aliases=["h"]):
        author = ctx.author
        emoji = ":white_check_mark:"
        msg = ctx.message
        embed=discord.Embed(title="title", description="description", color=discord.Color.blurple())
        embed.set_author(name="Help", url="https://google.com")#, icon_url=self.bot.avatar_url)
        # embed.set_thumbnail(url=self.bot.avatar_url)
        embed.add_field(name="[Need more help?](https://google.com)", value="value", inline=False)
        embed.set_footer(text="footer")
        
        await author.send(embed=embed)
        await self.bot.add_reaction(msg, emoji)```
how could i add a reaction to the message?
lament mesa
upbeat otter
#

Guys, so the thing is I want to make the buttons keep working for 60 seconds and then they should stop working but how would I do this ,-,
current code:

res = await client.wait_for("button_click")

if res.user == ctx.message.author and ctx.message.channel == res.channel:
    if res.component.label == "General":
        await res.send(embed=genEmbed, components=buttons_for_help)

    elif res.component.label == "Moderation":
        await res.send(embed=modEmbed, components=buttons_for_help)
lament mesa
boreal ravine
boreal ravine
# sullen shoal it should, if its not overwritting the dunder method of it
Ignoring exception in on_message
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/disnake/client.py", line 505, in _run_event
    await coro(*args, **kwargs)
  File "/home/runner/bonbons-1/cogs/fun.py", line 73, in on_message
    reason = getattr(mention_data, "reason")
AttributeError: 'dict' object has no attribute 'reason'
Ignoring exception in on_message
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/disnake/client.py", line 505, in _run_event
    await coro(*args, **kwargs)
  File "/home/runner/bonbons-1/cogs/fun.py", line 73, in on_message
    reason = getattr(mention_data, "reason")
AttributeError: 'dict' object has no attribute 'reason'
sullen shoal
#

its a dict

sullen shoal
#

use get

boreal ravine
#

hm ok

lament mesa
upbeat otter
upbeat otter
boreal ravine
# sullen shoal use get
Ignoring exception in on_message
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/disnake/client.py", line 505, in _run_event
    await coro(*args, **kwargs)
  File "/home/runner/bonbons-1/cogs/fun.py", line 87, in on_message
    description=f"{member.mention} is AFK: `{mention_data['reason']}` <t:{mention_data['timestamp']}:R>",
KeyError: 'reason'
``` same issue as earlier
boreal ravine
#

reason = mention_data.get('reason') <= used this

valid galleon
#

how can i get the attached image using ctx.message.attachments? im pretty sure it returns a list, so how can i make it so the image attached in the message is actually usable?

boreal ravine
sullen shoal
#

that doesnt exist

boreal ravine
#

OH WAIT

lament mesa
slate swan
#
    @commands.command()
    @commands.guild_only()
    @commands.cooldown(1, 2, commands.BucketType.member)
    async def help(self, ctx,aliases=["h"]):
        author = ctx.author
        emoji = ":white_check_mark:"
        msg = ctx.message
        embed=discord.Embed(title="title", description="description", color=discord.Color.blurple())
        embed.set_author(name="Help", url="https://google.com")#, icon_url=self.bot.avatar_url)
        # embed.set_thumbnail(url=self.bot.avatar_url)
        embed.add_field(name="[Need more help?](https://google.com)", value="value", inline=False)
        embed.set_footer(text="footer")
        
        await author.send(embed=embed)
        await self.bot.add_reaction(msg, emoji)```
how could i add a reaction to the message?
boreal ravine
#

oh fuck i made it the wrong way

boreal ravine
slate swan
sullen shoal
boreal ravine
#

sure ig

#

thanks @sullen shoal @lament mesa

lament mesa
lament mesa
#

!d discord.Message.add_reaction

unkempt canyonBOT
#

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

Add a reaction to the message.

The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").

You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
boreal ravine
#

my send func already has too many kwargs

sullen shoal
boreal ravine
#

hm

sullen shoal
#

mention_timestamp = mention_data["timestamp"]

boreal ravine
#

ah ok sure ig

idle sparrow
#

what am i looking at here

#

XD

boreal ravine
#

code

sullen shoal
#

also yes, it will look simpler if you do smth like,

mention_timestamp = mention_data["timestamp"]
embed = discord.Embed()
embed.description = ...
channel.send(embed=embed)```
idle sparrow
#
await message.channel.send(
  embed=disnake.Embed(
    description=f"{member.mention} is AFK. Since <t:{mention_data['timestamp']}:R>"
  ),
  allowed_mentions=disnake.AllowedMentions(
    everyone=False, users=False, roles=False
  ),
)