#discord-bots

1 messages · Page 361 of 1

distant fulcrum
#

It worked thank you

slate swan
#

the code repeatability is huge

viscid hornet
dawn lake
viscid hornet
#

why

slate swan
dawn lake
viscid hornet
dawn lake
#

It's a pain to create a command handler for newbies like meh

viscid hornet
dawn lake
#

Even if you have good knowledge

dawn lake
viscid hornet
dawn lake
viscid hornet
#

never heard of that

dawn lake
#

Ok tell me

#

Where you host your bot?

slate swan
#

maybe he just means a command

dawn lake
#

Bruh

viscid hornet
#

where else 😭

slate swan
dawn lake
#

The common that you run to start the bot is command handler

#

Like

slate swan
#

a terminal?

dawn lake
#

python3 bot.py

slate swan
dawn lake
viscid hornet
slate swan
#

at least stuff i made is not Like

slate swan
dawn lake
#

Nothing wrong bro was asking what is command handler

viscid hornet
#

@slate swan

slate swan
dawn lake
#

d.py wiki is also confusing tho

viscid hornet
#

wait how is running your code a dpy issue? 💀

slate swan
dawn lake
slate swan
#

i aint getting what you have problems with

dawn lake
viscid hornet
#

demnstrate an example

timber dragon
#

Their status says it all tbh

slate swan
#

soheab arrived :stab:

upbeat mason
#

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

quick gust
upbeat mason
quick gust
#

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

viscid hornet
#

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

viscid hornet
quick gust
#

you can switch on_ready with setup_hook is what they said, so no

viscid hornet
#

but only called once

#

as opposed to on ready which can be called multiple times

upbeat mason
#

ohh

timber dragon
#

No it's not

viscid hornet
#

so instead of reloading all your commands 2 or 3 times, you only need to do it once

#

(as an oversimplification)

timber dragon
#

om_ready is an actual even from discord for when everything is ready like cache etc

viscid hornet
upbeat mason
#

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?

viscid hornet
#

ohh and setup hook is doy

timber dragon
#

setup_hook is called by dpy after login

viscid hornet
upbeat mason
#

discord.ext.commands.errors.ExtensionFailed: Extension 'commands.ping' raised an error: TypeError: object NoneType can't be used in 'await' expression

timber dragon
#

You should subclass and override the method

viscid hornet
timber dragon
#

It's not an event

upbeat mason
viscid hornet
#

he just pulled a “technically”

upbeat mason
#

somehow still ended up giving me an error though

timber dragon
#

Check your extensions

upbeat mason
#

it is isnt it

timber dragon
timber dragon
quick gust
upbeat mason
#

oh wait yeah it isnt async

timber dragon
#

setup func must be async

#

Are those messages duplicated for anyone else?

upbeat mason
#

bruh now this RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited bot.add_cog(Ping(bot))

quick gust
#

yeah your messages duplicated

timber dragon
#

add_cog is async, await it

timber dragon
upbeat mason
#

im so dumb lmao alr

quick gust
#

the error pretty much tells u what to do here

upbeat mason
#

finally fixed it, thanks guys i was so confused

upbeat mason
quick gust
#

yes, always a good idea

stoic tusk
#

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 )

upbeat mason
#

im pretty sure we cant directly give you the code but only help you with it?

#

im not sure though

stoic tusk
fiery girder
#

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

upbeat mason
#

in the simpliest way possible ^

fiery girder
#

yea

stoic tusk
quick gust
#
@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

stoic tusk
# fiery girder you can send it here
@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.")
fiery girder
#

seems about right

upbeat mason
#

what are the downsides of using all intents? (discord.Intents.all())?

stoic tusk
#

should be i think

quick gust
fiery girder
fiery girder
upbeat mason
#

alr

upbeat mason
#

it should do

stoic tusk
#

let me see

fiery girder
#

discord.Member not discord.user

quick gust
#

they have discord.Member only?

fiery girder
#

