#discord-bots
1 messages Β· Page 256 of 1
ofc
a friend did that π
he dont reply π
Just do in portal what's wrong
i want to sell the tool then i want to customize the bio from the script to save the bio π
Why
tf
???
normal..
You cannot
The way your friend did it can lead to their Discord account getting banned and terminated by Discord
Sounds amazing right 
π
alr thanks guys π
doing that would be self botting πΏ
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))
it's not working doesn't explain the problem
!code
So when I test it out to say !help it doesnβt respond
@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
yes but it needs to be list comprehension
!listcomp
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.
Can u help me please
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())
show your cogs folder
folder ?
its cogs.Mod not ./cogs.Mod
oh i though when you do ./ you are refering to the current directory you are in
which is development
no cause its not even path
wdym
yes but its not path
the load_extension does not take a path
oh yeah mb
just do what is said
!d discord.ext.commands.Bot.load_extension
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)").
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.
oh thx
crap another error
show setup function in your cog file
oh my bad i need to await it too
oh god
Help please
With?
looks like you enabled scope that needs redirect url
if you dont know what it is for you prolly dont want that scope
i got it
cool but why delete message?
thanks for the help
idk
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
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
Same question
How?
no idea
And answer this
Disnake or discord?
!d discord.app_commands.checks.cooldown
@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:
Can you answer me?
can someone help me
i dont understand your question hence i cant answer it
Look
When I use the same command it should change the numbers but it doesn't
And then it's some random lines in the code 
does it randomly choose them?
But before that, let's send the same screenshot multiple times 
provide code
what message is sent twice
why to use random module from numpy?
Why?
well i dont know how the seeds in numpy module work
you want a list with 9 random numbers?
I remove this
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))
@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

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
there is something like docs so you dont put random arguments inside
Alright
Work?
Move
k = np.random....
in your command function
the await message.channel.send(f"{message.author.mention} your not allowed to spam")
is repeating twice
!e ```py
import random
print(random.choices(range(10), k=14))
@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]
here you go
here @slate swan
The double ping, pog useful
thats just representation of the list you can format it either way you want
it is inside for loop which means it will be ran as many times as there are loops
!e ```py
x = [0, 2, 5, 6]
print(f'[{" ".join(str(number) for number in x)}]')
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
[0 2 5 6]
No
Didn't fix
show code
- not as screenshot
- code of the command not just 2 lines out of nowhere
and where is the random number generation part in your command?
I want him to make it himself
?
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
if you define it inside command it will be new each command run
thats basics of programming
I am new
Your initial code was fine, just in the wrong place as mentioned
nobody said discord bot is a good project for beginner
Yes
But i can
What can I do with it now?
yeah you can but then dont complain you are new
Id understand that
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()
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 8
002 | 6
003 | 4
004 | 7
!e ```py
import random
random_number = random.randint(1, 9)
def func():
print(random_number)
func()
func()
func()
func()
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 9
002 | 9
003 | 9
004 | 9
see the difference?
Look i can this
X = [1,2,3,4,5,6,7,8,9,]
K = random.randint(x,range=14)
?
thats normal?
did you even look at the example i showed?
no thats not
do u know why this is happening?
i tried to google it but could not find much about
cause you exceed discord api limitations
Yes but range?
True?
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
u know some possible solutions?
possibly you have too many actions happening in your bot so it does too many api calls
for example you have an infinite for loop sending some message will cause this
I know all that, but I don't want 14. How
so what you want
what does Range 14 mean
ππππ
I don't want random to put one number, I want to put 14 random number
and it does it?
it generates a list with 14 random numbers from range 0-9
Send me code
you literally have the code that does it
But the circus doesn't change the numbers@slate swan
and what did you change to the code?
Please explain it better
move the generation part to the command
and if you dont get it
learn python basics better
Generation?
yes you generate the numbers dont you
What?
What generation?
!intents
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.
you generate numbers so i called it generation π
whats so hard to understand
do you use env varriables
then youdont
so why do you
Didn't work
πβ°οΈβ°οΈβ°οΈβ°οΈβ°οΈ
HELP ME SEND VIDEO
well gpt wont help you with discord bot since it has informations from 2021 and discord bot libraries changes a lot from it
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
This example, I have just copied and pasted your code but it didn't work
thats not a discord bot thats discord app then and its 10x more complicated than a discord bot
cause you are pasting it in the wrong place
also its not about copy pasting its about understanding what it does
and where did you find that Join server for you? is it in the scopes when creating oauth2 url
Where do I paste ?
in the command
last time i say this
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
its guilds.join my bad
@slate swan Where?
whenever above you use this varriable
Which row should I put it in now?
..
????
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
It was very strange at first when I made it
It was no problem, then it happened on its own
nothing happens on its own the code you had before could have never worked as you want it to
Bro you tryna use 0Auth
wait you're doing this on a phone
that's crazy
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?
discord's api doesn't support that but everytime that command is run you can add whatever data you would need to a list or whatever datatype you wanna use
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
The question regarding "self bots" has come up here and there, and we'd like to make our stance clear:
Discord's API provides a separate type of user account dedicated to automation, called a bot a...
dankmemer most likely ignored messages from other bots
and iirc dankmemer doesn't even use messaged based commands anymore it's all interaction based
Is it possible to do something if a user doesn't submit a modal and cancels it?
no
There is an on_timeout, though
yes and its very usfull
Anyone know how I can make my click counts function only sync with my guild, instead of gloabally?
!d discord.app_commands.guilds
@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...
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)
thank you so much for responding. This is what I have right now, I'm not quite understanding how to change my on ready tho
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
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))
omg, thank you so much!!!
I've literally been cracking my head over this for hours
ur a legend!

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)
choices are static, what you need is to use an autocomplete menu instead of choices
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()
]
ID of what
user
Just interaction.user.id?
!d discord.Interaction.user gives you a Member | User object
The user or member that sent the interaction.
thanks it worked
how do I drop down menu like this?
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}')```
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()
can you show the full traceback?
It might have some clue to what actually caused the bad request
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
This was right xD
I left the description variable I made as " " and forgot to fill it
Thx!!
how do i take the loop off
With the break keyword.
Idk where you loop and where/how you want to stop it.
after the message is sent
So after channel send break
await message.channel.send(f"{message.author.mention} your not allowed to spam", break)
like that?
but i get error
Under the code not in the code.
ok
can i await it
A break you cannot.
it says break can only be in an loop
Then you aren't inside a loop, so what are you experiencing? Does the bot reply to it's own spam message?
no
When I use the same command
It must change the position of the numbers but it does not
if message.author.id == client.user.id: return this is in my on_message
You can send a code of 14 digits from 0 to 9, but it doesn't work
Code random
What exactly is happening what you want to prevent tough?
spamming
The bot?
it just sends it twice
no a user
Is your bot running twice?
no. i can just purge 1 message from a channel
So the bot says the message twice towards a user.
in a channel
i just did await message.channel.purge(limit=1) so it only sends one
You can help meeee?????
You have to come to the server and I'll get you there
Here you can???
theres a random comma in your list
!d random.randint
random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
do 1, 14
do random.randint(0, 14)
Day 3 of telling this SIGMA/ZAMWA guy to put the goddamn random IN THE COMMAND FUNCTION
Where???
IN THE COMMAND FUNCTION
@bot.slash_command()
async def finder(ctx):
k = ........

