#discord-bots

1 messages Β· Page 256 of 1

lost dove
#

u can't

slate swan
#

are you sure ?

lost dove
#

ofc

slate swan
#

a friend did that πŸ’€

lost dove
#

then ask him

#

πŸ€¦β€β™‚

slate swan
#

he dont reply πŸ’€

lost dove
#

Just do in portal what's wrong

slate swan
naive briar
#

Why

lost dove
#

tf

slate swan
#

???
normal..

slate swan
#

The way your friend did it can lead to their Discord account getting banned and terminated by Discord

#

Sounds amazing right CatJAM

slate swan
#

alr thanks guys πŸ™

shrewd apex
#

doing that would be self botting πŸ—Ώ

proper thicket
#

Hello I have this script custom made help command script and it’s not working but it shows it loaded so here it is please take a look at it import discord
from discord.ext import commands

class HelpCommand(commands.Cog):
def init(self, client):
self.client = client

@commands.Cog.listener()
async def on_Ready(self):
 print("HelpCommand.py is online.")

@commands.command()
async def help(self, ctx):
  help_embed = discord.Embed(title="Help Desk for Hervy", description="All commands for the bot.", color=discord.Color.random())

  help_embed.set_author(name="Hervy")
  help_embed.set_field(name="Ping", value="Check its ms..",Inline=False)
  help_embed.set_field(name="Kick", value="Kicks user from guild/server.",Inline=False)
  help_embed.set_field(name="Ban", value="Bans user from guild/server.",Inline=False)
  help_embed.set_field(name="Purge", value="Deletes a specified amount of messags.",Inline=False)
  help_embed.set_field(name="Unban", value="Unbans user from guild/server.",Inline=False)
  help_embed.set_field(name="Mute", value="Person cannot talk untill he gets unmuted.",Inline=False)
  help_embed.set_field(name="Unmute", value="Person may talk after hes been unmuted.",Inline=False)
  help_embed.set_field(name="Need help", value="A Moderator/Admin wille right with you.",Inline=False)
  help_embed.set_footer(text=f"Requested by <@{ctx.author}>.*, icon_url=ctx.author.avatar")

  await ctx.send(embed=help_embed)

async def setup(client):
await client.add_cog(HelpCommand(client))

naive briar
#

!code

unkempt canyonBOT
#
Formatting code on discord

Here's how to format Python code on Discord:

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

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

For long code samples, you can use our pastebin.

proper thicket
slate swan
#
    @discord.ui.select( 
        placeholder = "Choose a Role!",
        min_values = 1, # the minimum number of values that must be selected by the users
        max_values = None, # the maximum number of values that can be selected by the users
        options =[
            for role in self_roles.find():
                discord.SelectOption(
                    # name of array is the name of the role
                    label = role["name"],
                    description = role["description"]
                )
        ]

can i use for loop in a list

slate swan
#

!listcomp

unkempt canyonBOT
#
List comprehensions

Do you ever find yourself writing something like this?

>>> squares = []
>>> for n in range(5):
...    squares.append(n ** 2)
[0, 1, 4, 9, 16]

Using list comprehensions can make this both shorter and more readable. As a list comprehension, the same code would look like this:

>>> [n ** 2 for n in range(5)]
[0, 1, 4, 9, 16]

List comprehensions also get an if clause:

>>> [n ** 2 for n in range(5) if n % 2 == 0]
[0, 4, 16]

For more info, see this pythonforbeginners.com post.

proper thicket
fringe lake
#
async def main():
    async with bot:
        for file in [f"./cogs.{filename[:-3]}" for filename in os.listdir('./cogs') if filename.endswith(".py")]:
            await bot.load_extension(file)
        
asyncio.run(main())
north kiln
#

show your cogs folder

fringe lake
#

folder ?

slate swan
#

its cogs.Mod not ./cogs.Mod

fringe lake
north kiln
#

yes

#

cogs.Mod

fringe lake
#

oh i though when you do ./ you are refering to the current directory you are in

#

which is development

slate swan
#

no cause its not even path

shrewd apex
#

./ indicates cwd

fringe lake
slate swan
north kiln
#

the load_extension does not take a path

shrewd apex
#

oh yeah mb

north kiln
#

just do what is said

slate swan
#

!d discord.ext.commands.Bot.load_extension

unkempt canyonBOT
#

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

Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.

Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.11)").
fringe lake
slate swan
# fringe lake what does it take

just read the docs name (str) – The extension name to load. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test if you want to import foo/test.py.

fringe lake
#

thank you guys for the help

slate swan
#

show setup function in your cog file

fringe lake
#

oh god

proper thicket
#

Help please

slate swan
slate swan
#

looks like you enabled scope that needs redirect url

#

if you dont know what it is for you prolly dont want that scope

void whale
#

i got it

slate swan
#

cool but why delete message?

void whale
#

thanks for the help

void whale
formal basin
#
    xauthor_id = message.author.id
    curr_time = datetime.datetime.now().timestamp() * 1000
   if not author_msg_times.get(author_id, False):
        author_msg_times[author_id] = []
   author_msg_times[author_id].append(curr_time)
   expr_time = curr_time - time_window_millisecond
   expired_msgs = [
        msg_time for msg_time in author_msg_times[author_id]
        if msg_time < expr_time
    ]
   for msg_time in expired_msgs:
        author_msg_times[author_id].remove(msg_time)
    

   if len(author_msg_times[author_id]) > max_msg_per_window:
    try:
      minutes = r.get(f"1 {str(message.guild.id)}")
      min = int(minutes.decode("utf-8"))
      if f'1 {message.guild.id}' not in r:
            pass
            
      duration = datetime.timedelta(minutes=min)
      embed = discord.Embed(title="User muted", description=f" {message.author.mention} has been muted", color=discord.Color.blue())
      embed.add_field(name = "Reason",value = "spamming")
      embed.add_field(name = "Mute duration",value = f"{min} minutes")
      await message.author.timeout(duration)
      await asyncio.sleep(2.5)
      await message.channel.send(f"{message.author.mention} your not allowed to spam")
      log = r.get(f"log {str(message.guild.id)}")
      log2 = int(log.decode("utf-8"))
      logging = client.get_channel(log2) or await client.fetch_channel(log2)
      await logging.send(embed=embed)
         
    except KeyError:
      pass

  
         ``` why is my bot sending the message twice i used acyncio sleep to try and only make it one
tidal folio
#

When I put random, I mean random once
It doesn't change why?

slate swan
#
async def rps(interaction: discord.Interaction):
    """
    rock paper scissors
    """
    with open(rock_paper_scissors, 'r', encoding='UTF-8') as file:
        rand_choices3 = random.choice(file.read().splitlines())
        rock, paper = scissors.split(':')
        output = "Done"```