Member is a Guild User subclass

quick gust
fiery girder
#

member has the addroles not the user so

quick gust
#

yeah and the code they sent has discord.Member... so they don't need to change it

fiery girder
#

oh

upbeat mason
#

yeah

fiery girder
#

i taught i read User

#

my bad

upbeat mason
#

lmao

fiery girder
#

ok back to making minecraft in discord

upbeat mason
#

minecraft in discord

fiery girder
#

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

upbeat mason
#

wondering rn how you're going to implement fighting and stuff

fiery girder
#

same lol

#

fighting is hard

fiery girder
#

also got enchantment

#

and Potions

#

and Food

stoic tusk
#

alr it works, thanks guys

#

had to censore some naughty names

upbeat mason
young dagger
#

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
upbeat mason
young dagger
#

await interaction.response.edit_message(content=f"Link '{self.link}' has been whitelisted.", view=None) AttributeError: 'Button' object has no attribute 'response'

timber dragon
#

Switch params

young dagger
wanton current
#

flip the interaction and buttons args

fiery girder
upbeat mason
#

alr

timber dragon
#

self, interaction, button

fiery girder
#

the interaction comes first

timber dragon
#

self is always first in methods

quick gust
young dagger
#

How can I remove the button after whitelisting the link?

viscid hornet
dim valve
unkempt canyonBOT
#

remove_item(item)```
Removes an item from the view.

This function returns the class instance to allow for fluent-style chaining.
young dagger
wanton current
#

you need to update the message with the new view

viscid hornet
#

you won this time cat person

young dagger
# viscid hornet need to update the view

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)```
viscid hornet
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

After pasting your code, save it by clicking the 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.

viscid hornet
#

put it in here cuz im on phone

dim valve
#

@young dagger hi

#

Can you help me?

viscid hornet
dim valve
naive briar
#

Of course it won't remove the button

viscid hornet
#

oh yeah

#

🤦🏽‍♂️

candid geyser
#

@dim valve whats in the requirements file?

#

are u running it in a docker container?

young dagger
naive briar
#

Sure

young dagger
#

To remove the view = button

#

Thanks

dim valve
#

I want to run using hosting

young dagger
# naive briar Sure

Do you like my method to whitelist links? Or do you have any other suggestions?

candid geyser
#

and the requirements file?

dim valve
#

@candid geyser wait

#

but my file use Indonesian

viscid hornet
# naive briar Sure

there’ll be inter failed errors if they dont defer before the first option

young dagger
viscid hornet
unkempt canyonBOT
#

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.
dim valve
#

File deleted by @unkempt canyon

young dagger
viscid hornet
naive briar
#

It may do the same thing, but they're not necessarily the same

viscid hornet
#
  1. you arent responding to the interaction, which you have to do
#

no. 2 is the key thing

naive briar
#

It looks like they're responding to the interaction to me, but okay

viscid hornet
#

like editing the message itself, which doesnt count as a response

naive briar
spice warren
timber dragon
#

Oh yeah

#

but it's not recommended to do that

spice warren
#

Yeah

viscid hornet
spice warren
#

Interaction.edit_original_response etc is part of it
This just calls regular Message.edit

viscid hornet
timber dragon
#

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

candid geyser
young dagger
#

or am I missing something?

viscid hornet
#

i thought you wanted to edit the original message with the new embed

fiery girder
#

lol

naive briar
#

🫠

stoic tusk
#

any idea of how to make a command that will show all roles names and their IDs?

upbeat otter
wanton current
#

user is misleading since it has to be a member

stoic tusk
#

not member

upbeat otter
#

!d discord.Guild.roles

unkempt canyonBOT
#

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.
upbeat otter
#

@wanton current

wanton current
#

what

upbeat otter
#

replace it with guild instance

stoic tusk
#

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 )

viscid hornet
stoic tusk
# viscid hornet 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

turbid condor
#

are you recieving any error in the terminal?

stoic tusk
turbid condor
#