gg
Yeah they're just pasting so that's why the wrong indentation
π
Wich one mistake?
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
What is that???
anti spam
provide code
Look
you have another embed in your command
No
yes you do
Where
under that is a other embed
Yes remove this?
spamming what
message.channel.send and logging.send im being rate limited
where is this code located in command or event?
event
what event
on_message
yeah its triggered on each message so if you send a message it will self trigger
ok i did if message.author.id == client.user.id: return
but now it sends it twice
looks like its called twice so you have 2 messages
how is it called twice
no idea try printing the message content and you will maybe get it
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
property mention```
Returns a string that allows you to mention the member.
!d discord.Member.ban
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").
!d discord.Embed
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...
well then no idea you should have error in console if something happens
show code and traceback as text
How to Only One member can use command
In disnake.py
is it for prefixed or slash command
Slash command
!d discord.app_commands.check
@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...
Man Help me
!d discord.ext.commands.Bot.change_presence
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...
literally did
No this
.
yeah so read docs on how to set presence which i linked above
!d discord.ext.commands.Bot.guilds
property guilds```
The guilds that the connected client is a member of.
here is how to get all guilds the bot is in
Check me question
^
i dont see any question in here
Checkk
This ^
There are no questions there
yeah i dont see any question still

Look random why create embed
When i use finder command he create new embed
@slate swan
ok cool and what about it
What?
why are the numbers random now? no idea you show some random code lines that dont even show how you generate it
Check dm
i have dms disabled
I can send you a link here?
Of what
I can't
You check dm
My DMs are disabled
πππ
You didn't disbale
Check
When i use the command he creates a new embed why?
it sends multiple embeds when it should do once?
I use one command he created new embed
Can you check dm and use bot
You understand

