#discord-bots
1 messages · Page 361 of 1
the code repeatability is huge
why is there a whole method to create 1 table
why
dont ask me 

what happen
It's a pain to create a command handler for newbies like meh
error handler?
Even if you have good knowledge
No command handler
what the hell is that

never heard of that
maybe he just means a command
Bruh
lucky for you there is a whole guide about most fetures discord.py offers that me and few others created
https://fallendeity.github.io/discord.py-masterclass/creating-a-bot/
A hands-on guide to Discord.py
a terminal?
yeah bro this shit is ass
python3 bot.py
yeah no its not

im joking dw
at least stuff i made is not 
and what is wrong about this
Nothing wrong bro was asking what is command handler
@slate swan
thats called a console i belive
wait how is running your code a dpy issue? 💀

No i said creating that is a pain see again
i aint getting what you have problems with

demnstrate an example
Their status says it all tbh
soheab arrived :stab:
original code:
import discord
from discord.ext import commands
import json
import asyncio
with open('settings.json', 'r') as f:
settings = json.load(f)
prefix = settings.get('prefix', '>')
token = settings.get('token')
if not token:
print("Invalid Token in settings.json!")
exit()
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=prefix, intents=intents)
initial_extensions = ['commands.ping']
for extension in initial_extensions:
bot.load_extension(extension)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
bot.run(token)
i really have no clue why this is even happening anymore, im getting a tracemalloc warning/error and none of my commands are working, i've tried using an await but it still for some reason doesnt work, original code is above
you need to await bot.load_extension
yes but it has to be in an async function and whenever i do it just gives errors
Yeah you don't need to be doing it outside anyways, it needs to be inside some setup_hook shit, @viscid hornet might know, I haven't used dpy in a while
just put it in setup hokk
replace the on_ready event with setup_hook and load all your extensions there
on_ready() can be called multiple times but setup_hook() is only called once
tracemalloc means you forgot to await something
wont i need on_ready()
you can switch on_ready with setup_hook is what they said, so no
setup hook IS on ready
but only called once
as opposed to on ready which can be called multiple times
ohh
No it's not
so instead of reloading all your commands 2 or 3 times, you only need to do it once
(as an oversimplification)
om_ready is an actual even from discord for when everything is ready like cache etc
oh?
what so like
@bot.event
async def setup_hook():
print(f'Logged in as {bot.user.name}')
for extension in initial_extensions:
await bot.load_extension(extension)
or something?
ohh and setup hook is doy
yes 👍🏽
setup_hook is called by dpy after login
Yes but no
oh ok thanks for lmk
discord.ext.commands.errors.ExtensionFailed: Extension 'commands.ping' raised an error: TypeError: object NoneType can't be used in 'await' expression
You should subclass and override the method
hes gonna tell em to subclass it 😔
It's not an event
i aint that smart, i dont code discord bots much i just do it from time to time
leo said that also works. cant remember when, where or what his specifics were
he just pulled a “technically”
somehow still ended up giving me an error though
setup func must be async
Check your extensions
it is isnt it
You should learn python before doing anything bot related
Idk not my code
check the bottom of your ping file for a setup function
oh wait yeah it isnt async
bruh now this RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited bot.add_cog(Ping(bot))
yeah your messages duplicated
yes
add_cog is async, await it
yeah you gotta await it too
Oh FFS discord
im so dumb lmao alr
the error pretty much tells u what to do here
finally fixed it, thanks guys i was so confused
tbh i didnt even read it properly i should have probably done that before asking
yes, always a good idea
how to make a command that will give a user ( ID ) a role?
by example I want it :
?role (User ID I want to assign the role to) ( Role ID )
im pretty sure we cant directly give you the code but only help you with it?
im not sure though
well i can try myself I just need a little push yk
@bot.command()
async def role(ctx, user:discord.User, role:discord.Role):
await user.add_roles(role.id)
something like that
u need to have the classification of the user and role so discord can convert the id into the user or role
in the simpliest way possible ^
yea
i think i got the correct code ( not sure ) but idk if I'm allowed to send it here
you can send it here
@bot.command()
@has_permissions(manage_roles=True)
async def role(ctx, user: discord.Member, role: discord.Role)
# use discord.Member.add_roles to add the role
# make sure the bot has permissions to add the role (bot's role is above the user, and the input role)
something like this. wrote this in discord though
@bot.command()
async def role(ctx, user: discord.Member, role: discord.Role):
if ctx.author.guild_permissions.manage_roles:
if role not in user.roles:
await user.add_roles(role)
await ctx.send(f"Role `{role.name}` added to {user.mention}.")
else:
await ctx.send(f"{user.mention} already has the role `{role.name}`.")
else:
await ctx.send("You don't have permission to manage roles.")
seems about right
what are the downsides of using all intents? (discord.Intents.all())?
should be i think
Incorrect, discord.User doesnt have add_roles
you have to verify all the intents that you using
i said its something like that i have made a role adding bot in ages
alr
and does it work?
it should do
it should
i dont know I'm currently trying to grab one of my bot's token rq
let me see
change User to Member
discord.Member not discord.user
they have discord.Member only?
member has the addroles not the user so
yeah and the code they sent has discord.Member... so they don't need to change it
oh
yeah
lmao
ok back to making minecraft in discord
minecraft in discord
yea
wanna try
made the mining system only yet
and inventory
need to make crafting fighting and more that i cant think of right now
wondering rn how you're going to implement fighting and stuff
u wanna try the mining tho?
also got enchantment
and Potions
and Food
sure if you want me to
What is wrong?
class Whitelist(discord.ui.View):
def __init__(self):
super().__init__()
self.link = None
@discord.ui.button(label='Whitelist', style=discord.ButtonStyle.green)
async def whitelist_button(self, button: discord.ui.Button, interaction: discord.Interaction):
# Add the link to the whitelist
if self.link:
whitelisted_links.append(self.link)
with open(whitelist_file, "w") as f:
json.dump(whitelisted_links, f)
# Edit the interaction response message to indicate the link has been whitelisted
await interaction.response.edit_message(content=f"Link '{self.link}' has been whitelisted.", view=None)
def set_link(self, link):
self.link = link
would be nice if you actually said your issue
await interaction.response.edit_message(content=f"Link '{self.link}' has been whitelisted.", view=None) AttributeError: 'Button' object has no attribute 'response'
any errors?
Switch params
you swapped arguments
^^
flip the interaction and buttons args
sure dm me
alr
self, interaction, button
the interaction comes first
self is always first in methods
not if its a class' instance's method
How can I remove the button after whitelisting the link?
!d discord.ui.View.remove_item
Help me
remove_item(item)```
Removes an item from the view.
This function returns the class instance to allow for fluent-style chaining.
Hmh self.remove_item(button) doesn't remove it 
you need to update the message with the new view
need to update the view
i misspelt “view” as “vhew”
you won this time cat person
I did
# Remove the button from the view
self.remove_item(button)
# Send a message in embed format
embed = discord.Embed(
title="Link Whitelisted",
description=f"The link '{self.link}' has been whitelisted.",
color=discord.Color.green()
)
await interaction.response.send_message(embed=embed, view=self)```
hmm thats weird. where are you doing this?
!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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
put it in here cuz im on phone
did you pip install discord?
.
You're sending a new message with the view, not editing the original message 🤨
Of course it won't remove the button
@dim valve whats in the requirements file?
are u running it in a docker container?
Oh so I need to do something like
await interaction.message.edit(view=None)
await interaction.response.send_message(embed=embed)```
Sure
Do you like my method to whitelist links? Or do you have any other suggestions?
use edit_message
there’ll be inter failed errors if they dont defer before the first option
What do you mean?
!d discord.InteractionResponse.edit_message
await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=..., delete_after=None, suppress_embeds=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by editing the original message of a component or modal interaction.
File deleted by @unkempt canyon
Isn't await interaction.message.edit(view=None) the same?
- you’re removing the view, not the button
It may do the same thing, but they're not necessarily the same
- you arent responding to the interaction, which you have to do
no. 2 is the key thing
It looks like they're responding to the interaction to me, but okay
they’re editing the message, not responding to the interaction
like editing the message itself, which doesnt count as a response
I don't know about you, but it seems to me that:
await interaction.message.edit(view=None)
await interaction.response.send_message(embed=embed) # <--- they're responding here
Can't say this in here, you fool.
setup_hook can use the @bot.event decorator, it's just technical an implementation detail
|| the decorator just patches the Bot.<attr> where <attr> is the decorated coro func's name ||
Yeah
now im even more confused 🤦🏽♂️.
Message.edit is not part of the interaction flow
Interaction.edit_original_response etc is part of it
This just calls regular Message.edit
yeah thats what i was tryna explain
You can edit as a response and send a followup
or defer, edit original response and send followup
You rarely need to interact the interaction's message
idk indonesian
sry
but u can copy paste the contents of those files i've asked
idk it seem to be working
or am I missing something?
oh thats what you wanted
i thought you wanted to edit the original message with the new embed
lol
🫠
any idea of how to make a command that will show all roles names and their IDs?
roles = user.roles
for role in roles:
print(role)
print(role.id)```
user is misleading since it has to be a member
all roles of the guild
not member
💀yeah ok
!d discord.Guild.roles
property roles```
Returns a sequence of the guild’s roles in hierarchy order.
The first element of this sequence will be the lowest role in the hierarchy.
@wanton current
what
most of this code
replace it with guild instance
also there is this issue.
my bot works perfectly, but when i added him to my friends server all commands stopped working ( almost, the administrative commands did stop ), the bot has all the perms enabled, i have access to the administrative commands too, what's the issue here?
by example I have this .role (uid) (role id ) command that worked in the test server, when i added the bot it stopped working in the friends server, the bot has all perms enabled ( like I already said )
wait can you rephrase what your issue is please?
Ok yes,
So, I made multiple commands, one of the important ones that wont work is .role
.role works like this: .role ( Target User ID ) (The ID of the role that will be given to the user )
This worked on my test server for the bot, where the bot had admin,
I moved it to my friends server, where the bot got admin, but the. .role command didnt work for whatever reason
are you recieving any error in the terminal?
no error anywhere
if you have a global error handler disable it and then check
and i checked the code, only requirement for the command to work is to have your ID inside a config.json file ( which it has mine ) and it works
i dont have that,
@commands.command()
async def role(self, ctx, user: discord.Member, role: discord.Role):
if ctx.author.id in config["topdogs"]:
if role not in user.roles:
await user.add_roles(role)
await ctx.send(f"✅ | Role `{role.name}` added to {user.name}.")
else:
await ctx.send(f"❌ | {user.name} already has the role `{role.name}`.")
else:
await ctx.send("❌ | You don't have permission to manage roles.")
and i checked, the bot has the same perms in both the servers
what about intents?
in the code? it's the same didnt ever change it
yeah in the code and dev portal too
it's the same bot yes
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
with open('config.json', 'r') as file:
config = json.load(file)
PREFIX = config["prefix"]
TOKEN = config["token"]
bot = commands.Bot(command_prefix=PREFIX, intents=intents, case_insensitive=True)
bot.remove_command('help')
async def main():
async with bot:
await load()
await bot.start(TOKEN["main"])
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles) to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)s must appear lower in the list of roles than the highest role of the member.
yeah that's why i dont know why it works in other server but in other server not, having the exact same code, intents, requirements that need to be meet ( topdogs )
let me check the docs
alr
can you wrap the role in the part where you are adding in an int() function
and then see
or can try using get_role() on the the role_id first and passing it to add_role()
dk to do all of that, i'm still learning discord.py, that's why i came here to ask cuz this seemed a serious issue
also make sure that your bot role is higher in hieararchy then the role you are trying to assign
it is
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
use this to get the role and pass it to add_role function
you can Guild object by using ctx.guild
ill see
@commands.command()
async def role(self, ctx, user: discord.Member, role_id: int):
if ctx.author.id in config["topdogs"]:
guild = ctx.guild
role = guild.get_role(int(role_id))
if role:
if role not in user.roles:
await user.add_roles(role)
await ctx.send(f"✅ | Role `{role.name}` added to {user.name}.")
else:
await ctx.send(f"❌ | {user.name} already has the role `{role.name}`.")
else:
await ctx.send("❌ | Role not found.")
else:
await ctx.send("❌ | You don't have permission to manage roles.")
better or im missing on smth?
role = guild.get_role(int(role_id))
edited
role_id parameter will be recieved as a string evein if you typehint it as string
that's just how discord works
oh so now it's fixed?
don't know you have to check it and see
alr
still the same somehow
I don't get what could go wrong here
can you add checkpoint's in the command like printing statements in there after each step to see till which point it is executed
alr
@commands.command()
async def role(self, ctx, user: discord.Member, role_id: int):
if ctx.author.id in config["topdogs"]:
guild = ctx.guild
role = guild.get_role(int(role_id))
if role:
if role not in user.roles:
await user.add_roles(role)
await ctx.send(f"✅ | Role `{role.name}` added to {user.name}.")
print("Role added")
else:
await ctx.send(f"❌ | {user.name} already has the role `{role.name}`.")
print("Error: user already has the role")
else:
await ctx.send("❌ | Role not found.")
print("Error: Role not found")
else:
await ctx.send("❌ | You don't have permission to manage roles.")
print("Error: No perms for u")
should be good?
add one at the start of function definition and one more after the first if statement
@turbid condor apparently it's not printing anything at any point
@commands.command()
async def role(self, ctx, user: discord.Member, role_id: int):
print("Start")
if ctx.author.id in config["topdogs"]:
print("Valid User")
guild = ctx.guild
role = guild.get_role(int(role_id))
if role:
if role not in user.roles:
await user.add_roles(role)
await ctx.send(f"✅ | Role `{role.name}` added to {user.name}.")
print("Role added")
else:
await ctx.send(f"❌ | {user.name} already has the role `{role.name}`.")
print("Error: user already has the role")
else:
await ctx.send("❌ | Role not found.")
print("Error: Role not found")
else:
await ctx.send("❌ | You don't have permission to manage roles.")
print("Error: No perms for u")
it means your cog isn't loaded correctly ot there is some issue with in the file
weird cuz other commands from the file work
then check if this command isn't outside the last class
it's like the rest of the commands, nothing wrong
i removed self
you will need self inside a cog
when i add the self and run it again, it wont print anything
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
one sec
weird i don't see any issue
well i'm out of ideas you might need to w8 for someone else
np
I am trying to have my bot send a message whenever a spefici user sends a message in a channel. How can I go about this?
!d discord.Client.on_message
No documentation found for the requested symbol.
@bot.listen('on_message')
async def yourmsglistener(message: Message):
pass```
you want this ⬆️
Thanks!
how can i get a users id in a cog command file? here's the code => https://paste.pythondiscord.com/QOOA
@viscid hornet
Is it supposed to DM the user that submitted the modal?
How do I implement the cogs to my bot?
async def load_cogs():
for filename in os.listdir("src/cogs"):
if filename.endswith(".py"):
await bot.load_extension(f"src.cogs.{filename[:-3]}")```
already done
cogs != extensions
async def load_cogs():
for filename in os.listdir("src/cogs"):
if filename.endswith(".py"):
await bot.load_extension(f"src.cogs.{filename[:-3]}")
@bot.event
async def on_ready():
print(Fore.LIGHTWHITE_EX + pyfiglet.figlet_format("Sew", font="slant"))
print(Fore.LIGHTWHITE_EX + f"({round(bot.latency * 1000, 2)}ms) | Prefix: [{bot.command_prefix}] Bot: [{bot.user.name}#{bot.user.discriminator}]")
try:
cursor.execute("SELECT 1")
result = cursor.fetchall()
if result:
print(Fore.LIGHTWHITE_EX + "--------------------------------")
print(Fore.LIGHTWHITE_EX + "[+] Conectado a la base de datos")
except sqlite3.Error:
print(Fore.LIGHTWHITE_EX + "-------------------------------------")
print(Fore.LIGHTWHITE_EX + "[-] No es posible establecer conexión")
await load_cogs()```
?
no.. i mean thats prob what its doing but thats not what i was trying to do
whats the issue
cogs don't charge
So what are you trying to do?
charge?
dm the given user id instead of the whos submitting the modal
/home/runner/Utl-bot/src/cogs/general.py:13: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(General(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2024-05-04 16:23:45 ERROR discord.client Ignoring exception in on_ready
Traceback (most recent call last):
File "/home/runner/Utl-bot/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 947, in _load_from_module_spec
await setup(self)
TypeError: object NoneType can't be used in 'await' expression
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/Utl-bot/.pythonlibs/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/home/runner/Utl-bot/bot.py", line 70, in on_ready
await load_cogs()
File "/home/runner/Utl-bot/bot.py", line 52, in load_cogs
await bot.load_extension(f"src.cogs.{filename[:-3]}")
File "/home/runner/Utl-bot/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1013, in load_extension
await self._load_from_module_spec(spec, name)
File "/home/runner/Utl-bot/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 952, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'src.cogs.general' raised an error: TypeError: object NoneType can't be used in 'await' expression```
setup func must be async
Make sure to also await add_cog
Ic
async def setup(bot):
bot.add_cog(Utils(bot))``` ?
You can access your bot from interaction.client and use get_user on that
Yes but also the message you replied to
async def load_cogs():
for filename in os.listdir("src/cogs"):
if filename.endswith(".py"):
await bot.load_extension(f"src.cogs.{filename[:-3]}")```
cog: py async def setup(bot): bot.add_cog(Utils(bot))
thx bro
cogs is correct now
@timber dragon thanks
await it
What is the best way to detect links/domains?
oh wait nvm
urlparse?
eyes bc it turns blue when its a link
probs regex from what ive heard
regex
one dude
Are cogs better with async and await or without async and await?
they dont work without async and await
like if i said “are cars better with wheels than without?”
What is wrong with urllib.parse?
@viscid hornet
what
async def load_cogs():
for filename in os.listdir("src/cogs"):
if filename.endswith(".py"):
try:
await bot.load_extension(f"src.cogs.{filename[:-3]}")
print(f"Cog: {filename[:-3]} cargado.")
except Exception:
print(f"Cog: {filename[:-3]} error.")
@bot.event
async def on_ready():
print(Fore.LIGHTWHITE_EX + pyfiglet.figlet_format("Sew", font="slant"))
print(Fore.LIGHTWHITE_EX + f"({round(bot.latency * 1000, 2)}ms) | Prefix: [{bot.command_prefix}] Bot: [{bot.user.name}#{bot.user.discriminator}]")
try:
cursor.execute("SELECT 1")
result = cursor.fetchall()
if result:
print(Fore.LIGHTWHITE_EX + "--------------------------------")
print(Fore.LIGHTWHITE_EX + "[+] Conectado a la base de datos")
except sqlite3.Error:
print(Fore.LIGHTWHITE_EX + "-------------------------------------")
print(Fore.LIGHTWHITE_EX + "[-] No es posible establecer conexión")
await presence.start()
await load_cogs(bot)```
I have an error and it is that it does not show the prints in the console
i dont think it works with links in messages
also you need to stop with catching exceptions and not doing anything with them
other than printing “hey there was an error”
Should I close the connection to the database if it doesn't connect?
“where was it?” 🤷🏽♂️
“what part of the line was it on?” 🤷🏽♂️
“what file is it in?” 🤷🏽♂️
wdym?
the cogs are in src/cogs
@slim bloom do you have any error message?
:/
is this the whole code?
no
xD
Firstly, you understand what on_ready does and how it works. Then you put things in a more appropriate place
so explain what you have in your code and what you run because it is impossible not to have an error code
:v
What should be in the on_ready alone?
(that wasnt to your message)
Do you understand how on_ready works? This should be an informed decision rather than randos telling you
for example
@bot.event
async def on_ready():
print("Bot is ready")
only py @bot.event async def on_ready(): print(Fore.LIGHTWHITE_EX + pyfiglet.figlet_format("Sew", font="slant")) print(Fore.LIGHTWHITE_EX + f"({round(bot.latency * 1000, 2)}ms) | Prefix: [{bot.command_prefix}] Bot: [{bot.user.name}#{bot.user.discriminator}]") in on_ready?
@bot.event
async def on_ready():
print(Fore.LIGHTWHITE_EX + pyfiglet.figlet_format("Sew", font="slant"))
print(Fore.LIGHTWHITE_EX + f"({round(bot.latency * 1000, 2)}ms) | Prefix: [{bot.command_prefix}] Bot: [{bot.user.name}#{bot.user.discriminator}]")
await presence.start()
await load_cogs(bot)```
Do you want a print every time the bot does a routine reconnect?
Then go nuts but I have no idea why you'd care about that
I'm not sure if you can currently use load_cogs in on_ready
maybe try to load extensions in main():
we don't know the whole code so it will be hard to help you, I think
Should I load the cogs in on_connected?
try writing a bot adding the code one by one step by step
Extensions are just extensions of the bot. Generally they don't (or shouldn't) care at all about your bot being connected
You don't need to wait until you're connected to add them
So where in the code would it be correct to load the cogs?
When do you want to load them?
I don't know, which part would be correct
I load it in the main() function
It entirely depends on what you want
exactly
I can tell you that the most common approach is to put any setup inside the bot's setup_hook, but it should be an informed decision based on what you're trying to accomplish instead of just doing that because I said so
I do it this way
initial_extensions = ['cogs.code1',
'cogs.code2']
async def main():
async with bot:
await load_extensions()
await bot.start('*** secret ***')
async def load_extensions():
if __name__ == '__main__':
for extension in initial_extensions:
try:
await bot.load_extension(extension)
except Exception as e:
print(f'Failed to load extension {extension}', file=sys.stderr)
traceback.print_exc()
the bot is running by
asyncio.run(main())
how I can make a command to reset the bot?
define "reset the bot"
rerun the project
There's not a good way to do this besides just shutting the process down entirely and letting a process manager spin it back up
@fast osprey ```py
@bot.event
async def on_ready():
print(Fore.LIGHTWHITE_EX + pyfiglet.figlet_format("Sew", font="slant"))
print(Fore.LIGHTWHITE_EX + f"Prefix: [{bot.command_prefix}] Bot: [{bot.user.name}#{bot.user.discriminator}]")
await presence.start()
@bot.event
async def on_disconnect():
print("El bot se ha desconectado de Discord")
@bot.event
async def on_connect():
print("El bot se ha conectado a Discord")
@bot.event
async def on_resumed():
print("El bot se ha reanudado a Dsiccord")```
@strange lichen
so what is the question?
What is presence, and do you want to start it every time the bot does a random routine reconnect?
(task loops already look for disconnection errors and don't cancel themselves as a result)
Also, if it is a task loop, .start() isn't a coroutine
@tasks.loop(seconds=30)
async def presence():
await bot.change_presence(status=discord.Status.online, activity=discord.Activity(type=discord.ActivityType.watching, name=f"{bot.command_prefix}help | {bot.command_prefix}invite"))
await asyncio.sleep(15)
await bot.change_presence(status=discord.Status.online, activity=discord.Activity(type=discord.ActivityType.watching, name=f"CPU: {psutil.cpu_percent():.2f}% | RAM: {psutil.virtual_memory().percent:.2f}%"))
await asyncio.sleep(15)```
@tasks.loop(seconds=30)
async def presence():
await bot.change_presence(status=discord.Status.online, activity=discord.Activity(type=discord.ActivityType.watching, name=f"{bot.command_prefix}help | {bot.command_prefix}invite"))
await asyncio.sleep(15)
await bot.change_presence(status=discord.Status.online, activity=discord.Activity(type=discord.ActivityType.watching, name=f"CPU: {psutil.cpu_percent():.2f}% | RAM: {psutil.virtual_memory().percent:.2f}%"))
await asyncio.sleep(15)
async def load_cogs():
for filename in os.listdir("src/cogs"):
if filename.endswith(".py"):
await bot.load_extension(f"src.cogs.{filename[:-3]}")
@bot.event
async def on_ready():
print(Fore.LIGHTWHITE_EX + pyfiglet.figlet_format("Sew", font="slant"))
print(Fore.LIGHTWHITE_EX + f"Prefix: [{bot.command_prefix}] Bot: [{bot.user.name}#{bot.user.discriminator}]")
await presence.start()
await load_cogs(bot)
@bot.event
async def on_disconnect():
print("El bot se ha desconectado de Discord")
@bot.event
async def on_connect():
print("El bot se ha conectado a Discord")
@bot.event
async def on_resumed():
print("El bot se ha reanudado con Discord")```
async def main():
await load_cogs()
await bot.start(os.getenv("TOKEN"), reconnect=True)
asyncio.run(main())```
because everyone cares about how much RAM your bot is using that it needs to be in the status
how to run miltiple discord bot on one project?
and if I edited it all of them will get edited
Can someone help me with this please 🙂
If you're still putting those things in on_ready, you haven't really been listening at all to what I've been saying
Describing what's going wrong and what you expect to happen would be a good start
It's preety obvious I'm giving a on reaction callback and with bot.event but it's showing indentation error
Been struggling with this for a hour now...
The indentation error will tell you which line it's happening on
@strange lichen i like you broo
i mean it says what is wrong exactly
!paste the code around that
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
You're trying to put an event underneath an except
^^
How to fix it
Probably want to fill out that except block with whatever you want to do
thx
Cog añadido: utils
Cog añadido: general
Conectado a Discord
_____
/ ___/___ _ __
\__ \/ _ \ | /| / /
___/ / __/ |/ |/ /
/____/\___/|__/|__/
Prefix: [?] Bot: [Pruebas#3847]```
@strange lichen the best
async def load_cogs():
for filename in os.listdir("src/cogs"):
if filename.endswith(".py"):
try:
await bot.load_extension(f"src.cogs.{filename[:-3]}")
print(Fore.LIGHTGREEN_EX + f"Cog añadido: {filename[:-3]}")
except Exception as e:
print(Fore.LIGHTRED_EX + f"Cog error: {filename[:-3]}: {e}")
async def main():
await load_cogs()
await bot.start(os.getenv("TOKEN"), reconnect=True)
asyncio.run(main())```
How can I fix this @fast osprey
You have 3 different indents one after another
How can I fix it then?
This editor is also wrapping your lines weirdly
I am using VPS for this so maybe...
So how to fix this @fast osprey
Don't have to keep pinging me
Ohk sorry mb
Do you fully understand how indents work in python and what they accomplish? That's a good first step
Otherwise you're just hitting tab and praying
I am but my braincells don't work at night so if you can help me it's good
Do you see how your if not 2 line is completely unaligned with all of the lines above it?
Yeah
@fast osprey
You should probably ask the question instead of just pinging them
I think that's with the return maybe? Or is it wrong?
that line is not aligned with any of the lines above it within the function
So that will fix it?
I have a question, how can I avoid data breaches and performance problems and errors that have to do with the db?
@fast osprey
Bruh this isn't the channel for this
That's an extremely broad question lol
step 1. sanitize input
its a db for my bot
sqite3
sqlite3*

@slim bloom good to hear about success, enjoy xD
Anywho yeah there's an entire channel dedicated to databases, but you probably want to pick one topic at a time
Refresh your discord client
when loading cogs does it have to create 2 pyache files or is something wrong
its normal
yes
okays
this issue is still ongoing if someone can help me ( ping me )
@viscid hornet What could I put in a utils folder?
anyone here good with ffmpeg
not replying, i tried putting print in the code to see where it fails, no luck
idk to make them
and i dont like them either
yes
that's what the issue is
he didnt touch anything
ye it's fine
ill try
tell sth more about the problem
idk, i did like @slate swan said and added the bot to a diff servers, works perfectly
i also checked my friend's server, every perms enabled, role hierarchy is also good, nothing unusual
ah ok so propably another server have enought libraries installed maybe
this is when it works, for my friend's server doesnt output anything
apparently, it can detect if i already have a role, but can not assign a role, the role the bot has, has "manage roles" perms enabled, so idk
yes
[gdigrab @ 00000198adc00a00] Stream #0: not enough frames to estimate rate; consider increasing probesize
Input #0, gdigrab, from 'desktop':
Duration: N/A, start: 1714850803.882659, bitrate: 6186977 kb/s
Stream #0:0: Video: bmp, bgra, 4480x1440, 6186977 kb/s, 29.97 fps, 1000k tbr, 1000k tbn
[AVFormatContext @ 00000198adc03380] Unable to choose an output format for 'C:\Users\pilip\Desktop\projects\python\very'; use a standard extension for the filename or specify the format manually.
[out#0 @ 00000198adc04d40] Error initializing the muxer for C:\Users\pilip\Desktop\projects\python\very: Invalid argument
Error opening output file C:\Users\pilip\Desktop\projects\python\very.
Error opening output files: Invalid argument
im trying to make a screen recording thing with ffmpeg but no matter what i do i get an error, anyone able to fix?
ill try to get the owner to give him the highest role
even tho it kinda already has it but ok
@stoic tusk So that I understand correctly, you are writing about your problem from before many ours abour roles?
@upbeat mason error doesn't tell you anything "Error initializing the muxer for C:\Users\pilip\Desktop\projects\python\very: Invalid argument"?
uh yes
yeah but what invalid argument its all correct
i've retried the code multiple times
@viscid hornet do you maybe know anything abt ffmpeg?
alr it didnt print out the "role added", it's smth that stops him from assigning roles
@upbeat mason If you understand it simply, you run a program by giving the wrong arguments
but im not, atleast i dont think so
i've tried out multiple different types of code for it
this is what i have rn for whats being given in args:
os.system(f'ffmpeg -y -f gdigrab -t {duration} -i desktop {file_path}')
nope ❌
any way you can possibly help me
do they already have the role?
@upbeat mason maybe try sth like this ffmpeg -probesize 10M -i input ...
dont think so
should i put that before the -y
cause its free
don't know
no
how 😭
limited edition
@upbeat mason Have you tried adding this argument? xD
im getting this now so its something
changed it to ```py
os.system(f'ffmpeg -probesize 10M -i -y -f gdigrab -t {duration} -i desktop {file_path}')
think i fixed it lemme see
@upbeat mason isn't "-i" a input file you need to put?
idk shit about ffmpeg so
im looking at the ffmpeg docs rn anyways
chill and good luck xD
@upbeat mason if using -f gdigrab don't you need -framerate also? im think about it
yes, try 30
why the hell is it 54 years 😢
isnt 30 too much
is that dutch or something
@leaden olive you need to as the bot xD
what? hah
germany
close enough
did nothing
@upbeat mason its framerate you trying to grab, try 10 for start
😦
os.system(f'ffmpeg -y -f gdigrab -probesize 10M -framerate 10 -t {duration} -i desktop {file_path}')
@leaden olive sorry it was a joke xD
maybe its something to do with the use a standard extension for the filename or specify the format manually
@upbeat mason well im thinking...
haahha all fine
@upbeat mason the manual says
-y (global)
Overwrite output files without asking.
and next they put some examples
ffmpeg -i foo.mov -c:v libxvid -pass 1 -an -f rawvideo -y NUL
ffmpeg -i foo.mov -c:v libxvid -pass 1 -an -f rawvideo -y /dev/null
so maybe try put a NUL after -y
LOL i fixed it
and it was the simpliest fix ever
thanks to some guy in another python help channel
what was causing the problem? tell me please
basically the parenting folders had spaces in them (thats why the path had just cut off at "very") so i just quickly renamed them to a and b (to remove spaces) and its fixed
idk how i didnt think of it but honestly atleast it works now
lol how did this guy find this error? had more information from you?
just this itself already made me realise my possible mistake
thanks still for trying to help lmao
well never mind anyway, good that it works
yeah
i still gotta make alot of changes to the command
its got some bugs but the recording works so
@upbeat mason good to know, thanks
can I run 2 bots or more on 1 code?
and if I edited the code both of them will get edited?
why
dont run multiple bots at once. we already told you why its not advisable
It's possible?
its possible to drive a car on one wheel. in what world would that be reasonable? 🤷🏽♂️
I think it is possible if you use requests and the discord API
mfw “bot1 = …, bot2 = …, …” then “for bot in bots: bot.run(…)”
but dont do that because you gain literally nothing and it just wastes your RAM 🙏🏽
What could I save in a folder called utils?
@viscid hornet
idfk. utilities?
yeah folder named utilities
put whatever you want in there, idk
@viscid hornet
Could you give me an explanation of how selfbots work or rather how they make them?
!rule tod
The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
but im pretty sure its just using some API requests bs like dpy but for a user account instead of a bot account
yeah, with websockets, requests, asyncio, api discord, and for the heartbeart websocket
Yo just wanted to say appreciate the vs code tip, been easy lately
U got any places I could check for games like tic tac toe, rock paper scissors etc
I have a question with the event cogs, are all the events in 1 single cog and 1 cog for 1 event?
That's confusing 
hi i was just wondering what i did wrong here
python3 : The term 'python3' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
- python3 main.py
-
+ CategoryInfo : ObjectNotFound: (python3:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
what does py -0 return?
-V:3.12 * Python 3.12 (64-bit)
alright. whenever you see python3 just replace it with py and you should be good
to run a file named main.py: py main.py
oh tysm
what was the difference between python3 and py
Traceback (most recent call last):
File "C:\Users\C\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\C\Documents\Discord Bot\main.py", line 14, in hello
await ctx.sent ("Hello.")
^^^^^^^^
AttributeError: 'Context' object has no attribute 'sent'. Did you mean: 'send'?
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\C\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\C\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\C\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'sent'
😭
ctx.send
is ctx.send
instead of ctx.sent
i think i changed it but its still giving me the same error
try to rerun the file and send the updated traceback
oh nevermind
👍
thanks it worked
makes it easier to read for those helping
alright ill do that next time
@viscid hornet I have a question with the event cogs, are all the events in 1 single cog or 1 cog for 1 event?
I recommend that each cog have related events.
One cog for connection events, another cog for command events, ....
when can bot.fetch_channel raise Forbidden: Missing access?
I know its "you do not have permission to fetch this channel" but what permission do i need?
If I'm not wrong it might be the view_channels permission but i might be wrong
You need a requirements.txt file: pip freeze > requirements.txt
Oh
You also use bot-hosting.net
I also use it 🙂
It's cool right 👍
You haven't installed discord yet in there
I am familiar with this software
I can handle it from here
@tawdry vector Go to Startup and scroll down till you find a option called additional python packages
There you write discord
And then you Start then your code must work...
It must work unless there is error in the actual code itself...
Thx
no problem man. 👍🏽
heres tictactoe. lemme get my connect four stuff rq
on here, just take connect four and rps. i forgot what the check wins stuff was
oh wait you want the check wins stuff too
i need to update the repo with that 🤦🏽♂️
I needed a requirement.txt a guy said
And i tried and it worked
Yes but that doesn't work for this
My bot doesn't have it but still it works
Im making my hybrid command but they slash commands doesn't up of the hybrid but it works for regular commands
No
Did you sync the app_commands.CommandTree?
this could be a reason of slash commands not showing up 
async def setup(bot: commands.Bot):
await bot.add_cog(channel(bot))
await app_commands.commandtree.sync()
this isn't where you sync
not like this
It says it app commands don't have a attribute command tree
Then where?
your bot has an attribute "tree" and that attribute has a sync method
https://about.abstractumbra.dev/discord.py/2023/01/29/sync-command-example.html
create a separate command for syncing the tree
I curated and created a pretty full-featured command for syncing your CommandTree, you can see it here:
So tree instead of command tree?
!d discord.ext.commands.Bot.tree.sync
No documentation found for the requested symbol.
…
!d discord.ext.commands.Bot.tree
property tree```
The command tree responsible for handling the application commands in this bot.
New in version 2.0.
you stinky
please can i have nitro 😔🙏🏽
no, use the bot tree
its because its not a static method
bot .tree.sync?
YES
just await it and call it
^^
this is the right place to do it?

Do you guys have any tips how I could improve this function?
edit the message itself instead of sending a new one, or make the new message an ephemeral and make the other message’s embed green or red based on the result
i think the second would be really good
How long does it take to sync discord slash commands using hybrid commands?
should be instant
refresh your discord client
How
Oh you meant fresh right?
I did it and it worked
Thanks for the help 😄
cool
hm
ive been using bot-hosting.net for like 3 years now and had a friend in their staff team 🗣️
Noice
!paste
Someone please help me with this
https://paste.pythondiscord.com/IFIA
Try running it and a huge error pops up
How can I fix it?
@solar path Here is the error
!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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
use paste service for big text
good luck with the help 👍
Bruh
asked you to post error like 5 times , you are still not doing it 🤷♂️
anyway, i gotta go , good luck
@viscid hornet
How do I make a command that, through requests and a proxy, sends a message to a channel
a bot command that sends a message in a channel?
and request proxy
how about just dont??
its saying apparently you cant have reactions for some reason?
I think so...
!d discord.Message.add_reaction - this tells u why it raises Forbidden
await add_reaction(emoji, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji).
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) to do this. If nobody else has reacted to the message using this emoji, [`add_reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.add_reactions) is required.
Changed in version 2.0: `emoji` parameter is now positional-only.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) instead of `InvalidArgument`.
I want to learn to use proxies and the requests library for when my bot is more advanced and has many requests
But I'm kinda new to dpy like for 3 months maybe?
So I don't have any experience with this
you're missing add_reactions permission in the channel
just a suggestion, use buttons instead of reactions
it will be easier to work with
requests is blocking, number 1. number 2, what possible use case could you have for using proxies in the context of a discord bot?
was just about to say this ^^
Without proxies, how can big bots make too many requests and no cooldown?
its called not fucking with the ratelimits 👍
different processes have different ratelimits. sending a shit ton of messages in one channel will arise quite quickly, but sending one or two mesasges across multiple channels is far less strain on the API
If y'all wondering the code
https://paste.pythondiscord.com/IFIA
impossible
damn it
very possible.
What can I do
For example, the bot called antilink makes too many requests to delete messages and is on 10k servers and has no delays when deleting links
How do you explain that to me?
Guys is there anyone developing discord bots for leagues?
I gave it some extra permissions and it's working now 😄 thanks 👍 @viscid hornet
because the message is before 2 weeks. discord lets you bulk delete messages <2wks in age. after that, they have to be deleted individually, and you have to make an API call for each message
what do you mean by leagues?
no probs. i suspected something was missing 👍
ok
also something else i should mention is that proxies and the requests lib will get you nowhere in terms of avoiding ratelimits. discord.py and all its forks and rewrites use those methods. if they're using them (at their full capacity for such a project) and they're getting ratelimits, you defo wont be able to skip them by writing similar code yourself
guys How can I improve this code? ```py
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
embed = discord.Embed(title="Comando no encontrado", description=f"{emoji_warning} El comando {ctx.invoked_with} no se encuentra en mi codigo.", color=color_sew)
await ctx.author.send(embed=embed)
elif isinstance(error, commands.CommandOnCooldown):
embed = discord.Embed(title="Cooldown", description=f"{emoji_warning} Debes esperar `{round(error.retry_after)}` segundos antes de usar este comando nuevamente.", color=color_sew)
await ctx.author.send(embed=embed)
elif isinstance(error, commands.CommandError):
embed = discord.Embed(title="Error inesperado", description=f"{emoji_warning} Ha ocurrido un error ejecutando el comando. ```{error}```", color=color_sew)
await ctx.author.send(embed=embed)```
add this: py else: raise error
otherwise you'll eat all other errors in the future
axo can you dm me?
why?
i dont think theres any
??
if you want help, you're literally in the place for it
Don't need to make a new embed each time, make one at the start and just edit the descriptions inside each if statement
Raise errors u aren't handling
What if the bot can't message the user?
mfw the error handler causes errors
"ferb i discovered recursio- 💣 "
thx
no recursion here unfortunately because it only handles command errors
click on general and this is immediately what comes in
💀 I'd delete that image before a mod spawns
you realise you're doing the same thing by posting a screenshot of the same, right 💀
that too without blurring the link and image LMAO
Atleast blur the link 
@viscid hornet
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
embed = discord.Embed(title="Comando no encontrado", description=f"{emoji_warning} El comando `{ctx.invoked_with}` no se encuentra en mi codigo.", color=color_sew)
await ctx.author.send(embed=embed)
elif isinstance(error, commands.CommandOnCooldown):
embed = discord.Embed(title="Cooldown", description=f"{emoji_warning} Debes esperar `{round(error.retry_after)}` segundos antes de usar este comando nuevamente.", color=color_sew)
await ctx.author.send(embed=embed)
elif isinstance(error, commands.CommandError):
embed = discord.Embed(title="Error inesperado", description=f"{emoji_warning} Ha ocurrido un error ejecutando el comando. {error}", color=color_sew)
await ctx.author.send(embed=embed)
elif isinstance(error, discord.Forbidden):
embed = discord.Embed(title="Mensajes directos", description=f"{emoji_warning} Activa tus mensajes directos para recibir comunicaciones del bot.", color=color_sew)
message = await ctx.channel.send(embed=embed)
await asyncio.sleep(7)
await message.delete()
else:
raise error```
oh really?
!d discord.Message.delete
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages).
Changed in version 1.1: Added the new `delay` keyword-only parameter.
?
see the delay kwarg?, you can use that instead of asyncio.sleep
my bad gang 🗣️

oh ok thx
@viscid hornet It is not sending the error message when the user has dm closed
:)
@slim bloom
what?
read the message
skibidi dop dop?
🤦🏽♂️
Regarding the above, what could I add when the user has DM closed?
@viscid hornet
idk. send a message in the channel saying dms are closed?
If anyone is keen on making a new Discord bot that everyone (including myself) will use, here's one: #python-discussion message
Let me know if its made 
"everyone" -> Meanwhile people just set their time zone in bio
your handler is only for command errors by the way
that sounds pretty easy ngl. lemme try something
oh yay
quick question: what behaviour should the bot have?
- i was thinking on every message sent, it adds a little embed underneath saying times for the different people in the chats
Embedding on every message is spammy. Why not in intervals of active chat? Say in every 15 min?
If chat is inactive, it will pause as well. When chat starts again, then show the new embed
ok i'll do every 15 minutes, and let you customise the time
or, hold on
Instead of just embedding in any message, why not embed on notification?
So if I @ someone, then it shows the embedding but only so in every 15 min when the @ someone is used
So a cooldown to @ that person and not be spammy at least for 15 min
ok so:
- person pings another user
- embed displays their time and your time (if they have them added. if not - prompt them)
- cooldown for 15 minutes on that user
- repeat
and then to define an active chat, i'll say 20 messages in a minute
yeah thats the gist of it
So at least the bot doesn't get rate limited or something
no like how to make it work lmao
lol take your time
how
in on_message event?
no?
no?
in case the error messages cannot be sent to the dm :v
use a try except statement while messaging the author

i was thinking about that but he mentioned in the context of a command error handler which threw me off from giving that solution
idk
Has InteractionResponse.send_modal() been depreciated? The following:
await interaction.response.send_modal(ContactModal())
yields "Unknown Integration" instead of the usual "Application did not respond"
can you send the code
integration or interaction?
and no its not been deprecated
!d discord.InteractionResponse.send_modal
await send_modal(modal, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a modal.
what does the console say?
It doesn't throw any exceptions
how come it has an activity section then?
Not sure, it does that for failed interactions too
i mean it shouldnt do because thats something else
have you tried resyncing?
i reproduced the thing
Yeah, but I just found out that it changes from Unknown Integration to The application did not respond, after I leave the TextChannel and revisit it, so there must be some bug but I can't find it
Yes, same error
sounds like a discord issue
i have no idea how you managed to get an activity in your bot tho 😭
It's a discord bug but it shouldn't affect the command
when i enter ANYTHING besides that id or anything that is shorter than this id it accepts but whenever i enter a normal id in there i keep getting this thing. why and is this about my code or is it about discord
send your code (mention reply me)
heyo, so idk how i would proceed with this but how would i make the update_type say "Multiple" when multiple changes are saved in one go (e.g., name, topic, NSFW, etc.)? the example photo is what i'm trying to make it look like but for channels. if there aren't multiple changes saved in one go then everything else should work the same as before. idk how i would implement it
here's my code: https://pastes.dev/kE3sW4s1In
server_id: int --> server_id: str; catch a ValueError when you try to convert it to an integer using int(server_id).
See: https://github.com/ibnaleem/amiri/blob/main/cogs/utility.py#L122-L136
but im not getting any error it just says "input a valid integer"
After changing your code to the above, try running it and see if the error persists
still the same thing is happening, to make the code work or do something this thing needs to be sended after that the code you provided could work
why not type hint to discord.Guild? (question btw im not sure if thats possible)
Guild is not a supported type by slash commands, especially given that slash commands really are meant to execute within the context of one guild and not multiple
letting people in guild A look up stuff about guild B could be considered an invasion of privacy (for things not covered by the public guild preview)
ah thanks for the insight i never thought about it like that
then i guess this 'workaround' is good
It's a discord "bug"
Their js handler doesn't support "big int" numbers, anything greater than an unsigned 32 bit integer isn't valid
oh, so thats why its typehinted to str
Yes, sadly
yo
got an issue with hikari/lightbulb
@info_plugin.command
@lightbulb.app_command_permissions(dm_enabled=False)
@lightbulb.option("email", "Your email", str, required=True)
@lightbulb.option("password", "Your password", str, required=True)
@lightbulb.command("login", "Log your account into the bot", auto_defer=True, pass_options=True)
@lightbulb.implements(lightbulb.SlashCommand)
async def userinfo(ctx: lightbulb.SlashContext, email: str, password: str):
# my code
parameters arent in order
tried changing option decorators order
The order goes from bottom to top
yeah i fixed it
So you want to put email at the bottom and password at the top
had to change a parameter name and change it back for discord to change it
Skibidi toilet
what does that mean
What does what mean
i meant what is a 32 bit integer
The number 2,147,483,647 is the eighth Mersenne prime, equal to 231 − 1. It is one of only four known double Mersenne primes.
The primality of this number was proven by Leonhard Euler, who reported the proof in a letter to Daniel Bernoulli written in 1772. Euler used trial division, improving on Pietro Cataldi's method, so that at most 372 divis...
dude literally goin 🤨
why is this causing the problem that im having i dont understand 😭
i need help with my discord bot liek the bot works perfectly fine no error what i tougth the bot when i type the command {with the prefix} and the other nececerry stuff it just doesnt work
so would be nice if someon could help me out
Code?
modals
oh
!d discord.ui.Modal
class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.
This object must be inherited to create a modal popup window within discord.
New in version 2.0.
Examples...
wait there is no actual way to get last member message?
Not efficiently
not through the API, so you'll need to track message events as they come in and keep a record of their last messages
hey, I have been working on a small discord bot using Python and I am encountering a very strange bug, discord.py for whatever reason is not able to tell what the contents of a message is when a user sends the message. I have been working to fix this and find ways around it for a very long time now and am very confused, can anyone help?
class GameButton(discord.ui.Button):
def __init__(self, ticket_channel):
super().__init__(label="Game", style=discord.ButtonStyle.grey, custom_id="confirm")
self.ticket_channel = ticket_channel
async def callback(self, interaction: discord.Interaction):
options = [
discord.SelectOption(label="Game", description="Game"),
discord.SelectOption(label="Game", description="Game"),
discord.SelectOption(label="Game", description="Game"),
discord.SelectOption(label="Game", description="Game"),
discord.SelectOption(label="Game", description="Game"),
discord.SelectOption(label="Game", description="Game")
]
select = discord.ui.Select(placeholder="Select Game", options=options)
select_view = discord.ui.View()
select_view.add_item(select)
embed = discord.Embed(
title='Select Game',
description='Please select your Game.',
color=discord.Color.green()
)
await interaction.response.send_message(embed=embed, view=select_view)
self.select_view = select_view
async def select_callback(select, interaction: discord.Interaction):
await interaction.response.send_message(f"Awesome! I like {select.values[0]} too!")```
anyone can help why select_callback wont work? idk what to do
That's just making a floating function named select_callback, nothing is going to call that
You should probably be subclassing ui.View and implementing the select in it
You probably aren't requesting the message_content intent
Could you give me an example if it's not too much to ask please?Could you give me an example if it's not too much to ask please?
hmm can I have an example of how I can do that?
taken from dpy:
from discord import ui
class Questionnaire(ui.Modal, title='Questionnaire Response'):
name = ui.TextInput(label='Name')
answer = ui.TextInput(label='Answer', style=discord.TextStyle.paragraph)
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message(f'Thanks for your response, {self.name}!', ephemeral=True)
- [ Documentation ]
- [ Detailed example ]
Anyone?
cant you only make one change?
!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.
@viscid hornet
code: ```py
class Questionnaire(ui.Modal, title='Questionnaire Response'):
name = ui.TextInput(label='Name')
answer = ui.TextInput(label='Answer', style=discord.TextStyle.paragraph)
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message(f'Thanks for your response, {self.name}!', ephemeral=True)
@bot.command()
async def questionnaire(ctx):
await ctx.send('Please provide your response:', view=Questionnaire())```
error: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In components.0.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8). In components.1.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
You're trying to send a modal as a view
wym
You also can only send a modal in response to an interaction, you can't just send it to a context
how fix?
cant you only update one role? also i feel like thats deprecated by an audit log
you can only send it in response to an interaction, ie. interaction.response.send_modal()
its not a view, so you cant tell the message “hey, this is a view” because the message has eyes and it can see that its not a view.
no im not talking about the role. that was an example picture. im trying to do the "Multiple" update_type for channel updates
if you want to still use your feature, how many updates can you make to a channel? what do you mean by “multiple” updates?
and why not just use the audit log?
like for example, if i change the name, nsfw, and channel topic in one go
im asking in what ways could i implement it
doesnt this just get you rate limited?
code?
i wouldnt think so
!d discord.InteractionResponse.send_modal
await send_modal(modal, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a modal.
class PaymentSelectView(discord.ui.View):
def __init__(self, ticket_channel):
super().__init__()
self.ticket_channel = ticket_channel
options = [
discord.SelectOption(label="Game", description="Game"),
discord.SelectOption(label="Game", description="Game"),
discord.SelectOption(label="Game", description="Game"),
discord.SelectOption(label="Game", description="Game"),
discord.SelectOption(label="Game", description="Game"),
discord.SelectOption(label="Game", description="Game")
]
select = discord.ui.Select(placeholder="Select Game", options=options)
select.callback = self.select_callback
self.add_item(select)
async def select_callback(self, select, interaction: discord.Interaction):
await interaction.response.send_message(f"Selected game: {select.values[0]}")
class ConfirmButton(discord.ui.Button):
def __init__(self, ticket_channel):
super().__init__(label="Confirm", style=discord.ButtonStyle.grey, custom_id="confirm")
self.ticket_channel = ticket_channel
async def callback(self, interaction: discord.Interaction):
view = PaymentSelectView(self.ticket_channel)
await interaction.response.send_message("Selectt", view=view)
ticket_channel = None
confirm_button = ConfirmButton(ticket_channel)```
i did this and i get this error -
Traceback (most recent call last):
File "/home/runner/pln-scma/.pythonlibs/lib/python3.10/site-packages/discord/ui/view.py", line 427, in _scheduled_task
await item.callback(interaction)
TypeError: PaymentSelectView.select_callback() missing 1 required positional argument: 'interaction'
Idk why
|| (read the error) ||
also you should be subclassing modal as well. it’ll make things way easier
if i am looking at right line then it already has it?
async def select_callback(self, select, interaction: discord.Interaction):
hello
selects dont take those args…?
wait
huh
ngl i feel like the issue would be solved if you just subclass the select as well
sorry mate i had pain in the a$$ coming to this part and it still aint working
i dont know how to subclass select as well ngl
bc i dont understand how to do it rn
this is finish line i js need to code select menu to send embeds
but can't manage to code it send this easy message at first
pls help
do it in the same way you did with ui.View
You shouldn't be stapling callbacks onto generic selects
^^
either a) use the @ui.select decorator or b) subclass Select
What is a good starting place to make a script for this client?
what client?
Discord api for Python
ok
can someone help?
class TicketView(View):
def init(self):
super().init()
self.add_item(Button(label="General", style=ButtonStyle.green, custom_id="general"))
self.add_item(Button(label="IA", style=ButtonStyle.green, custom_id="ia"))
self.add_item(Button(label="Management", style=ButtonStyle.green, custom_id="management"))
async def interaction_check(self, interaction: discord.Interaction) -> bool:
return interaction.user.id == interaction.message.author.id
@discord.ui.button(label="General", style=discord.ButtonStyle.green, custom_id="general")
async def general_button(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message("You've selected General ticket.")
@discord.ui.button(label="IA", style=discord.ButtonStyle.green, custom_id="ia")
async def ia_button(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message("You've selected IA ticket.")
@discord.ui.button(label="Management", style=discord.ButtonStyle.green, custom_id="management")
async def management_button(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message("You've selected Management ticket.")
@bot.event
async def on_ready():
channel = bot.get_channel(1216429762604564591)
embed = Embed(title="Open a Ticket", description="Select the type of ticket you want to open.")
view = TicketView()
await channel.send(embed=embed, view=view)
idk what i did wrong
2024-05-06 00:03:32 ERROR discord.client Ignoring exception in on_ready
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/home/container/bot.py", line 44, in on_ready
view = TicketView()
^^^^^^^^^^^^
File "/home/container/bot.py", line 21, in init
self.add_item(Button(label="General", style=ButtonStyle.green, custom_id="general"))
^^^^^^^^^^^
NameError: name 'ButtonStyle' is not defined
did you import the discord.ButtonStyle module?
idk how
when i tried to import it, it said it wasnt defined
from discord.ui import Button, View, ButtonStyle
like that
try with from discord import ButtonStyle
alr
lets see if this works
okay now that worked now its showing 2024-05-06 00:11:25 ERROR discord.client Ignoring exception in on_ready
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/home/container/bot.py", line 46, in on_ready
await channel.send(embed=embed, view=view)
File "/home/container/.local/lib/python3.11/site-packages/discord/abc.py", line 1561, in send
data = await state.http.send_message(channel.id, params=params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/http.py", line 745, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.3.custom_id: Component custom id cannot be duplicated
In components.0.components.4.custom_id: Component custom id cannot be duplicated
In components.1.components.0.custom_id: Component custom id cannot be duplicated
buttons have a duplicate or repeated ID, check that each component has its own ID
they dont, they all have different id's
well
class TicketView(View):
def init(self):
super().init()
self.add_item(Button(label="General", style=ButtonStyle.green, custom_id="general"))
self.add_item(Button(label="IA", style=ButtonStyle.green, custom_id="ia"))
self.add_item(Button(label="Management", style=ButtonStyle.green, custom_id="management"))
async def interaction_check(self, interaction: discord.Interaction) -> bool:
return interaction.user.id == interaction.message.author.id
@discord.ui.button(label="General", style=discord.ButtonStyle.green, custom_id="general")
async def general_button(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message("You've selected General ticket.")
@discord.ui.button(label="IA", style=discord.ButtonStyle.green, custom_id="ia")
async def ia_button(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message("You've selected IA ticket.")
@discord.ui.button(label="Management", style=discord.ButtonStyle.green, custom_id="management")
async def management_button(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message("You've selected Management ticket.")
i mean they all have different ids am i wrong?
when you define a view class with buttons with the @discord.ui.button decorator they are added automatically. Delete them from the __init__ method.
alright