if you have a global error handler disable it and then check

stoic tusk
#

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

stoic tusk
# turbid condor if you have a global error handler disable it and then check

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

turbid condor
#

what about intents?

stoic tusk
turbid condor
stoic tusk
#
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"])
turbid condor
#

looks ok

#

!d discord.Member.add_roles

unkempt canyonBOT
#

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

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)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.
stoic tusk
# turbid condor looks ok

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 )

turbid condor
#

let me check the docs

stoic tusk
#

alr

turbid condor
#

and then see

#

or can try using get_role() on the the role_id first and passing it to add_role()

stoic tusk
#

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

turbid condor
#

also make sure that your bot role is higher in hieararchy then the role you are trying to assign

turbid condor
#

!d discord.Guild.get_role

unkempt canyonBOT
#

get_role(role_id, /)```
Returns a role with the given ID.

Changed in version 2.0: `role_id` parameter is now positional-only.
turbid condor
#

use this to get the role and pass it to add_role function

#

you can Guild object by using ctx.guild

stoic tusk
#

ill see

stoic tusk
# turbid condor use this to get the role and pass it to add_role function
@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?

turbid condor
#

role = guild.get_role(int(role_id))

turbid condor
#

that's just how discord works

stoic tusk
#

oh so now it's fixed?

turbid condor
#

don't know you have to check it and see

stoic tusk
#

alr

stoic tusk
#

I don't get what could go wrong here

turbid condor
stoic tusk
#

alr

stoic tusk
# turbid condor can you add checkpoint's in the command like printing statements in there after ...
@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?

turbid condor
#

add one at the start of function definition and one more after the first if statement

stoic tusk
#

@turbid condor apparently it's not printing anything at any point

turbid condor
# stoic tusk ```py @commands.command() async def role(self, ctx, user: discord.Member, role_i...
@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")
turbid condor
stoic tusk
turbid condor
#

then check if this command isn't outside the last class

stoic tusk
#

i removed self

turbid condor
stoic tusk
turbid condor
#

can you upload whole file code?

#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

After pasting your code, save it by clicking the 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.

stoic tusk
#

one sec

turbid condor
#

weird i don't see any issue

#

well i'm out of ideas you might need to w8 for someone else

stoic tusk
#

np

agile cobalt
#

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?

unkempt canyonBOT
#
Certainly not.

No documentation found for the requested symbol.

viscid hornet
#
@bot.listen('on_message')
async def yourmsglistener(message: Message):
    pass```
#

you want this ⬆️

ivory falcon
timber dragon
slim bloom
#

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]}")```
wanton current
#

cogs != extensions

slim bloom
# viscid hornet already done
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()```
#

?

ivory falcon
slim bloom
timber dragon
viscid hornet
ivory falcon
timber dragon
#

You're dming user

#

What's wrong with that?

slim bloom
# viscid hornet charge?
/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```
timber dragon
#

Make sure to also await add_cog

ivory falcon
timber dragon
#

Ic

slim bloom
timber dragon
# ivory falcon

You can access your bot from interaction.client and use get_user on that

timber dragon
slim bloom
#
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))

timber dragon
#

Read the warning very carefully

slim bloom
#

cogs is correct now

#

@timber dragon thanks

young dagger
#

What is the best way to detect links/domains?

viscid hornet
#

oh wait nvm

young dagger
#

urlparse?

viscid hornet
#

probs regex from what ive heard

slim bloom
slim bloom
viscid hornet
#

like if i said “are cars better with wheels than without?”

young dagger
slim bloom
viscid hornet
slim bloom
#
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

viscid hornet
viscid hornet
#

other than printing “hey there was an error”

slim bloom
viscid hornet
slim bloom
#

ah ok

strange lichen
#

@slim bloom do you have any error message?

fast osprey
#

:/

slim bloom
#

And how could I improve on_ady?

#

on_ready*

strange lichen
#

is this the whole code?

slim bloom
strange lichen
#

xD

fast osprey
#