this guy has been with the same issue for a week
anyone know why its sending the message twice. message.channel.send and logging.send
What?
Look you understand why to create a new embed
because you coded to do so?
man you should really learn python first
you are sending embed before it even exists
how do i fix it
lmao
please learn the basics of python before you start a discord bot how many times i need to repeat it
I KNOW BRO BUT I AM MOBILE
Does that even count as error
doesnt look like you know
What does that have to do with anything
reading error
is like complaining your print statement printed something

you send an embed and complain it gets sent
You're not here to help you
Here's to teasing them
How come
it has literally nothing to do
anyone
why?
how?
call it logging_channel for example
They'd assume it's logging module
oh
At least I did
x2
ok
can you send it through !paste
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.
!d discord
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.
1 sec
!d discord.Client.change_presence
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...
yes already told you
yep that

await client.change_presence(activity=discord.Activity(type = discord.ActivityType.watching, name=f'{len(client.guilds)} servers')
^
Me when spoonfeeding
https://paste.pythondiscord.com/civaqoduyi
anyone know why its sending the message twice. message.channel.send and logging_channel.send
an on_message event
it is sending it twice
yes
because you are sending it twice
what? how?
you literally have 2 .sends
it goes to different channels
did you do what i say
print message content and see what makes it run
You can send me random code in embed ?
no cause i dont code for you
smh
it printed the last thing i sent while spamming
2 times the same message?
no
so what was the other message who triggered it
the second one
the thing is i muted the user first
then sent it
doesnt look like he was muted if he sent them essage
print logging_channel.id and message.channel.id
why?
you said it should be sent to different channels right
yes
and on the logging_channel it sends it twice aswell
no
me too
the channel where the user spammed
and the logging_channel
possibly your spam detection is wrong and the messages are being sent after for example second and third message

what?
how do i do that
easiest one:
reboot pc
oh ok
open task manager > right click python > kill
where is task manager?
yeah just restart pc
ok
!d discord.Activity
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")
It's keyword-only
nah still sending twice
Do you two on_message events and or listeners
on_message
That didn't answer the question
only one
how many on_message listenres do you have
3
!d discord.Activity
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")
3 of them
send them
You just said one
!paste
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.
with capital b
!d discord.Button
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.
thx
np
where the channel to get help w vpsβs
thank you
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
also instead of creating a function to generate roles you can do list comprehension: ```py
options = [discord.SelectOption(label = role["name"], description = role["description"]) for role in self_roles.find()]
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
interaction comes before select
in callback function
ohh
also the error you are getting is cause somewhere you call .add_command and you passed something that is not command to it
why do you need to call this method
.add_command? where?
oh sorry its source code my bad
so then
are you talking about .add_roles?
show line 71 in bot.py
bot.add_command(self_roles.self_roles)
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
ahh from the beginning only i am doing bot.add_command
yeah but you should not call this method directly use cogs instead
why not?
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
i can't i have many files and i need to keep them in different folders
so that i will get to know which command belongs to which category
sure but it will be harder to load them
Wouldn't subclassing help with that?
subclassing what
The cogs
you always need to subclass from Cog
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
no thats not how it works
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?
Naming conventions 
no why would you want to do that
cogs are to separate commands not merge them all
yeah i dont see why you'd want to do that
Welp i did that like in my case the code wasn't getting pretty big and messy so i did this
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
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
how can i make it so it sends how long the bot has been up for
save current date on startup and then display timedelta from current date to start date
how?
!d datetime.datetime.now
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").
I would recommend going over the datetime library and familiarizing yourself with it, because it can be incredibly useful
!d datetime.timedelta
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...
you don't "count up", you simply subtract two datetime objects to get a timedelta object of the time lapsed
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)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
4 days, 13:52:21.508629
yep 20.06.2023 was 4 days ago etc...
How to start coding
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
YouTube videos, huh, sounds about right
for beginners doesnt matter
if you want to learn python there are resources here:
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Ok thanks
is using a bot as a class a good practice ?
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
that and you need to await self.load_extension
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
import asyncio library and use it to run your load_cogs function
no just run it in on_ready
oh that too mb
asyncio.run wouldnt even work since there is already running an event loop
yeah you're right im sped my bad
i did
await self.load_extension("cogs.add_money")```
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
ahh where to put await?
before calling load_cogs 
async def load_cogs(self):
await self.load_extension("cogs.add_money")
i did this
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?
- it wont work yet
- why pass bot inside?
i didnt understand where are you telling me to put await
could you put await and show in the code?
thats good now just asking why you pass bot to the method
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
ahh i am using github copilot so he passed bot there i am removing that
bot.load_cogs()
no offense but copilot wouldn't pass the class to the function, its smarter than that.
are you using channelid to send to, provide code please
idk he did it
how do i send it in quotes i forgot β οΈ
!codeblock
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)
make sure that channel_id is indeed the correct channel
idk whats wrong fr fr
it is
interesting. should be sending to that channel then, are you 1000% sure?
i am even 100000000000000000000000000% sure
fixed it but idk how lmao
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")
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?
why did you remove the await
do you mean i shall keep await bot.load_cogs() like this?
then where is the async ?
what
ok
async def on_ready(self):
await self.load_cogs()
print(f'{bot.user} has connected to Discord!')
ok?
yeah it literally tells you
that it cannot choose 14 different items from a list that contains 9 items
you probably want random.choices
yes, usually it's used in an unhelpful/rude way
yeah this guy already had random.choices and made it work but i dont know why he changed it back to the form that does not
odd guy
cntrl z
why did you put this outside function again?
I mean this why again?
Why didn't Change?
man we literally solved it a day ago
Can you help me?
v = random.choices(...) is only run once at the start, hence does not change between runs
You mean remove sample?
what did you do with the code you had yesterday
can you paraphrase what i said
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'".
example when banning?
@wise jewel
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.
I know I put it but bot didn't change
Can you help me?
@tidal folio do you understand this explanation?
What can I do with it?
You ban him?πππ
Can you answer me?
not sure which error it raises then
Why didn't it change??
There is someone?
Forbidden or HTTPException
Man you can?
there is not a strict exception for this case for sure
that would be odd bot if you could ban yourself
Hello?
man im not helping you i already did
you dont understand basic things learn basic python first
So reply I'll watch and you haven't told me why it doesn't change before
last time i explain why its the same each run of the command
!e ```py
import random
random_number = random.randint(1, 10)
def func():
print(random_number)
func()
func()
func()
func()
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 4
002 | 4
003 | 4
004 | 4
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()
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 9
002 | 8
003 | 7
004 | 5
when we generate inside function its generated again each function call
You mean i adead func()?
can someone please take a look at my question?
Where even is your question
here
thats not how u use view components
aww. It seemed that was the only part that was working π¦
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 ^^
Thank you I will take a look in a second
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
I think you can get that with ctx?
ctx.author gets you the user who used the command I think
not the user? dont u usually want them to be the same user?
both interaction and ctx have author properties
I think they want to disable the button when it is not the same user
compare it with the interaction recieved on button callback
!d discord.ui.Button.disabled
property disabled```
Whether the button is disabled or not.
What does "button.callback = callback" do in this example?
assign the function to be called after button click
^^
thank you
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
Sorry, english is not my first language. does monkey patch mean it's not the ideal solution but it works?
its not the best solution but it works yeah
thank you
99% of the time that is enough
how did you calculate this 
how many ppl would touch code that is working perfectly 
also monkey patch is fine as long as its a small callback imo nothing to complex
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
check by id
wouldn't it be interaction.author and ctx.author?
ok
no, not quite
interaction.user
lol
!d discord.Memebr
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`).
!d discord.Member
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`).
property id```
Equivalent to [`User.id`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.id "discord.User.id")
I'm sorry if I'm being stupid but how would I differentiate between the buttons?
button_1.callback, button_2.callback, etc.?
yep
u can pass the command user into the view or atleast the id then in interaction_check use == to compare id
how can i disable a button
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
why i have ping here
ghost
i have 3 buttons will it disable all those 3 buttons
cause i want it to
it will disable every item in the view
ok thanks
its not disabling
i havent subclassed it so i put view
and where did you put it
after it has been pressed
did u edit the message with the new view?
no
then edit
i have to?
nothing will change until you edit
ohhhh
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
btw here is inter a varible?
its interaction
how horribly wrong did I do this?
if you use global varriables? very
totally
Seeing the word global already makes it 10 times worse than it ever could be
π
real
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... π
yes
@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
i just sends it again with disabled buttons and the original is still not disabled
bot is not defined too bad
Oh so "async def callback()" is supposed to be inside the same function!
yeah since you dont use it outside
you only need it for this
u can yes in languages like python function is a first class citizen
altho if ur using it in another command u can define the callback outside
Okay that makes a lot of sense
i said edit the message with the view
dont send the new view
gg
Does it automatically know what "name" is?
its called a f string it should work fine since name is defined in outer scope did u try it?
Outer scope?
it gets the name from the for loop: for name in names:
so that defines and uses the variable at the same time?
yeah
thats just how the for loop works yeah
okay thank you!
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```
!e
code
!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!
!e
import os
print(os.listdir())```
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
['main.py']
#bot-commands
!d discord.Interaction.edit_original_response
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.
why cant i use it here itys called discord bots
its for help with discord-bots
for child in view.children:
child.disabled = True
await interaction.edit_original_response(f"I picked {paper} and you picked rock so I win {interaction.user.mention}", view=view)```
its channel to help with discord bots
read the channel description
content=
content?
your text must be with keyword content
content="message"
@slate swan
yes
like that
??
can u help me solve this
down is so popular π
thats not even about discord bots
nope i know nothing about ctypes
he is a big koder
looks like there is no such thing like windll in this library
The only ctype I know of is C#