Anyone know how i can add a cooldown to slash commands
slate swan
#

no idea

tidal folio
tidal folio
slate swan
unkempt canyonBOT
#

@discord.app_commands.checks.cooldown(rate, per, *, key=...)```
A decorator that adds a cooldown to a command.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and return a value that is used as a key to the internal cooldown mapping.

The `key` function can optionally be a coroutine.

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandOnCooldown "discord.app_commands.CommandOnCooldown") is raised to the error handlers.

Examples

Setting a one per 5 seconds per member cooldown on a command:
tidal folio
slate swan
tidal folio
#

Look

slate swan
#

provide some code and brief explaination of the problem

#

Doesn't know what that means

tidal folio
#

When I use the same command it should change the numbers but it doesn't

slate swan
#

And then it's some random lines in the code sunglasscat

slate swan
#

But before that, let's send the same screenshot multiple times gigachad

tidal folio
slate swan
#

why to use random module from numpy?

tidal folio
slate swan
#

well i dont know how the seeds in numpy module work

#

you want a list with 9 random numbers?

tidal folio
slate swan
#

14, from 0 to 9

#

ah i see you want a list of random 14 numbers from range 0-9

#

The seeder is fine

#

If they do it as a global variable, it will be set once and that's it

#

!e ```py
import random

print(random.sample(range(9), 14))

unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 3, in <module>
003 |     print(random.sample(range(9), 14))
004 |           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
005 |   File "/usr/local/lib/python3.11/random.py", line 456, in sample
006 |     raise ValueError("Sample larger than population or is negative")
007 | ValueError: Sample larger than population or is negative
slate swan
#

it cannot repeat in sample?

#

So they'll have to move that thing that gets the randint within the command, otherwise it'll stay the same forever

slate swan
# tidal folio

there is something like docs so you dont put random arguments inside

slate swan
formal basin
#

is repeating twice

slate swan
#

!e ```py
import random
print(random.choices(range(10), k=14))

unkempt canyonBOT
#

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

[8, 5, 5, 2, 6, 4, 8, 2, 4, 2, 4, 2, 0, 8]
slate swan
#

here you go

tidal folio
#

Remove ,

slate swan
#

The double ping, pog useful

slate swan
slate swan
#

!e ```py
x = [0, 2, 5, 6]

print(f'[{" ".join(str(number) for number in x)}]')

unkempt canyonBOT
#

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

[0 2 5 6]
slate swan
#

what did not fix

#

its still the same numbers each command run?

tidal folio
#

Didn't work

slate swan
#

show code

tidal folio
slate swan
#
  • not as screenshot
  • code of the command not just 2 lines out of nowhere
tidal folio
slate swan
#

and where is the random number generation part in your command?

tidal folio
slate swan
tidal folio
slate swan
#

Someone doesn't understand variable declarations

#

and where did you define k

#

if you define it outside of the command obviously it will be the same value all the time

tidal folio
slate swan
#

if you define it inside command it will be new each command run

#

thats basics of programming

tidal folio
slate swan
slate swan
tidal folio
#

But i can

#

What can I do with it now?

slate swan
#

yeah you can but then dont complain you are new

slate swan
#

read my messages above

tidal folio
slate swan
#

let me demonstrate

#

see its always the same each function run

#

but if i put it inside

#

!e ```py
import random

def func():
random_number = random.randint(1, 9)
print(random_number)

func()
func()
func()
func()

unkempt canyonBOT
#

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

001 | 8
002 | 6
003 | 4
004 | 7
slate swan
#

!e ```py
import random
random_number = random.randint(1, 9)
def func():

print(random_number)

func()
func()
func()
func()

unkempt canyonBOT
#

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

001 | 9
002 | 9
003 | 9
004 | 9
slate swan
#

see the difference?

tidal folio
#

Look i can this

X = [1,2,3,4,5,6,7,8,9,]

K = random.randint(x,range=14)
velvet sierra
#

thats normal?

slate swan
slate swan
velvet sierra
#

i tried to google it but could not find much about

slate swan
tidal folio
slate swan
# tidal folio Yes but range?

it does not matter if its range or one number or 300 numbers its the fact and how it works when its inside function and when its outside

velvet sierra
slate swan
#

for example you have an infinite for loop sending some message will cause this

tidal folio
slate swan
tidal folio
#

Look

#

Range 14

slate swan
#

what does Range 14 mean

tidal folio
#

Like this

slate swan
#

what like this

#

what do you want

tidal folio
#

πŸ’€πŸ’€πŸ’€πŸ’€

tidal folio
slate swan
#

it generates a list with 14 random numbers from range 0-9

tidal folio
slate swan
#

you literally have the code that does it

tidal folio
#

But the circus doesn't change the numbers@slate swan

slate swan
tidal folio
#

Nothing

slate swan
#

i literally explained why it doesnt work above

#

do you even read my messages

tidal folio
slate swan
#

move the generation part to the command

#

and if you dont get it

#

learn python basics better

tidal folio
slate swan
#

yes you generate the numbers dont you

tidal folio
tidal folio
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
#

whats so hard to understand

#

do you use env varriables

#

then youdont

#

so why do you

tidal folio
#

πŸ’€βš°οΈβš°οΈβš°οΈβš°οΈβš°οΈ

#

HELP ME SEND VIDEO

slate swan
#

well gpt wont help you with discord bot since it has informations from 2021 and discord bot libraries changes a lot from it

slate swan
# tidal folio Didn't work

i have no idea how to explain it to you i told you 3 times what to to and even presented an example why your current solution doesnt work

#

depends what you are trying to make

#

discord bot cant join itself someone has to invite him

tidal folio
slate swan
#

thats not a discord bot thats discord app then and its 10x more complicated than a discord bot

slate swan
#

and where did you find that Join server for you? is it in the scopes when creating oauth2 url

slate swan
#

yeah, no idea what that is

#

yeah so you are talking about gdm.join scope which lets the app join guilds for you but this is a discord app as i said before it is so complicated that i for sure wont code it for you and since you dont understand python all my steps how to make it would make no sense for you

so either learn python or find another way arround

tidal folio
#

@slate swan Where?

slate swan
tidal folio
slate swan
tidal folio
slate swan
#

i wont just give you step by step guide i can give you examples and explaination how to solve your problem not solve it for you

#

and i belive i already gave you too many hints

tidal folio
#

It was very strange at first when I made it
It was no problem, then it happened on its own

slate swan
slate swan
#

Bro you tryna use 0Auth

pallid meadow
#

that's crazy

clear lark
#

Wanting to make a command that requires two people to fully run

So userOne would do .command userTwo how would I make it so the bot wait for 30 seconds, and if during that time userTwo does .keyword then the rest of .command will run?