Firstly, you understand what on_ready does and how it works. Then you put things in a more appropriate place

strange lichen
#

so explain what you have in your code and what you run because it is impossible not to have an error code

slim bloom
#

What should be in the on_ready alone?

viscid hornet
fast osprey
#

Do you understand how on_ready works? This should be an informed decision rather than randos telling you

strange lichen
#

for example

@bot.event
async def on_ready():
    print("Bot is ready")
slim bloom
#
@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)```
fast osprey
#

Do you want a print every time the bot does a routine reconnect?

fast osprey
#

Then go nuts but I have no idea why you'd care about that

strange lichen
#

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

slim bloom
strange lichen
#

try writing a bot adding the code one by one step by step

fast osprey
#

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

slim bloom
fast osprey
#

When do you want to load them?

slim bloom
strange lichen
#

I load it in the main() function

fast osprey
#

It entirely depends on what you want

strange lichen
#

exactly

fast osprey
#

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

strange lichen
#

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())
harsh orbit
#

how I can make a command to reset the bot?

wanton current
#

define "reset the bot"

harsh orbit
#

rerun the project

strange lichen
#

SIGHUP xD

#

I think it's not simple, I'm curious about the correct answer

fast osprey
#

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

slim bloom
#

@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

strange lichen
#

so what is the question?

fast osprey
#

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

slim bloom
#

@strange lichen

#

I implemented your logic, the cogs everything seems to work

slim bloom
# fast osprey What is `presence`, and do you want to start it **every time the bot does a rand...
@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())```
wanton current
#

because everyone cares about how much RAM your bot is using that it needs to be in the status

topaz steppe
#

how to run miltiple discord bot on one project?

#

and if I edited it all of them will get edited

spice seal
#

Can someone help me with this please 🙂

fast osprey
#

If you're still putting those things in on_ready, you haven't really been listening at all to what I've been saying

spice seal
#

@fast osprey can u help ig?

#

Been struggling with this for an hour

fast osprey
#

Describing what's going wrong and what you expect to happen would be a good start

spice seal
fast osprey
#

The indentation error will tell you which line it's happening on

slim bloom
#

@strange lichen i like you broo

spice seal
#

@fast osprey

shrewd apex
#

i mean it says what is wrong exactly

spice seal
#

I can't understand what to do 😭

#

I am struggling with this for a Freaking hour

#

😦 😦

shrewd apex
#

!paste the code around that

unkempt canyonBOT
#
Pasting large amounts of code

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

After pasting your code, save it by clicking the 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.

fast osprey
#

You're trying to put an event underneath an except

shrewd apex
#

^^

spice seal
#

How to fix it

fast osprey
#

Probably want to fill out that except block with whatever you want to do