@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
prolly issue the replit machine is like ubuntu or some vm and windll dont exist
is there an error in the console though?
yes
show it then
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?
looks like the message was deleted already
when i clicked the button
windll is windows specific
no i mean it sends error msg if i execute "$add no arguments/ only 1 argument" in console but not in bot
nothing is deleted in the button
ok so can you show the error in the console
If I name a non global variable the same in two different functions, I should be fine right?
yes
thanks
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```
also when i just send "$add", the bot says answer is 0 instead of sending error msg
can someone help me
make ur original message a property of the view then do message.edit()
thats a lot of copying code
too long xd
ah okay
view.message = await ctx.send() or inter.response.send_message()
then in ur callback view.message.edit()
i see so
(interaction.response.send_message doesn't return the sent message)
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 ^
oops original_response it is then
ah okay thx
it will be a list of ints
hi
do you know how to annotate it properly now?
a bit confused
what should i do
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]
oh
works now?
no tbh *args: int is interpreted by the typecheck as tuple[int, ...] https://peps.python.org/pep-0484/#arbitrary-argument-lists-and-default-argument-values
Python Enhancement Proposals (PEPs)

ok then annotate it as tuple[int]
in function params that is
no
why
I think the main problem of error message not displaying is cuz i wrote s = 0?
*args: int -> in function is inferred as tuple of integers
error says otherwise
what are u supplying as arg here? can u show ur sample input
$add 2 3 ....
ah thats it
to check error msg i simply send $add
there is a space
!e int(" ")
@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: ' '
just print args to console and you will know
make a custom converter
in ur case here it shows invalid literal 'a' so a letter slipped in there somehow too
The buttons now almost work! Thank you!
The only problem is that it always does what the third button should do instead of the one that was pressed.
ah ic yeah thats cause thats what last name was defined
last name points to the last string
lemme edit it a bit
this ctx.send will fail
you need to have one string you cant pass many it wont merge them
wait but there are no commas 
!e print("a" "b" "c")
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
abc
no way it works like this
Pycharm shouts at me if I let a line get too long so I cut it up.
it does
i see it does
It adds the extra " by itself
i never knew