pallid meadow
#

you would also have a sleep for 30 seconds then after that sleep you would wanna remove it from said datatype

#

that's against tos

#

under account automation

#

dankmemer most likely ignored messages from other bots

#

and iirc dankmemer doesn't even use messaged based commands anymore it's all interaction based

swift acorn
#

Is it possible to do something if a user doesn't submit a modal and cancels it?

sick birch
#

There is an on_timeout, though

flat saffron
#

yes and its very usfull

fiery trout
hushed galleon
unkempt canyonBOT
#

@discord.app_commands.guilds(*guild_ids)```
Associates the given guilds with the command.

When the command instance is added to a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree"), the guilds that are specified by this decorator become the default guilds that it’s added to rather than being a global command.

Note

Due to an implementation quirk and Python limitation, if this is used in conjunction with the [`CommandTree.command()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.command "discord.app_commands.CommandTree.command") or [`CommandTree.context_menu()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.context_menu "discord.app_commands.CommandTree.context_menu") decorator then this must go below that decorator.

Example...
hushed galleon
#

there's also a guild=/guilds= parameter for command(), but either way afterwards you'll need to make a call to tree.sync() with the guild that you're syncing to, for example: py guild = discord.Object(1234) await bot.tree.sync(guild=guild)

fiery trout
#

with my code like this, click counts doesn't sync at all, I'm assuming this is becuase I need to still do something with on ready

hushed galleon
#

basically syncing global commands and guild commands are separate API calls, so discord.py requires you to make each of those API calls individually

#

one for global commands: py await bot.tree.sync() and another for your guild's commands: py await bot.tree.sync(guild=discord.Object(267624335836053506))

fiery trout
#

omg, thank you so much!!!

#

I've literally been cracking my head over this for hours

#

ur a legend!

molten skiff
#

hi

#

how to fix this , i want to add options after getting the choices from request depending on the user's id
error:

line 40, in <module>
    @app_commands.choices(keys = get_keys(discord.Interaction.user.id))
                                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'member_descriptor' object has no attribute 'id'
def get_keys(user_id):
    url = f"https://example.com/api.php?action=1&discord_id={user_id}"
    headers = CaseInsensitiveDict()
    resp = requests.get(url, headers=headers)
    data = json.loads(resp.text)
    keys = []
    for item in data:
        choice = Choice(name=f"{item['key']}", value=f"{item['Subscription']}")
        keys.append(choice)
    return keys


@app_commands.choices(keys = get_keys(discord.Interaction.user.id))

@client.tree.command(description='check your key')
async def key_check(interaction: discord.Interaction , keys: str):
    user_id = interaction.user.id
    await interaction.response.send_message(' Subscription: ' + keys)


molten skiff
# slate swan choices are static, what you need is to use an autocomplete menu instead of choi...

how to get the discord id before fruits = ['Banana', 'Pineapple', 'Apple', 'Watermelon', 'Melon', 'Cherry'] ot not possible ?

@fruits.autocomplete('fruit')
async def fruits_autocomplete(
    interaction: discord.Interaction,
    current: str,
) -> list[app_commands.Choice[str]]:
    fruits = ['Banana', 'Pineapple', 'Apple', 'Watermelon', 'Melon', 'Cherry']
    return [
        app_commands.Choice(name=fruit, value=fruit)
        for fruit in fruits if current.lower() in fruit.lower()
    ]
naive briar
#

ID of what

molten skiff
#

user

naive briar
#

Just interaction.user.id?

slate swan
unkempt canyonBOT
drifting arrow
#

how do I drop down menu like this?

unkempt canyonBOT
#

examples/app_commands/transformers.py lines 80 to 89

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

# On Discord, this will show up as two choices, Buy and Sell.
# In the code, you will receive either 'Buy' or 'Sell' as a string.
@client.tree.command()
@app_commands.describe(action='The action to do in the shop', item='The target item')
async def shop(interaction: discord.Interaction, action: Literal['Buy', 'Sell'], item: str):
    """Interact with the shop"""
    await interaction.response.send_message(f'Action: {action}\nItem: {item}')```
lethal drift
#

Anyone know how to fix this error?

discord.app_commands.errors.CommandSyncFailure: Failed to upload commands to Discord (HTTP status 400, error code 50035)
#

when using bot.tree.sync()

vocal snow
#

can you show the full traceback?

#

It might have some clue to what actually caused the bad request

lethal drift
#

It was in an on_ready to begin with, after the first error, I created a different function and put an asyncio.create_task() in on_ready and it gave the same error

vocal snow
#

the issue looks like you have an empty description

#

can you show your commands?

lethal drift
#

I left the description variable I made as " " and forgot to fill it

#

Thx!!

cloud dawn
formal basin
#

in the channel.send?

cloud dawn
#

Idk where you loop and where/how you want to stop it.

formal basin
slate swan
#

So after channel send break

formal basin
#

like that?

#

but i get error

cloud dawn
#

Under the code not in the code.

formal basin
#

ok

formal basin
cloud dawn
formal basin
cloud dawn
#

Then you aren't inside a loop, so what are you experiencing? Does the bot reply to it's own spam message?

tidal folio
#

When I use the same command
It must change the position of the numbers but it does not

formal basin
tidal folio
tidal folio
cloud dawn
cloud dawn
#

The bot?

formal basin
formal basin
cloud dawn
#

Is your bot running twice?

formal basin
cloud dawn
#

So the bot says the message twice towards a user.

formal basin
formal basin
tidal folio
#

You have to come to the server and I'll get you there

#

Here you can???

formal basin
tidal folio
#

Why didn't work?

cloud dawn
#

!d random.randint

unkempt canyonBOT
#

random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
cloud dawn
#

You need a range

#

random.randint(0, 14)

formal basin
tidal folio
#

Look

#

That doesn't change it

#

@formal basin

formal basin
slate swan
#

Day 3 of telling this SIGMA/ZAMWA guy to put the goddamn random IN THE COMMAND FUNCTION

tidal folio
slate swan
#

IN THE COMMAND FUNCTION

tidal folio
#

Wich line?

slate swan
#
@bot.slash_command()
async def finder(ctx):
    k = ........
shrewd apex
slate swan
#

My guy, it's the third day in a row we're telling you that

#

Holy smokes

shrewd apex
#

gg

tidal folio
#

Look error

shrewd apex
#

look at the indents

#

also outer parantheses are not needed

slate swan
#

Yeah they're just pasting so that's why the wrong indentation

shrewd apex
#

πŸ˜”

tidal folio
tidal folio
#

He work but look

formal basin
#
   author_id = message.author.id
   curr_time = datetime.datetime.now().timestamp() * 1000
   if not author_msg_times.get(author_id, False):
        author_msg_times[author_id] = []
   author_msg_times[author_id].append(curr_time)
   expr_time = curr_time - time_window_milliseconds
   expired_msgs = [
        msg_time for msg_time in author_msg_times[author_id]
        if msg_time < expr_time
    ]
   for msg_time in expired_msgs:
        author_msg_times[author_id].remove(msg_time)
    
   if len(author_msg_times[author_id]) > max_msg_per_window:
    try:
      minutes = r.get(f"1 {str(message.guild.id)}")
      min = int(minutes.decode("utf-8"))
      if f'1 {message.guild.id}' not in r:
            pass
            
      duration = datetime.timedelta(minutes=min)
      embed = discord.Embed(title="User muted", description=f" {message.author.mention} has been muted", color=discord.Color.blue())
      embed.add_field(name = "Reason",value = "spamming")
      embed.add_field(name = "Mute duration",value = f"{min} minutes")
      await message.author.timeout(duration)
      await message.channel.send(f"{message.author.mention} your not allowed to spam")
      log = r.get(f"log {str(message.guild.id)}")
      log2 = int(log.decode("utf-8"))
      logging = client.get_channel(log2) or await client.fetch_channel(log2)
      await logging.send(embed=embed)
     
    except KeyError:
      pass

  
      
```the bot is spamming
formal basin
tidal folio
#

Look he created a new embed why

#

@formal basin

formal basin
tidal folio
tidal folio
formal basin
tidal folio
#

No

formal basin
tidal folio
formal basin
tidal folio
formal basin
slate swan
formal basin
slate swan
#

what event

formal basin
#

on_message

slate swan
#

yeah its triggered on each message so if you send a message it will self trigger

formal basin
#

but now it sends it twice

slate swan
formal basin
slate swan
#

no idea try printing the message content and you will maybe get it

slate swan
#

title='' is causing an error I think

#

has to either be None or a non-empty string if I remember correct

#

does it send any message?

#

Nevermind i'm wrong.

#

author.ping doesn't exist

#

You want author.mention probably

#

and no errors in the console?

#

!d discord.Member.mention

unkempt canyonBOT
slate swan
#

!d discord.Member.ban

unkempt canyonBOT
#

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

Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.ban "discord.Guild.ban").
slate swan
#

!d discord.Embed

unkempt canyonBOT
#

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

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

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

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
slate swan
#

well then no idea you should have error in console if something happens

#

show code and traceback as text

tidal folio
slate swan
tidal folio
slate swan
#

!d discord.app_commands.check

unkempt canyonBOT
#

@discord.app_commands.check(predicate)```
A decorator that adds a check to an application command.

These checks should be predicates that take in a single parameter taking a [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure") exception is raised and sent to the appropriate error handlers.

These checks can be either a coroutine or not.

Examples

Creating a basic check to see if the command invoker is you...
slate swan
#

random words dont just work

#

if you want to change the bot presence

tidal folio
slate swan
#

!d discord.ext.commands.Bot.change_presence

unkempt canyonBOT
#

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

Changes the client’s presence.

Example

```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
```   Changed in version 2.0: Removed the `afk` keyword-only parameter...
slate swan
tidal folio
#

No this

slate swan
tidal folio
#

Look random why create embed

#

When i use finder command he create new embed

slate swan
#

yeah so read docs on how to set presence which i linked above

#

!d discord.ext.commands.Bot.guilds

unkempt canyonBOT
slate swan
#

here is how to get all guilds the bot is in

tidal folio
tidal folio
slate swan
tidal folio
tidal folio
naive briar
#

There are no questions there

slate swan
#

yeah i dont see any question still

tidal folio
#

Look random why create embed
When i use finder command he create new embed
@slate swan

slate swan
#

ok cool and what about it

tidal folio
#

Why is this happening?

#

Come on, use a server bot, you understand

naive briar
#

What?

slate swan
#

why are the numbers random now? no idea you show some random code lines that dont even show how you generate it

slate swan
tidal folio
#

I can send you a link here?

naive briar
#

Of what

tidal folio
#

I can't

tidal folio
naive briar
#

My DMs are disabled

tidal folio
#

πŸ’€πŸ’€πŸ’€

tidal folio
#

Check

#

When i use the command he creates a new embed why?

slate swan
tidal folio
#

Can you check dm and use bot

#

You understand

slate swan
thin raft
#

this guy has been with the same issue for a week

formal basin
naive briar
#

What?

tidal folio
thin raft
#

man you should really learn python first

slate swan
tidal folio
naive briar
slate swan
#

please learn the basics of python before you start a discord bot how many times i need to repeat it

thin raft
#

you've been with the same error for a week

#

and couldn't send your code once

tidal folio
naive briar
slate swan
naive briar
thin raft
#

is like complaining your print statement printed something

naive briar
thin raft
#

you send an embed and complain it gets sent

tidal folio
naive briar
#

How come

thin raft
thin raft
#

don't name your variable logging

#

it will confuse anyone who reads it

formal basin
formal basin
thin raft
#

call it logging_channel for example

naive briar
#

They'd assume it's logging module

formal basin
#

oh

naive briar
#

At least I did

thin raft
#

x2

formal basin
#

ok

thin raft
#

can you send it through !paste

formal basin
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

thin raft
#

!d discord

unkempt canyonBOT
#

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

Creating a Bot account is a pretty straightforward process.

thin raft
#

1 sec

naive briar
#

!d discord.Client.change_presence

unkempt canyonBOT
#

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

Changes the client’s presence.

Example

```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
```   Changed in version 2.0: Removed the `afk` keyword-only parameter...
slate swan
#

yes already told you

thin raft
#

yep that

slate swan
thin raft
#

ok now, what are you trying to do and what does it do

#

there's an example tho

slate swan
#

you got the same link now

#

and here are examples

thin raft
slate swan
#

i told you how to get bot guilds count

#

what you dont understand

formal basin
#

await client.change_presence(activity=discord.Activity(type = discord.ActivityType.watching, name=f'{len(client.guilds)} servers')

slate swan
naive briar
#

Me when spoonfeeding

formal basin
naive briar
#

Just that won't explain it

#

Where is that code being executed

formal basin
thin raft
#

it is sending it twice

formal basin
thin raft
#

because you are sending it twice

formal basin
thin raft
#

you literally have 2 .sends

formal basin
slate swan
tidal folio
slate swan
thin raft
#

smh

formal basin
slate swan
formal basin
slate swan
#

so what was the other message who triggered it

formal basin
formal basin
#

then sent it

slate swan
#

doesnt look like he was muted if he sent them essage

thin raft
formal basin
thin raft
#

you said it should be sent to different channels right

thin raft
#

wait

#

you're executing the command on the logs channel?

formal basin
thin raft
#

send ss

#

I am not understanding

naive briar
#

Who does

#

I've been watching and don't understand one bit

slate swan
#

me too

formal basin
#

and the logging_channel

thin raft
#

you have 2 python instances

#

kill all python processes

slate swan
#

possibly your spam detection is wrong and the messages are being sent after for example second and third message
Shrugdge

formal basin
slate swan
#

easiest one:
reboot pc

formal basin
thin raft
#

open task manager > right click python > kill

formal basin
slate swan
#

yeah just restart pc

formal basin
#

ok

naive briar
#

!d discord.Activity

unkempt canyonBOT
#

class discord.Activity(**kwargs)```
Represents an activity in Discord.

This could be an activity such as streaming, playing, listening or watching.

For memory optimisation purposes, some activities are offered in slimmed down versions:

β€’ [`Game`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Game "discord.Game")

β€’ [`Streaming`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Streaming "discord.Streaming")
naive briar
#

It's keyword-only

formal basin
naive briar
#

Do you two on_message events and or listeners

formal basin
naive briar
#

That didn't answer the question

formal basin
#

only one

formal basin
#

wdym

thin raft
#

how many on_message listenres do you have

formal basin
thin raft
#

!d discord.Activity

unkempt canyonBOT
#

class discord.Activity(**kwargs)```
Represents an activity in Discord.

This could be an activity such as streaming, playing, listening or watching.

For memory optimisation purposes, some activities are offered in slimmed down versions:

β€’ [`Game`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Game "discord.Game")

β€’ [`Streaming`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Streaming "discord.Streaming")
slate swan
#

didnt you get answer already

#

its key-word only

formal basin
thin raft
#

send them

naive briar
#

You just said one

formal basin
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

thin raft
#

with capital b

slate swan
#

!d discord.Button

unkempt canyonBOT
#

class discord.Button```
Represents a button from the Discord Bot UI Kit.

This inherits from [`Component`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Component "discord.Component").

Note

The user constructible and usable type to create a button is [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") not this one.

New in version 2.0.
slate swan
#

thx

thin raft
#

np

swift siren
#

where the channel to get help w vps’s

slate swan
#

It's a thread in this channel

swift siren
#

thank you

slate swan
#
def process_roles():
    roles = []
    
    for role in self_roles.find():
        discord.SelectOption(

            label = role["name"],
            description = role["description"]
        )
        
    return roles

#select menus
class select_roles(discord.ui.View):

    @discord.ui.select( 
        placeholder = "Choose a Role!",
        min_values = 1,
        max_values = None, 
        options = process_roles()
    )

TypeError: The command passed must be a subclass of Command

#

show full code and full traceback

slate swan
slate swan
# slate swan show full code and full traceback
def process_roles():
    roles = []
    
    for role in self_roles.find():
        discord.SelectOption(
            # name of array is the name of the role
            label = role["name"],
            description = role["description"]
        )
        
    return roles

# make select menus
class select_roles(discord.ui.View):

    @discord.ui.select( 
        placeholder = "Choose a Role!",
        min_values = 1, # the minimum number of values that must be selected by the users
        max_values = None, # the maximum number of values that can be selected by the users
        options = process_roles()
    )
    async def select_callback(self, select, interaction):


        role = discord.utils.get(interaction.guild.roles, name=select.values[0])
        await interaction.user.add_roles(role)
        await interaction.response.send_message(f"Added {role.mention} to you!" , ephemeral=True)

Traceback (most recent call last):
  File "c:\Users\DELL PC\Desktop\On going projects\project\arcadefunhouseindia\main.py", line 6, in <module>
    from lottery_bot import bot as lottery_bot_app
  File "c:\Users\DELL PC\Desktop\On going projects\project\arcadefunhouseindia\lottery_bot\bot.py", line 71, in <module>
    bot.add_command(self_roles.self_roles)
  File "C:\Users\DELL PC\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\bot.py", line 246, in add_command
    super().add_command(command)
  File "C:\Users\DELL PC\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\core.py", line 1342, in add_command
    raise TypeError('The command passed must be a subclass of Command')
TypeError: The command passed must be a subclass of Command
#

I want that roles label and description should come from my database

slate swan
#

in callback function

#

ohh

slate swan
#

why do you need to call this method

slate swan
slate swan
#

so then

#

are you talking about .add_roles?

slate swan
#

so you do run this method

#

what is self_roles.self_roles

#

ohh yeah this is because i want to keep all commands files seperate

#

so why dont you use cogs?

#

thats what they are for

slate swan
#

yeah but you should not call this method directly use cogs instead

slate swan
#

cause you will get into such problems

#

ok let me update my code

#

@slate swan is it ok if my command files are in different folders
like

./admin
  admin_commands.py
./community
  community_commands.py
bot.py
#

preferably create one folder like cogs or extensions and put all files there

slate swan
#

so that i will get to know which command belongs to which category

#

sure but it will be harder to load them

turbid condor
#

Wouldn't subclassing help with that?

slate swan
#

subclassing what

turbid condor
#

The cogs

slate swan
#

you always need to subclass from Cog

turbid condor
#

Nah i mean he can keep the commands in multiple folders as he wants and then creates a cog that inherits from other cogs and load that

slate swan
#

no thats not how it works

turbid condor
#
class cog1(commands.Cog):
#rest of the code....

And then ```py
from cogs.Cog1 import cog1

class cog2(cog1):

rest of the code ...```

Something like this?

slate swan
#

Naming conventions bravemmlol

slate swan
#

cogs are to separate commands not merge them all

twilit grotto
#

yeah i dont see why you'd want to do that

turbid condor
#

Welp i did that like in my case the code wasn't getting pretty big and messy so i did this

vocal snow
#

I can see why you'd want to do it if you wanted to have some common functionality for each cog.
Or perhaps use the subclass hook for loading them.
Not sure how much that would actually benefit you though

slate swan
#
class BaseCog(commands.Cog):
    hidden: bool

    def __init__(self, bot: PokeLore) -> None:
        self.bot = bot

    def __init_subclass__(cls, hidden: bool = False) -> None:
        cls.hidden = hidden
``` there is something like this in PokeLore which is understable but i dont see why need to use this in this case
formal basin
#

how can i make it so it sends how long the bot has been up for

slate swan
vocal snow
#

!d datetime.datetime.now

unkempt canyonBOT
#

classmethod datetime.now(tz=None)```
Return the current local date and time.

If optional argument *tz* is `None` or not specified, this is like [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today"), but, if possible, supplies more precision than can be gotten from going through a [`time.time()`](https://docs.python.org/3/library/time.html#time.time "time.time") timestamp (for example, this may be possible on platforms supplying the C `gettimeofday()` function).

If *tz* is not `None`, it must be an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass, and the current date and time are converted to *tz*’s time zone.

This function is preferred over [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today") and [`utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "datetime.datetime.utcnow").
formal basin
#

then how can i count up

#

from that date

vocal snow
#

I would recommend going over the datetime library and familiarizing yourself with it, because it can be incredibly useful

slate swan
#

!d datetime.timedelta

unkempt canyonBOT
#

class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.

Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
vocal snow
#

you don't "count up", you simply subtract two datetime objects to get a timedelta object of the time lapsed

slate swan
#

wait thats not it

#

you can just subtract them i belive

#

!e ```py
import datetime
d1 = datetime.datetime(2023, 6, 20)
d2 = datetime.datetime.now()

print(d2-d1)

unkempt canyonBOT
#

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

4 days, 13:52:21.508629
slate swan
#

yep 20.06.2023 was 4 days ago etc...

runic loom
#

How to start coding

slate swan
#

imagine something you want to do and start doing it

#

you want to create a website for example -> start learning html from some websites / yt videos

naive briar
#

YouTube videos, huh, sounds about right

slate swan
#

if you want to learn python there are resources here:

#

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

fringe lake
#

is using a bot as a class a good practice ?

slate swan
#
class Bot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.all()
        super().__init__(command_prefix=commands.when_mentioned_or('!'), intents=intents)
    
    async def load_cogs(self):
        self.load_extension("cogs.add_money")
bot = Bot()

    

def run_discord_bot():
    token = config.find_one()['token']
    bot.run(token)

is it right?

#

discord.ext.commands.errors.CommandNotFound: Command "add" is not found
i am getting this

#

cause you dont load any cogs so there are no commands

#

load_cogs method is never called

twilit grotto
#

that and you need to await self.load_extension

slate swan
# slate swan cause you dont load any cogs so there are no commands
class Bot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.all()
        super().__init__(command_prefix=commands.when_mentioned_or('!'), intents=intents)
         
      
    async def load_cogs(self):
       await self.load_extension("cogs.add_money")
    
    async def on_ready(self):

        print(f'{bot.user} has connected to Discord!')


bot = Bot()
bot.load_cogs(bot)

i get this
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

#

its async function as you can see

#

so it has to be awaited

twilit grotto
#

import asyncio library and use it to run your load_cogs function

slate swan
#

no just run it in on_ready

twilit grotto
#

oh that too mb

slate swan
#

asyncio.run wouldnt even work since there is already running an event loop

twilit grotto
#

yeah you're right im sped my bad

slate swan
#

the load_cogs has to be awaited

#

isnt that async too?

#

ahh how to do it now?

#

like you do always just put await before

slate swan
#

before calling load_cogs skull

#
    async def load_cogs(self):
        await self.load_extension("cogs.add_money")

i did this

slate swan
# slate swan before calling load_cogs <:skull:1059358976267010078>
class Bot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.all()
        super().__init__(command_prefix=commands.when_mentioned_or('!'), intents=intents)
      
      
    async def load_cogs(self):
        await self.load_extension("cogs.add_money")
    


    async def on_ready(self):

        print(f'{bot.user} has connected to Discord!')


bot = Bot()

await bot.load_cogs(bot)

wtf like this?

#
  1. it wont work yet
  2. why pass bot inside?
slate swan
#

thats good now just asking why you pass bot to the method

alpine oar
#

yo i need help so basically i made this code where my bot should send a godbye message to my godbye channel but it still sends it to the welcome channel and idk why

slate swan
#

bot.load_cogs()

twilit grotto
twilit grotto
alpine oar
#

how do i send it in quotes i forgot ☠️

twilit grotto
#

!codeblock

unkempt canyonBOT
#
Formatting code on discord

Here's how to format Python code on Discord:

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

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

For long code samples, you can use our pastebin.

alpine oar
#

thanks

#
async def on_member_remove(member):
    channel_id = 1115986595997294612  # Replace YOUR_CHANNEL_ID with the actual channel ID

    channel = bot.get_channel(channel_id)

    background = Editor("pic2.jpg")
    profile_image = await load_image_async(str(member.avatar.url))

    profile = Editor(profile_image).resize((150, 150)).circle_image()
    poppins = Font.poppins(size=50, variant="bold")
    poppins_small = Font.poppins(size=20, variant="light")

    background.paste(profile, (325, 90))
    background.ellipse((325, 90), 150, 150, outline="white", stroke_width=5)

    background.text((400, 260), f"Goodbye, {member.name}#{member.discriminator}!", color="white", font=poppins, align="center")
    background.text((400, 325), f"We'll miss you.", color="white", font=poppins_small, align="center")

    image_bytes = background.image_bytes
    file = File(fp=image_bytes, filename="pic1.jpg")

    await channel.send(f"Goodbye {member.name}#{member.discriminator}! We'll miss you. Hope to see you again soon.")
    await channel.send(file=file)
twilit grotto
#

make sure that channel_id is indeed the correct channel

alpine oar
#

idk whats wrong fr fr

twilit grotto
#

interesting. should be sending to that channel then, are you 1000% sure?

alpine oar
alpine oar
slate swan
#

this can be raised from many reasons

#

!d discord.Forbidden

unkempt canyonBOT
#

exception discord.Forbidden(response, message)```
Exception that’s raised for when status code 403 occurs.

Subclass of [`HTTPException`](https://discordpy.readthedocs.io/en/latest/api.html#discord.HTTPException "discord.HTTPException")
slate swan
#

Forbidden

#

.http 403

#

@slate swan

class Bot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.all()
        super().__init__(command_prefix=commands.when_mentioned_or('!'), intents=intents)      
      
      
    async def load_cogs(self):
        await self.load_extension("cogs.add_money")
        


    async def on_ready(self):

        print(f'{bot.user} has connected to Discord!')


bot = Bot()

# load cogs
bot.load_cogs()

what shall i do here?

slate swan
slate swan
#

then where is the async ?

slate swan
slate swan
#

yeah you need to put it in on_ready

slate swan
#
    async def on_ready(self):
        await self.load_cogs()
        print(f'{bot.user} has connected to Discord!')
#

ok?

slate swan
#

tias domain blocked :(

tidal folio
#

Someone can help

slate swan
#

yeah it literally tells you

#

that it cannot choose 14 different items from a list that contains 9 items

wise jewel
#

you probably want random.choices

wise jewel
slate swan
#

odd guy

shrewd apex
#

cntrl z

slate swan
tidal folio
slate swan
#

man we literally solved it a day ago

tidal folio
wise jewel
slate swan
tidal folio
wise jewel
full cosmos
#

Hello!
I'm sorry if this is stupid but I couldn't find a solution on google.
I'm trying to make a message with buttons that change a string variable based on which button is clicked.
"on_button_click" doesn't appear to reach the bot at all. Not even a simple "print" command happens when the buttons are pressed. I don't even get any error message in the console.
"on_interaction" does appear to work but it won't let me use "custom_id" to differentiate between the buttons. This one gives me an error message saying: "AttributeError: 'Interaction' object has no attribute 'custom_id'".

slate swan
#

example when banning?

tidal folio
slate swan
# tidal folio I remove all

so you got code with the same problem, we help you solve it for 2 days then you remove it and ask the same question again meaning that you dont understand what you are doing at all

#

no thanks im not into it again

#
Raises
NotFound – The requested user was not found.

Forbidden – You do not have the proper permissions to ban.

HTTPException – Banning failed.

TypeError – You specified both delete_message_days and delete_message_seconds.
tidal folio
tidal folio
wise jewel
slate swan
#

which one

#

Forbidden?

tidal folio
#

You ban him?πŸ’€πŸ’€πŸ’€

tidal folio
slate swan
#

not sure which error it raises then

tidal folio
#

Why didn't it change??
There is someone?

slate swan
#

Forbidden or HTTPException

tidal folio
slate swan
#

there is not a strict exception for this case for sure

#

that would be odd bot if you could ban yourself

tidal folio
slate swan
#

you dont understand basic things learn basic python first

tidal folio
slate swan
#

!e ```py
import random
random_number = random.randint(1, 10)
def func():
print(random_number)
func()
func()
func()
func()

unkempt canyonBOT
#

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

001 | 4
002 | 4
003 | 4
004 | 4
slate swan
#

when we generate outside function its the same each call ^

#

!e ```py
import random
def func():
random_number = random.randint(1, 10)
print(random_number)
func()
func()
func()
func()

unkempt canyonBOT
#

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

001 | 9
002 | 8
003 | 7
004 | 5
slate swan
#

when we generate inside function its generated again each function call

tidal folio
slate swan
#

oh damn

#

yeah please learn python

full cosmos
#

can someone please take a look at my question?

naive briar
#

Where even is your question

shrewd apex
full cosmos
#

aww. It seemed that was the only part that was working 😦

shrewd apex
#
view = discord.ui.View()
button = discord.ui.Button(label="Test")
async def callback(inter):
  await inter.response.send_message("Button pressed!")
button.callback = callback
await inter.response.send_message("HERE IS THE BUTTON!", view=view)
#

this is a simple example

#

more elaborate examples here ^^

full cosmos
#

Thank you I will take a look in a second

formal basin
#

how can i check if the user that used the button is not the user that used the command

#

and how do i disable a button

full cosmos
#

I think you can get that with ctx?

#

ctx.author gets you the user who used the command I think

shrewd apex
#

both interaction and ctx have author properties

full cosmos
#

I think they want to disable the button when it is not the same user

shrewd apex
#

compare it with the interaction recieved on button callback

naive briar
#

!d discord.ui.Button.disabled

unkempt canyonBOT
shrewd apex
#

u can just set button.disabled = True

#

and edit the view in the message

full cosmos
slate swan
shrewd apex
#

^^

full cosmos
#

thank you

shrewd apex
#

its a monkey patch alternative to subclassing

#

in examples they yse a decorator

#

which registers the button and assigns the decorated function as its callback

full cosmos
#

Sorry, english is not my first language. does monkey patch mean it's not the ideal solution but it works?

shrewd apex
#

its not the best solution but it works yeah

full cosmos
#

thank you

shrewd apex
#

99% of the time that is enough

slate swan
shrewd apex
#

also monkey patch is fine as long as its a small callback imo nothing to complex

formal basin
#

if interaction.user is not user: how do i check if the user of a button is not the user of the command. I thought this works

slate swan
#

check by id

full cosmos
#

wouldn't it be interaction.author and ctx.author?

formal basin
slate swan
formal basin
slate swan
#

lol

formal basin
#

!d discord.Memebr

unkempt canyonBOT
#
Nope.

No documentation found for the requested symbol.

#

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

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

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

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

hash(x) Returns the member’s hash.

str(x) Returns the member’s handle (e.g. `name` or `name#discriminator`).
formal basin
#

!d discord.Member

unkempt canyonBOT
#

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

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

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

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

hash(x) Returns the member’s hash.

str(x) Returns the member’s handle (e.g. `name` or `name#discriminator`).
slate swan
unkempt canyonBOT
#

property id```
Equivalent to [`User.id`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.id "discord.User.id")
full cosmos
shrewd apex
shrewd apex
#
for child in self.children:  # self if subclassed else view
  child.disabled = True
await inter.edit_original_response(view=view)  # imma assume u wanna edit the message and have responded before
slate swan
#

why i have ping here

shrewd apex
formal basin
#

cause i want it to

slate swan
formal basin
#

ok thanks

formal basin
#

i havent subclassed it so i put view

slate swan
#

and where did you put it

formal basin
#

after it has been pressed

shrewd apex
formal basin
shrewd apex
#

then edit

formal basin
#

i have to?

slate swan
#

nothing will change until you edit

formal basin
#

ohhhh

shrewd apex
# formal basin i have to?

did u think it was optional remember anything u want to reflect in discord needs to be awaited since all methods which interact with the api are async

formal basin
slate swan
#

its interaction

formal basin
#

ok

#

thx

full cosmos
#

how horribly wrong did I do this?

slate swan
#

if you use global varriables? very

shrewd apex
slate swan
#

Seeing the word global already makes it 10 times worse than it ever could be

full cosmos
#

πŸ˜…

shrewd apex
#

lemme give u an example

#

are u using prefix commands?

full cosmos
#

I used to define the buttons in the command where the view is called but then I can't access them in the callback so I just made them global... πŸ˜…

full cosmos
shrewd apex
#
@bot.command()
async def foo(ctx):
  view = View()
  names = ["a", "b", "c"]
  for name in names:
    button = Button(label=name)
    async def callback(inter):
      await inter.response.send_message(f"Switching to {name}!")
    button.callback = callback
    view.add_item(button)
  await ctx.send("Press one of these", view=view)
#

here copy paste this and use

#

should work hopefully

formal basin
full cosmos
slate swan
#

you only need it for this

shrewd apex
#

altho if ur using it in another command u can define the callback outside

full cosmos
#

Okay that makes a lot of sense

shrewd apex
#

dont send the new view

shrewd apex
full cosmos
shrewd apex
#

its called a f string it should work fine since name is defined in outer scope did u try it?

full cosmos
#

Outer scope?

slate swan
#

it gets the name from the for loop: for name in names:

full cosmos
#

so that defines and uses the variable at the same time?

shrewd apex
#

yeah

slate swan
#

thats just how the for loop works yeah

full cosmos
#

okay thank you!

formal basin
# shrewd apex i said edit the message with the view
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/ui/view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "/Users/zagzag/vscode/zagzag.py", line 122, in button_callback
    await interaction.edit_original_response(f"I picked {paper} and you picked rock so I win {interaction.user.mention}", view=view)
TypeError: edit_original_response() takes 1 positional argument but 2 positional arguments (and 1 keyword-only argument) were given```
slate swan
#

!e

unkempt canyonBOT
#
Missing required argument

code

#
Command Help

!eval [python_version] <code, ...>
Can also use: e

Run Python code and get the results.

This command supports multiple lines of code, including formatted code blocks. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.

The starting working directory /home, is a writeable temporary file system. Files created, excluding names with leading underscores, will be uploaded in the response.

If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside them.

By default, your code is run on Python 3.11. A python_version arg of 3.10 can also be specified.

We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!

slate swan
#

!e

import os
print(os.listdir())```
unkempt canyonBOT
#

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

['main.py']
slate swan
slate swan
unkempt canyonBOT
#

await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the original interaction response message.

This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.
slate swan
slate swan
formal basin
shrewd apex
slate swan
#

read the channel description

formal basin
slate swan
#

your text must be with keyword content

formal basin
#

content="message"

twin dragon
#

@slate swan

slate swan
#

yes

formal basin
#

like that

twin dragon
slate swan
twin dragon
#

can u help me solve this

shrewd apex
#

down is so popular πŸ‘€

slate swan
slate swan
twin dragon
slate swan
#

looks like there is no such thing like windll in this library

full cosmos
#

The only ctype I know of is C#

slate swan
winter token
#

@bot.command()
async def add(ctx,*args:int):
    s = 0
    for i in args:
      s = s+i
    await ctx.send(f"The required answer is: {s}")

@add.error
async def add_error(ctx, error):
   if isinstance(error, commands.MissingRequiredArguments):
     await ctx.send("Error: Please input atleast 2 numbers!")
   elif isinstance(error, commands.BadArgument):
     await ctx.send("Syntax Error\nCorrect Usage: $add num1 num2 and so on")

The bot is not sending error message

shrewd apex
slate swan
winter token
slate swan
#

show it then

formal basin
# slate swan yes
Traceback (most recent call last):
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/ui/view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "/Users/zagzag/vscode/zagzag.py", line 198, in button_callback3
    await interaction.edit_original_response(content=f"I picked {paper} and you picked scissors so you win {interaction.user.mention}", view=view)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/interactions.py", line 485, in edit_original_response
    data = await adapter.edit_original_interaction_response(
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/webhook/async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
``` webhook?
slate swan
formal basin
winter token
# slate swan show it then

no i mean it sends error msg if i execute "$add no arguments/ only 1 argument" in console but not in bot

formal basin
slate swan
full cosmos
#

If I name a non global variable the same in two different functions, I should be fine right?

shrewd apex
#

yes

full cosmos
#

thanks

formal basin
# slate swan looks like the message was deleted already
async def button_callback(interaction):
      bot_answers = random.choice(bot_answer)
      if interaction.user.id is not user:
        await interaction.response.send_message("This is not your button do /rock-paper-scissors to use these buttons", ephemeral=True)
      else:
           
       if bot_answers == rock:
          
          await channel2.send(f"{rock} clicked by {interaction.user}")
          for child in view.children:  
           child.disabled = True
          await interaction.edit_original_response(content=f"we both picked {rock} so it is a tie {interaction.user.mention}", view=view)
      if interaction.user.id is not user:
        await interaction.response.send_message("This is not your button do /rock-paper-scissors to use these buttons", ephemeral=True)
      else:
       if bot_answers == paper:
          
          await channel2.send(f"rock clicked by {interaction.user}")
          for child in view.children:  
           child.disabled = True
          await interaction.edit_original_response(content=f"I picked {paper} and you picked rock so I win {interaction.user.mention}", view=view)
      if interaction.user.id is not user:
        await interaction.response.send_message("This is not your button do /rock-paper-scissors to use these buttons", ephemeral=True)
      else:
       if bot_answers == scissors:
          
          await channel2.send(f"rock clicked by {interaction.user}")
          for child in view.children:  
           child.disabled = True
          await interaction.edit_original_response(content=f"I picked {scissors} and you picked rock so you win {interaction.user.mention}", view=view)
       

           
    
    

 button.callback = button_callback```
winter token
#

also when i just send "$add", the bot says answer is 0 instead of sending error msg

slate swan
#

ok but its not full traceback

#

i need the bottom part

shrewd apex
slate swan
winter token
slate swan
shrewd apex
#

view.message = await ctx.send() or inter.response.send_message()
then in ur callback view.message.edit()

slate swan
#

i see so

naive briar
#

(interaction.response.send_message doesn't return the sent message)

slate swan
#

you have a param named *args it will always be a list bcz of that * and you are telling it to convert it to int

#

@winter token ^

shrewd apex
slate swan
#

it will be a list of ints

formal basin
#

hi

slate swan
winter token
#

what should i do

slate swan
#

currently you say that *args: int so it will be int which is wrong it will be list of ints meaning it should be annotated as list[int]

winter token
#

oh

slate swan
#

works now?

slate swan
#

ok then annotate it as tuple[int]

shrewd apex
#

in function params that is

winter token
slate swan
shrewd apex
#

no tuple[] is auto inferred

#

since *args is a tuple

winter token
#

I think the main problem of error message not displaying is cuz i wrote s = 0?

shrewd apex
#

*args: int -> in function is inferred as tuple of integers

slate swan
#

error says otherwise

shrewd apex
#

what are u supplying as arg here? can u show ur sample input

winter token
shrewd apex
#

ah thats it

winter token
#

to check error msg i simply send $add

shrewd apex
#

there is a space

winter token
#

and the boy says 0

#

instead of sending error

shrewd apex
#

!e int(" ")

unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     int(" ")
004 | ValueError: invalid literal for int() with base 10: ' '
slate swan
#

just print args to console and you will know

shrewd apex
#

make a custom converter

shrewd apex
full cosmos
shrewd apex
#

last name points to the last string

#

lemme edit it a bit

full cosmos
#

thank you!

#

want me to paste my version?

slate swan
#

you need to have one string you cant pass many it wont merge them

#

wait but there are no commas what

full cosmos
slate swan
#

!e print("a" "b" "c")

unkempt canyonBOT
#

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

abc
slate swan
#

no way it works like this

full cosmos
shrewd apex
#

it does

slate swan
#

i see it does

full cosmos
#

It adds the extra " by itself

slate swan
#

i never knew

shrewd apex
#

pycharm ftw

#

u can either write like that or use \