slim bloom
#

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())```
spice seal
#

How can I fix this @fast osprey

fast osprey
#

You have 3 different indents one after another

spice seal
fast osprey
#

This editor is also wrapping your lines weirdly

spice seal
#

So how to fix this @fast osprey

fast osprey
#

Don't have to keep pinging me

spice seal
#

Ohk sorry mb

fast osprey
#

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

spice seal
#

I am but my braincells don't work at night so if you can help me it's good

fast osprey
#

Do you see how your if not 2 line is completely unaligned with all of the lines above it?

slim bloom
#

@fast osprey

quick gust
#

You should probably ask the question instead of just pinging them

spice seal
fast osprey
#

that line is not aligned with any of the lines above it within the function

slim bloom
#

I have a question, how can I avoid data breaches and performance problems and errors that have to do with the db?

#

@fast osprey

spice seal
fast osprey
#

That's an extremely broad question lol

wanton current
#

step 1. sanitize input

slim bloom
#

sqite3

#

sqlite3*

strange lichen
#

@slim bloom good to hear about success, enjoy xD

fast osprey
#

Anywho yeah there's an entire channel dedicated to databases, but you probably want to pick one topic at a time

slim bloom
#

xd?

#

@unkempt canyon

#

show console

fast osprey
#

Refresh your discord client

ivory falcon
#

when loading cogs does it have to create 2 pyache files or is something wrong

ivory falcon
#

okays

stoic tusk
slim bloom
#

@viscid hornet What could I put in a utils folder?

upbeat mason
#

anyone here good with ffmpeg

stoic tusk
#

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

strange lichen
#

tell sth more about the problem

stoic tusk
#

i also checked my friend's server, every perms enabled, role hierarchy is also good, nothing unusual

strange lichen
#

ah ok so propably another server have enought libraries installed maybe

stoic tusk
#

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

upbeat mason
#
[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?

stoic tusk
#

ill try to get the owner to give him the highest role

#

even tho it kinda already has it but ok

strange lichen
#

@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"?

upbeat mason
#

i've retried the code multiple times

strange lichen
#

@stoic tusk so the same code will works on another server but not yours?

#

Weird

upbeat mason
#

@viscid hornet do you maybe know anything abt ffmpeg?

stoic tusk
#

alr it didnt print out the "role added", it's smth that stops him from assigning roles

strange lichen
#

@upbeat mason If you understand it simply, you run a program by giving the wrong arguments

upbeat mason
#

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}')
upbeat mason
viscid hornet
strange lichen
#

@upbeat mason maybe try sth like this ffmpeg -probesize 10M -i input ...

viscid hornet
upbeat mason
#

cause its free

strange lichen
#

don't know

stoic tusk
upbeat mason
viscid hornet
#

limited edition

strange lichen
#

@upbeat mason Have you tried adding this argument? xD

upbeat mason
#

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

strange lichen
#

@upbeat mason isn't "-i" a input file you need to put?

upbeat mason
#

idk shit about ffmpeg so

strange lichen
#

see in manual

#

ffmpeg [global_options] {[input_file_options] -i input_url} ...

upbeat mason
#

im looking at the ffmpeg docs rn anyways

strange lichen
#

chill and good luck xD

upbeat mason
#

yeah no im fucked

#

gave me the same issue with invalid arguments again

strange lichen
#

@upbeat mason if using -f gdigrab don't you need -framerate also? im think about it

upbeat mason
#

what like -framerate 5

#

or something

strange lichen
#

yes, try 30

leaden olive
#

why the hell is it 54 years 😢

upbeat mason
#

isnt 30 too much

upbeat mason
strange lichen
#

@leaden olive you need to as the bot xD

leaden olive
leaden olive
upbeat mason
#

close enough

upbeat mason
strange lichen
#

@upbeat mason its framerate you trying to grab, try 10 for start

strange lichen
upbeat mason
#
os.system(f'ffmpeg -y -f gdigrab -probesize 10M -framerate 10 -t {duration} -i desktop {file_path}')
strange lichen
#

@leaden olive sorry it was a joke xD

upbeat mason
strange lichen
#

@upbeat mason well im thinking...

upbeat mason
#

i removed the -f gdigrab and it just now says no such file or directory

#

im so lost

leaden olive
strange lichen
#

@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

upbeat mason
#

and it was the simpliest fix ever

#

thanks to some guy in another python help channel

strange lichen
#

what was causing the problem? tell me please

upbeat mason
#

idk how i didnt think of it but honestly atleast it works now

strange lichen
#

lol how did this guy find this error? had more information from you?

upbeat mason
#

just this itself already made me realise my possible mistake

#

thanks still for trying to help lmao

strange lichen
#

well never mind anyway, good that it works

upbeat mason
#

yeah

#

i still gotta make alot of changes to the command

#

its got some bugs but the recording works so

strange lichen
#

@upbeat mason good to know, thanks

upbeat mason
#

ended up being only like 71 lines with merging so

#

not too bad for an ffmpeg mess

harsh orbit
#

can I run 2 bots or more on 1 code?
and if I edited the code both of them will get edited?

wanton current
#

why

viscid hornet
viscid hornet
slim bloom
viscid hornet
viscid hornet
# slim bloom Alr

but dont do that because you gain literally nothing and it just wastes your RAM 🙏🏽

slim bloom
slim bloom
#

@viscid hornet

viscid hornet
slim bloom
viscid hornet
abstract granite
#

Could you give me an explanation of how selfbots work or rather how they make them?

unkempt canyonBOT
#

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.

viscid hornet
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

viscid hornet
#

but im pretty sure its just using some API requests bs like dpy but for a user account instead of a bot account

slim bloom
cedar pebble
#

I've finally done it

#

I put the if str(message.author) == xef4.0 in the wrong place

round jetty
#

U got any places I could check for games like tic tac toe, rock paper scissors etc

slim bloom
#

I have a question with the event cogs, are all the events in 1 single cog and 1 cog for 1 event?

naive briar
#

That's confusing pithink

wanton bay
#

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
wanton bay
#

-V:3.12 * Python 3.12 (64-bit)

sick birch
#

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

wanton bay
#

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'

#

😭

blazing beacon
#

ctx.send

scarlet tiger
blazing beacon
#

instead of ctx.sent

wanton bay
#

i think i changed it but its still giving me the same error

blazing beacon
#

try to rerun the file and send the updated traceback

wanton bay
#

oh nevermind

blazing beacon
#

👍

wanton bay
#

thanks it worked

blazing beacon
#

np, also next time do this

#

!code

unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

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

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

For long code samples, you can use our pastebin.

blazing beacon
#

makes it easier to read for those helping

wanton bay
#

alright ill do that next time

slim bloom
#

@viscid hornet I have a question with the event cogs, are all the events in 1 single cog or 1 cog for 1 event?

scarlet tiger
quick gust
#

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?

mossy jacinth
tawdry vector
#

Help

mossy jacinth
# tawdry vector

You need a requirements.txt file: pip freeze > requirements.txt

tawdry vector
#

Oh

spice seal
# tawdry vector

You also use bot-hosting.net
I also use it 🙂
It's cool right 👍

spice seal
spice seal
#

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

viscid hornet
viscid hornet
#

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 🤦🏽‍♂️

tawdry vector
#

And i tried and it worked

spice seal
#

My bot doesn't have it but still it works

tawdry vector
#

Might because I'm using a lower version of py

#

Anyways

spice seal
#

Which one

#

It works very fine for me

#

@tawdry vector u use premium?

tawdry vector
#

Im making my hybrid command but they slash commands doesn't up of the hybrid but it works for regular commands

tawdry vector
slate swan
#

this could be a reason of slash commands not showing up thumbsupcat

tawdry vector
north kiln
#

this isn't where you sync

slate swan
#

not like this

tawdry vector
#

It says it app commands don't have a attribute command tree

tawdry vector
slate swan
#

your bot has an attribute "tree" and that attribute has a sync method

tawdry vector
#

So tree instead of command tree?

viscid hornet
unkempt canyonBOT
#
Nah.

No documentation found for the requested symbol.

viscid hornet
#

slate swan
#

!d discord.ext.commands.Bot.tree

unkempt canyonBOT
#

property tree```
The command tree responsible for handling the application commands in this bot.

New in version 2.0.
viscid hornet
slate swan
#

tree returns discord.app_commands.CommandTree

viscid hornet
tawdry vector
#

This gives error too

viscid hornet
viscid hornet
tawdry vector
#

bot .tree.sync?

viscid hornet
slate swan
#

just await it and call it

viscid hornet
#

^^

tawdry vector
viscid hornet
#

put it in a command

young dagger
#

Do you guys have any tips how I could improve this function?

viscid hornet
#

i think the second would be really good

spice seal
#

How long does it take to sync discord slash commands using hybrid commands?

wanton current
#

should be instant

upbeat otter
spice seal
#

Oh you meant fresh right?
I did it and it worked
Thanks for the help 😄

upbeat otter
#

cool

mossy osprey
#

hm

mossy jacinth
spice seal
#

Noice

#

!paste

#

Try running it and a huge error pops up

#

How can I fix it?

#

@solar path Here is the error

solar path
unkempt canyonBOT
#
Pasting large amounts of code

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

After pasting your code, save it by clicking the 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.

solar path
#

use paste service for big text

spice seal
#

Wait a sec

#

I have done it

solar path
#

good luck with the help 👍

spice seal
#

Bruh

solar path
# spice seal Bruh

asked you to post error like 5 times , you are still not doing it 🤷‍♂️

#

anyway, i gotta go , good luck

slim bloom
#

@viscid hornet

#

How do I make a command that, through requests and a proxy, sends a message to a channel

viscid hornet
spice seal
#

@solar path

#

This is error

slim bloom
viscid hornet
spice seal
#

Someone pls help me :_(

#

:=(

viscid hornet
quick gust
#

!d discord.Message.add_reaction - this tells u why it raises Forbidden

unkempt canyonBOT
#

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`.
slim bloom
spice seal
#

But I'm kinda new to dpy like for 3 months maybe?
So I don't have any experience with this

meager rock
spice seal
#

Ohk let me fix it and try

#

Will tell the updates 😄

meager rock
#

just a suggestion, use buttons instead of reactions
it will be easier to work with

viscid hornet
viscid hornet
slim bloom
viscid hornet
spice seal
#

@meager rock @viscid hornet Still didn't work

#

Doesn't work

viscid hornet
spice seal
slim bloom
viscid hornet
#

damn it

viscid hornet
spice seal
#

What can I do

slim bloom
#

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?

slate swan
#

Guys is there anyone developing discord bots for leagues?

spice seal
#

I gave it some extra permissions and it's working now 😄 thanks 👍 @viscid hornet

viscid hornet
viscid hornet
viscid hornet
slate swan
#

in roblox games

viscid hornet
# slim bloom 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

slim bloom
#

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)```
viscid hornet
#

otherwise you'll eat all other errors in the future

slate swan
#

axo can you dm me?

viscid hornet
viscid hornet
slate swan
#

okay

#

: (

viscid hornet
#

??

viscid hornet
quick gust
viscid hornet
viscid hornet
quick gust
viscid hornet
#

click on general and this is immediately what comes in

quick gust
#

💀 I'd delete that image before a mod spawns

meager rock
#

you realise you're doing the same thing by posting a screenshot of the same, right 💀

quick gust
#

that too without blurring the link and image LMAO

slate swan
#

Atleast blur the link ducky_concerned

slim bloom
#

@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```
unkempt canyonBOT
#

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.
slim bloom
quick gust
#

see the delay kwarg?, you can use that instead of asyncio.sleep

viscid hornet
slate swan
slim bloom
slim bloom
viscid hornet
slim bloom
viscid hornet
slim bloom
#

@viscid hornet

viscid hornet
gleaming inlet
#

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 lemon_wink

slate swan
#

"everyone" -> Meanwhile people just set their time zone in bio

viscid hornet
viscid hornet
gleaming inlet
#

oh yay

viscid hornet
# gleaming inlet 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
gleaming inlet
#

If chat is inactive, it will pause as well. When chat starts again, then show the new embed

viscid hornet
#

ok i'll do every 15 minutes, and let you customise the time

gleaming inlet
#

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

viscid hornet
#

and then to define an active chat, i'll say 20 messages in a minute

gleaming inlet
#

yeah thats the gist of it

#

So at least the bot doesn't get rate limited or something

viscid hornet
#

👍

#

fuck, now i gotta think about the logistics

gleaming inlet
#

what about logistics?

#

like where to deploy?

viscid hornet
#

no like how to make it work lmao

gleaming inlet
#

lol take your time

slim bloom
#

in on_message event?

viscid hornet
slim bloom
#

no?

viscid hornet
#

how would you even use that?

slim bloom
quick gust
#

use a try except statement while messaging the author

viscid hornet
viscid hornet
slim bloom
polar coyote
#

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"

viscid hornet
#

and no its not been deprecated

#

!d discord.InteractionResponse.send_modal

unkempt canyonBOT
#

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.
polar coyote
viscid hornet
#

what does the console say?

polar coyote
#

It doesn't throw any exceptions

viscid hornet
polar coyote
viscid hornet
#

i mean it shouldnt do because thats something else

wanton current
viscid hornet
#

i reproduced the thing

polar coyote
polar coyote
viscid hornet
#

i have no idea how you managed to get an activity in your bot tho 😭

wanton current
#

It's a discord bug but it shouldn't affect the command

viscid hornet
ivory falcon
#

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

polar coyote
outer violet
#

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

polar coyote
ivory falcon
polar coyote
#

After changing your code to the above, try running it and see if the error persists

slate swan
#

Hey! How can register commands to create dm slash commands?

#

I'm using pycord.

ivory falcon
blazing beacon
fast osprey
#

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)

blazing beacon
#

ah thanks for the insight i never thought about it like that

blazing beacon
spice warren
blazing beacon
spice warren
#

Yes, sadly

vital axle
#

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

outer violet
vital axle
#

yeah i fixed it

outer violet
#

So you want to put email at the bottom and password at the top

vital axle
#

had to change a parameter name and change it back for discord to change it

slim bloom
#

Skibidi toilet

spice warren
#

What does what mean

ivory falcon
spice warren
#

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

fast osprey
#

dude literally goin 🤨

ivory falcon
spice warren
#

Discord cannot handle big numbers

slate swallow
#

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

fast osprey
#

Code?

slim bloom
#

@fast osprey

#

@viscid hornet

#

How do I make forms in Python Discord?

ivory falcon
#

modals

ivory falcon
viscid hornet
unkempt canyonBOT
#

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...
shadow vigil
#

wait there is no actual way to get last member message?

fast osprey
#

Not efficiently

hushed galleon
#

not through the API, so you'll need to track message events as they come in and keep a record of their last messages

limber tide
#

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?

slate swan
#
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
fast osprey
#

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

fast osprey
slim bloom
limber tide
viscid hornet
# slim bloom Could you give me an example if it's not too much to ask please?Could you give m...

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)
viscid hornet
unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

slim bloom
#

@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).

fast osprey
#

You're trying to send a modal as a view

outer violet
fast osprey
#

You also can only send a modal in response to an interaction, you can't just send it to a context

viscid hornet
# outer violet wym

cant you only update one role? also i feel like thats deprecated by an audit log

viscid hornet
# slim bloom how fix?

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.

outer violet
viscid hornet
#

and why not just use the audit log?

outer violet
#

im asking in what ways could i implement it

outer violet
viscid hornet
viscid hornet
unkempt canyonBOT
#

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.
slate swan
# fast osprey You should probably be subclassing `ui.View` and implementing the select in it
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
viscid hornet
#

also you should be subclassing modal as well. it’ll make things way easier

slate swan
quasi surge
#

hello

viscid hornet
#

wait

slate swan
#

huh

viscid hornet
# slate swan huh

ngl i feel like the issue would be solved if you just subclass the select as well

slate swan
#

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

viscid hornet
fast osprey
#

You shouldn't be stapling callbacks onto generic selects

viscid hornet
#

^^

fast osprey
#

either a) use the @ui.select decorator or b) subclass Select

viscid hornet
#

i forgot theres a select decorator

#

thanks solstice

quasi surge
#

What is a good starting place to make a script for this client?

quasi surge
quasi surge
viscid hornet
quasi surge
#

ok

main holly
#

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

scarlet tiger
main holly
#

idk how

#

when i tried to import it, it said it wasnt defined

#

from discord.ui import Button, View, ButtonStyle

#

like that

scarlet tiger
main holly
#

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

scarlet tiger
main holly
#

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?

scarlet tiger
main holly
#

alright