#discord-bots

1 messages ยท Page 1124 of 1

slate swan
#

i get my energy at night lol

#

you can either
12456532 the ID
sarth#0460 the username#discriminator
sarth the username only

#

you sleep?

slate swan
#

Oh lol

jovial urchin
slate swan
#

๐Ÿ‘€

#

the unlucky one gets banned

#

lucas style baby

#

๐Ÿ˜ฉ

slate swan
jovial urchin
slate swan
#

can we trade

slate swan
#

And also name with tag

#

but usernames can be same

slate swan
#

like if i'll change my username to okimii

#

a ban would choose a random one from us

#

Don't

#

if we use !ban okimii

slate swan
#

Ye

slate swan
#

๐Ÿ˜๐Ÿ’

slate swan
#

:expressionless:

#

๐Ÿ˜

slate swan
slate swan
#

๐Ÿ˜

#

sparky, you didnt sleep yet

#

sparky sleep with me

slate swan
#

stop and go to sleep

#

๐Ÿ˜ค

#

..

#

btw oki, do you use some ide for rust?

#

i use vsc

#

same but i wanna escape the vscode addiction

#

neovim

#

ew

#

vim๐Ÿ‘๏ธ๐Ÿ‘๏ธ

#

notepad better

#

no u

jovial urchin
#

whats the difference between nvim and vim?

slate swan
#

vsc is like you sarth, i cant get enough of it๐Ÿ˜ฉ

#

bro they teaching me :quit command as the first topic
makes me already give up

jovial urchin
#

bro quitting is so easy

jovial urchin
#

idk why people complain about it, atleast not in normal vim

slate swan
jovial urchin
slate swan
#

yeah and linting

cedar sigil
#

Hi

slate swan
#

sarth lets do something, i keep learning rust without procrastination and you learn neovim without procrastination๐Ÿ˜ณ

#

productivity go boom

vocal plover
#

I was going to learn neovim and then I realised I'm lazy af

cedar sigil
#

does anyone know how discord webhooks work?

slate swan
jovial urchin
#

Is it allowed to ask people to join their server? I need 1 person to test my bot

slate swan
#

use an alt

paper sluice
#

nvim with emacs = โค๏ธ

slate swan
#

Why rust?

#

alts are kinda essential for bot dev

slate swan
cedar sigil
paper sluice
cedar sigil
#

ive already set up the code

slate swan
cedar sigil
#

I just dont know how to send info to it

slate swan
#

Rip Ryuga mail

slate swan
#

mehh gedit

slate swan
unkempt canyonBOT
#

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

Creates a webhook for this channel.

Requires [`manage_webhooks`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_webhooks "discord.Permissions.manage_webhooks") permissions.

Changed in version 1.1: Added the `reason` keyword-only parameter.
jovial urchin
slate swan
#

!d discord.Webhook.send

unkempt canyonBOT
#
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message using the webhook.

The content must be a type that can convert to a string through `str(content)`.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object.

If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects to send.

Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
slate swan
#

i like this better๐Ÿ˜

#

i still dont have a project idea smh

#

i did it, thank you

#

welcome

cedar sigil
slate swan
#

Guys use snipping tool

paper sluice
slate swan
paper sluice
#

imma write hikari in rust ๐Ÿ’€ ๐Ÿ’€

slate swan
slate swan
#

sis

#

๐Ÿ™€

slate swan
#

Wth is serenity

#

discord API for rust

#

Oh

swift pumice
#

what means buckettype default?

slate swan
swift pumice
slate swan
#

!pip hikari

unkempt canyonBOT
slate swan
#

OK 12 am

slate swan
#

** Application Programming Interface**

API stands for Application Programming Interface. In the context of APIs, the word Application refers to any software with a distinct function.

an API doesnt really need to be a website which gives you json

#

Gn everyone

#

I'm sleeping now enough

slate swan
paper sluice
swift pumice
slate swan
unkempt canyonBOT
#
Not in a million years.

No documentation found for the requested symbol.

slate swan
swift pumice
slate swan
#

!d discord.ext.commands.BucketType.member

unkempt canyonBOT
slate swan
swift pumice
#

thank youu

slate swan
#

yep

paper sluice
slate swan
slate swan
#

guess i'll use IDEA for rs

#

in vsc i just open an intergrated terminal and then i just do cargo run

paper sluice
#

i use pycharm for python because its too good to leave and emacs for rs and c

slate swan
#

vscode all the way

swift pumice
#
nextcord.ext.commands.BucketType.member(2,3)``` can i do it like that? i want that after 2 commands they get a 3 sec cooldown. does it work like that?
slate swan
#

vsc๐Ÿ˜

slate swan
swift pumice
#

does it have to be over async def or under?

slate swan
#

above ofcourse

#

its a decorator

swift pumice
#

oh okay

#
@commands.cooldown(2,3, commands.BucketType.member)
async def alex(ctx):
    await ctx.send("@rugged tulip ist sรผรŸ ๐Ÿ™„")``` it will work like that right?
slate swan
#

yep!

swift pumice
#

thank you for your help :)

#

and sorry that iam asking dumb questions, i just want to go sure

paper sluice
#
def decorator(function):
    # the decorator takes a function then we have an 
    # inner function which takes the params for the `function`.
    def inner(*args, **kwargs):
        # these *args **kwargs are the args that have to be passed in `function`
        ...
        return function(*args, **kwargs)
    return inner 

@decorator
def foo():
    ...
# is the same as
def foo():
    ...
foo = decorator(foo)

# --------------------------
# when u call foo, what basically happens is
# decorator(foo)(...)
# because decorator return inner the function call is
# inner(...)
slate swan
#

๐Ÿฟ

#

cause the callback is called directly, not with mentioning them inside a decorator

#

but the terminology is same

#

๐Ÿ˜” i misread

jovial urchin
#
@bot.command(name="ban-user")
async def ban_user(ctx, member):
    await ctx.guild.ban(member)

Whats the correct way to ban someone?

swift pumice
#

@slate swan

#
@commands.cooldown(2,5, commands.BucketType.member)
async def alex(ctx):
    await ctx.send("@rugged tulip ist sรผรŸ ๐Ÿ™„")
``` how can i make that if he still sends a command that my bot will say something like? stop?
slate swan
paper sluice
slate swan
#

me right now: lemon_imp

#

you forgot to check perms lmfao

livid hinge
#

bruh

swift pumice
slate swan
jovial urchin
livid hinge
#

why discord crashes on me so much

paper sluice
slate swan
unkempt canyonBOT
#

@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the current channel permissions, not the guild wide permissions.

The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").

This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
slate swan
slate swan
livid hinge
#

i literally cannot click "jump to message" without it literally crashing. x_x

swift pumice
warped mirage
#

guys how can i add a error message so if someone who doesnt have the correct perms it returns a inter.reply in a embed

jovial urchin
paper sluice
livid hinge
warped mirage
jovial urchin
#

I try to do !ban-user @rich otter#1111

slate swan
# swift pumice what

it raises a commands.CommandOnCooldown which you can handle using an error handler

livid hinge
#

so thinking of just running an out of date version ...

slate swan
swift pumice
paper sluice
livid hinge
slate swan
#

sometimes discord has breaking changes that can make your client crash if e.g a icon is in cache

jovial urchin
paper sluice
warped mirage
slate swan
slate swan
unkempt canyonBOT
#

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

The default command error handler provided by the bot.

By default this logs to the library logger, however it could be overridden to have a different implementation.

This only fires if you do not specify any listeners for command error.

Changed in version 2.0: `context` and `exception` parameters are now positional-only. Instead of writing to `sys.stderr` this now uses the library logger.
jovial urchin
slate swan
warped mirage
#

so lets say the user doesnt have the permissions i want it to return a error

swift pumice
slate swan
#

is interaction.message.author valid ? like ctx.message.author?

paper sluice
slate swan
maiden fable
#

Nice

jovial urchin
slate swan
slate swan
#

dont ignore me๐Ÿ˜ก

sick birch
paper sluice
slate swan
#

typehints in python are just a theory, not in rust tho๐Ÿ˜ณ

sick birch
#

!e

def my_function(str_arg: str):
  print(str_arg)
my_function(2)
unkempt canyonBOT
#

@sick birch :white_check_mark: Your eval job has completed with return code 0.

2
jovial urchin
#

oh I see. Ty all

sick birch
#

Python has no problem with that

slate swan
#

didnt I?

slate swan
warped mirage
slate swan
#

of course I did?

sick birch
#

She did

slate swan
#

rust is statically typed so it would scream at you

slate swan
# warped mirage wdym

has_permissions will raise a MissingAccess exception, handle that, and remove the if not client.has... and use the tree error I linked to

#

How can i get message author in discord.Interaction ? like ctx.message.author ?

#

yes....

unkempt canyonBOT
slate swan
#

Thank you

paper sluice
slate swan
#

yes....

sick birch
#

what's it say?

slate swan
#

ask him

slate swan
paper sluice
#

what are u passing in that function?

paper sluice
slate swan
#

what more proof do you want ๐Ÿ˜ญ

slate swan
slate swan
slate swan
warped mirage
#

can u please just help me with that?

slate swan
#

I literally have an error handler

#

uh...

warped mirage
slate swan
#

dude

warped mirage
#

i just need it for the specific command

paper sluice
#

imma use that

slate swan
#

hmmm InteractionResponded: This interaction has already been responded to before ?

slate swan
# warped mirage i just need it for the specific command

oh that
do it like this (I'll add it to the gist thanks)

@command_name.error
async def command_name_error(inter: discord.Interaction, error: discord.app_commands.AppCommandError):
  await inter.response.send_message("uwu you")
slate swan
#

ยฏ_(ใƒ„)_/ยฏ

unkempt canyonBOT
slate swan
# sick birch Code?
@bot.tree.command(name="mute", description="Mute a member !")
async def _mute(interaction: discord.Interaction, member: discord.member.Member, time: str):
    if interaction.user.guild_permissions.administrator:
        try:
            time_convert = {"s":1, "m":60, "h":3600,"d":86400}
            tempmute= int(time[0]) * time_convert[time[-1]]
            role = get(member.guild.roles, name='Muted')
            await member.add_roles(role)
            embed=discord.Embed(title="User Muted!",description="**{0}** was muted by **{1}**!".format(member,interaction.user),color=discord.Color.blue())
            await interaction.response.send_message(embed=embed)
            await asyncio.sleep(tempmute)
            await member.remove_roles(role)
        except:
            embed=discord.Embed(title="Error!", description="There is an error!", color=discord.Color.red())
            await interaction.response.send_message(embed=embed)
paper sluice
#

empty except ๐Ÿ˜ฉ

slate swan
#

followup ?

warped mirage
slate swan
paper sluice
slate swan
#

thank you !

#

wtf

sick birch
# slate swan ```py @bot.tree.command(name="mute", description="Mute a member !") async def _m...

What's probably happening is that an error is occurring in either of these 2 lines:

  • await asyncio.sleep(tempmute)
  • await member.remove_roles(role)
    You'll notice both of these lines come after await interaction.response.send_message(embed=embed), and you also have await interaction.response.send_message(embed=embed) inside your except. This means that you can respond to the interaction inside the try block, get an error, go into the except block, and respond to the interaction again
#

This is one of the reasons you should scope your try/catch blocks to be as specific as possible

paper sluice
#

its a whole different story when that happens irl ๐Ÿ’€

warped mirage
slate swan
#

yes.

#

but better use the isinstance

#

to typically catch the required error

#

I'll update the gist too for that

warped mirage
#

thats what i need

#

so how do i fix it then

#

@slate swan question one, can I make multiple of these error functions? 2) how should I fix it then

paper sluice
slate swan
paper sluice
#

then see what exception it raises and catch that @warped mirage

#
Raises
HTTPException โ€“ Sending the message failed.

Forbidden โ€“ You do not have the proper permissions to send the message.

ValueError โ€“ The files or embeds list is not of the appropriate size.

TypeError โ€“ You specified both file and files, or you specified both embed and embeds, or the reference object is not a Message, MessageReference or PartialMessage.
warped mirage
#

Damm , in dpy 1.7.3 u didnโ€™t have to make all of this lmao oh well stuff changed

paper sluice
#

why can't u catch Forbidden?

warped mirage
#

Ok let me make myself clear.

paper sluice
#

no that was not to u ๐Ÿ˜…

warped mirage
#

Lmfao

#

I donโ€™t wanna have any error handlers for all the functions ,

I wanna make error handlers for certain commands so currently I just want it for the ban command, you get what I mean?

slate swan
#
    @discord.ui.button( emoji = f"{e_gems}", style=discord.ButtonStyle.primary, row=2, disabled=False)
    async def b_profession(self, interaction: discord.Interaction, button: discord.ui.Button):

        img = requests.get(i_background_organization, stream = True) 
        img = Image.open(io.BytesIO(img.content))
        img = img.convert('RGBA') 

        imgF = requests.get(i_frameS_organization, stream = True) 
        imgF = Image.open(io.BytesIO(imgF.content))
        imgF = imgF.convert('RGBA') 

        imgFM = requests.get(i_frameSM_organization, stream = True) 
        imgFM = Image.open(io.BytesIO(imgFM.content))
        imgFM = imgFM.convert('L') 

        ava = interaction.user.display_avatar

        ava = requests.get(ava, stream = True) 
        ava = Image.open(io.BytesIO(ava.content))
        ava = ava.convert('RGBA') 
        ava = ava.resize((240, 240), Image.ANTIALIAS)

        avaM = Image.new('L', ava.size, 0 ) 
        avaMD = ImageDraw.Draw(avaM) 
        avaMD.ellipse((0, 0, 240, 240), fill=255) 

        img.paste(ava, (430, 195), avaM)
        img.paste(imgF, (0, 0), imgFM)

        img.save('./ImageS/profile_org.png')

        file = discord.File("./ImageS/profile_org.png")

        await interaction.response.edit_message(attachments = [file], view=self)

Dear tell me what is the problem?

warped mirage
#

I donโ€™t wanna have any error handlers for all the functions ,

I wanna make error handlers for certain commands so currently I just want it for the ban command, you get what I mean?

paper sluice
idle laurel
#

when im using message.content it returns a blank value?

            message = await new_channel.send(f"<@{str(author.id)}>", embed=embed)
            await message.add_reaction("๐Ÿ”’")

            def check(reaction, user):
                return user != self.bot.user and str(reaction.emoji) == "๐Ÿ”’" and reaction.message == message

            payload, user = await self.bot.wait_for('reaction_add', check=check)
            message = await new_channel.history().flatten()

            with open(f"./discord/data/{str(user.id)}{str(guild.id)}", 'w') as file:
                for i in reversed(range(len(message))):
                    message = f"{str(message[i].author)}: {str(message[i].content)}\n"
                    file.write(message)
slate swan
paper sluice
paper sluice
unkempt canyonBOT
#

4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.

paper sluice
#

oh

idle laurel
paper sluice
slate swan
warped mirage
#

?

warped mirage
paper sluice
#

u also need to import it

warped mirage
slate swan
#

Is the drop-down menu working on 1.7.3?

sick birch
paper sluice
slate swan
warped mirage
paper sluice
warped mirage
#

like for each function it will catch the permission from the command itself right?

paper sluice
inner wing
#

how add to embed image from path

jovial urchin
#
@bot.command(name="unban-user")
async def unban_user(ctx, member:discord.Member):
    await ctx.guild.unban(member)

discord.ext.commands.errors.MemberNotFound: Member "Alfonsalt#2064" not found.

warped mirage
#

please answer my question lol

paper sluice
warped mirage
#

wt

paper sluice
#

im not sure, its not practical to make multiple functions

#

u can do everything in one

inner wing
warped mirage
slate swan
unkempt canyonBOT
#

Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:

# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")

# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
    file = discord.File(f)

When using the file-like object, you have to open it in rb mode. Also, in this case, passing filename to it is not necessary.
Please note that filename can't contain underscores. This is a Discord limitation.

discord.Embed instances have a set_image method which can be used to set an attachment as an image:

embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png")  # Filename here must be exactly same as attachment filename.

After this, you can send an embed with an attachment to Discord:

await channel.send(file=file, embed=embed)

This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.

warped mirage
#

this is the last thing i need please

jovial urchin
#
@bot.command(name="unban-user")
async def unban_user(ctx, member:discord.Member):
    await ctx.guild.unban(member)

discord.ext.commands.errors.MemberNotFound: Member "Alfonsalt#2064" not found.
How do I solve this? Ofc the member won't be found since its not in the server anymore

restive urchin
idle laurel
#

im not sure whats going wrong with this, it was working before i enabled intents

            message = await new_channel.history().flatten()

            with open(f"./discord/data/{str(user.id)}{str(guild.id)}", 'w') as file:
                for i in reversed(range(len(message))):
                    message = f"{str(message[i].author)}: {str(message[i].content)}\n"
                    file.write(message)
Traceback (most recent call last):
  File "D:\Documents\Programming\Python\Hyplex Bot\venv\lib\site-packages\nextcord\client.py", line 445, in _run_event
    await coro(*args, **kwargs)
  File "D:\Documents\Programming\Python\Hyplex Bot\discord\cogs\ticket.py", line 85, in on_raw_reaction_add
    message = f"{str(message[i].user)}: {str(message[i].content)}\n"
AttributeError: 'Message' object has no attribute 'user'
jovial urchin
slate swan
iron sorrel
#

hi guys, can i have async checks for commands?

paper sluice
slate swan
iron sorrel
#

!d disnake.ext.commands.check

unkempt canyonBOT
#

@disnake.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Command "disnake.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Command.checks "disnake.ext.commands.Command.checks").

These checks should be predicates that take in a single parameter taking a [`Context`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Context "disnake.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.CheckFailure "disnake.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.disnake.ext.commands.on_command_error "disnake.disnake.ext.commands.on_command_error") event.

If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.CommandError "disnake.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.disnake.ext.commands.on_command_error "disnake.disnake.ext.commands.on_command_error").
idle laurel
#
Traceback (most recent call last):
  File "D:\Documents\Programming\Python\Hyplex Bot\venv\lib\site-packages\nextcord\client.py", line 445, in _run_event
    await coro(*args, **kwargs)
  File "D:\Documents\Programming\Python\Hyplex Bot\discord\cogs\ticket.py", line 85, in on_raw_reaction_add
    message = f"{str(message[i].author)}: {str(message[i].content)}\n"
AttributeError: 'str' object has no attribute 'author'
paper sluice
iron sorrel
#

i mean, how can i not have async checks, after all im accessing ctx, so i may need to send something to it

#

i havent tried it yet

idle laurel
# fading marlin code?
            message = await new_channel.history().flatten()

            with open(f"./discord/data/{str(user.id)}{str(guild.id)}", 'w') as file:
                for i in reversed(range(len(message))):
                    message = f"{str(message[i].author)}: {str(message[i].content)}\n"
                    file.write(message)
warped mirage
#
em = discord.Embed(title="An error has occured", description="You cannot use this command", color=0xFF0000, ephemeral=True)
TypeError: Embed.__init__() got an unexpected keyword argument 'ephemeral'
``` how do i fix this
slate swan
paper sluice
iron sorrel
#

would i do

#

how would i

#

add that check inside a cog tho

fading marlin
jovial urchin
#

Whut:
discord.ext.commands.errors.UserNotFound: User "Afonsalt#2064" not found.
I literally pressed the copy button on that account to get the username

warped mirage
#

but thanks

slate swan
paper sluice
warped mirage
slate swan
warped mirage
#

omg bruh

slate swan
#

im very sure on that

slate swan
iron sorrel
#

yeah but

fading marlin
iron sorrel
#

i want multiple ones

jovial urchin
#

discord.ext.commands.errors.UserNotFound: User "Afonsalt#2064" not found

slate swan
#

multiple?

restive urchin
#

huh that might be my problem

slate swan
unkempt canyonBOT
#
Not in my house!

No documentation found for the requested symbol.

slate swan
#

huh

paper sluice
#

!d asyncio.create_task

unkempt canyonBOT
#

asyncio.create_task(coro, *, name=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") and schedule its execution. Return the Task object.

If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").

The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop"), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError "RuntimeError") is raised if there is no running loop in current thread.
iron sorrel
#

๐Ÿคท

slate swan
#

ofc its not documented

iron sorrel
warped mirage
paper sluice
restive urchin
#

among the discord.py examples is this one, which calls client.loop.create_task(my_background_task()), which is where I got the idea.

restive urchin
warped mirage
#
    await self.on_error(interaction, error)  # type: ignore
  File "C:\Users\Dom\Desktop\ZEEFUT UTILITIES\main.py", line 56, in ban_error
    return await inter.send(embed=em, ephemeral=True)
AttributeError: 'Interaction' object has no attribute 'send'
``` any ideas
slate swan
#

thats just making a task with the attribute Client.loop which is literal to an asyncio.AbstractEventLoop @restive urchin

paper sluice
warped mirage
#
@ban.error
async def ban_error(inter: discord.Interaction, error: app_commands.AppCommandError):
    if isinstance(error, MissingPermissions):
        em = discord.Embed(title="An error has occured", description="You cannot use this command", color=0xFF0000)
        return await inter.send(embed=em, ephemeral=True)``` code
slate swan
fading marlin
iron sorrel
#

no. wait

slate swan
#

for all cmds in the cog?

jovial urchin
iron sorrel
#

i have 2 commands, lets say in this simple example,
marry and divorce,
i want to have checks like

async def check_target_not_bot(ctx):
  if any(u.bot in ctx.message.mentions):
    await ctx.send("you cant marry a bot")
    return False
  return True
 
async def check_is_not_already_married(self, ctx):
  # i will get the user here, dw about that part
  target   = ctx.message.mentions[0]
  user     = await self.client.db.users.get(ctx.author.id)
  target   = await self.client.db.users.get(target.id)

  return not user.marriage_id or not target.marriage_id
idle laurel
restive urchin
iron sorrel
paper sluice
slate swan
jovial urchin
unkempt canyonBOT
#

@paper sluice :x: Your eval job has completed with return code 1.

001 | 1
002 | ----------------------------------------------------------------------------------------------------
003 | Traceback (most recent call last):
004 |   File "<string>", line 6, in <module>
005 | TypeError: foo() takes 0 positional arguments but 1 was given
paper sluice
slate swan
#

ryuga what was that

#

๐Ÿ˜

jovial urchin
paper sluice
slate swan
#

oh nothing

paper sluice
restive urchin
#

Oh I think I know where I am messing up, I need to make my function a coroutine.

#

I'll look that up.

iron sorrel
grave basalt
deep osprey
#
from discord.ext import commands 

bot = commands.Bot(command_prefix='esk')

@bot.command()
async def say(ctx,arg):
  await ctx.send(arg)```
#

This code doesn't execute the command

slate swan
#

well are you running the command and the bot?

deep osprey
#

yeah

jovial urchin
#

I thought the username worked for that

grave basalt
#

yeah well a string isnt a snowflake

#

it expects a snowflake object

jovial urchin
#

What is a snowflake object?

warped mirage
#

Btw @slate swan just curious, would interaction.reply be possible? Without embeds or ephemeral

warped mirage
#

Ok

paper sluice
deep osprey
#

No I don't, just the command doesn't execute

paper sluice
#

is the bot running?

deep osprey
#

yeah

paper sluice
slate swan
paper sluice
#

have u ever seen irl Snowflakes?

jovial urchin
# grave basalt yeah well a string isnt a snowflake
@bot.command(name="ban-user")
async def ban_user(ctx, member:discord.Member):
    await ctx.guild.ban(member)

@bot.command(name="unban-user")
async def unban_user(ctx, member:discord.User):
    await ctx.guild.unban(member)

The ban works when I pass it a username but the unban doesn't and says it can't find the user. Both expect a User (abc.snowflake)

deep osprey
#

@paper sluice What is the guild?

paper sluice
deep osprey
#

yeah

paper sluice
slate swan
#

discords api calls a server a guild its mainly just an alias lol

paper sluice
#
class User(abc.snowflake): ....
jovial urchin
deep osprey
#

@paper sluice So why is my command not executing?

slate swan
paper sluice
jovial urchin
paper sluice
paper sluice
#

like !unban 739847923473284792837

jovial urchin
#

Is there no way to do it with @jovial urchinalt?

#

like using@

paper sluice
jovial urchin
#

yeah but the username is still unique?. Like if I do unban Alfons#7577

paper sluice
#

ya u can, but its very ugly

slate swan
#

if they dont share any other mutual guild, they are not in bot's cache anymore

paper sluice
#

u loop over the guild ban list, and check the name

jovial urchin
paper sluice
paper sluice
#

imo manual unbanning is better

vocal plover
slate swan
#

DaniGlasses lucas ban/unban over everything

paper sluice
jovial urchin
slate swan
#

!d discord.Guild.bans sure.

unkempt canyonBOT
#

async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").

You must have the [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to get this information.

Changed in version 2.0: Due to a breaking change in Discordโ€™s API, this now returns a paginated iterator instead of a list.

Examples

Usage...
vocal plover
#

at a certain point using search becomes uh... infeasible

paper sluice
restive urchin
#

Ok, I gotta be doing something wrong here, or working in the totally wrong direction.

I am trying to make a periodic save of some data to my database.

In my main file I am doing this:

asyncio.create_task(autosave.autosave(bot, logger, activitylog, db_conn))```

Which calls autosave, which looks like this: 
```py
async def autosave(bot, logger, activitylog, db_conn):
    await bot.wait_until_ready()
    while not bot.is_closed:
        await save(logger, activitylog, db_conn)
        await asyncio.sleep(60)  # saves every 60 seconds```

save() has a bunch of SQL, and I have no idea if that is working or not, but for debugging purposes I put in some logger code to check if things were working and it does not trigger at all, so something is wrong. The function, edited for brevity:

```py
async def save(logger, activitylog, db_conn, debug=True):

    ... # SQL stuff

    try:
        ... # more SQL stuff

        if debug:  # show our work in the console
            check = await db_conn.execute(f"SELECT * FROM activitylog")
            rows = await check.fetchall()
            logger.debug("Data in activitylog database:")
            for row in rows:
                logger.debug(f"ID: {row[0]} - Name: {row[1]} - Lastseen: {row[2]} "
                             f"- Firstseen: {row[3]} - Messagecount: {row[4]}")

    except aiosqlite.Error as e:
        logger.error(e)```

I am rather lost why my debugging code isn't working, and suspect the whole coroutine loop isn't firing.

Full code here: https://github.com/Volatar/ThuearleBot/tree/activitylog
GitHub

Contribute to Volatar/ThuearleBot development by creating an account on GitHub.

paper sluice
#

oop

deep osprey
#

@slate swan ```python
import os
my_secret = os.environ['TOKEN']
import discord
import requests
import json
from discord.ext import commands

bot = commands.Bot(command_prefix='esk')

@bot.command()
async def say(ctx,arg):
await ctx.send(arg)

client = discord.Client()

def getquote():
response = requests.get("https://zenquotes.io/api/random")
json_data = json.loads(response.text)
quote = json_data[0]['q'] + " -" + json_data[0]['a']
return(quote)

@client.event
async def on_ready():
print("We have sucessfully logged in as {0.user}".format(client))

client.run(my_secret)```

paper sluice
#

why do u have client and bot

#

remove the client, just use bot and do bot.run(token)

austere vale
#

what does this error mean?

paper sluice
austere vale
#

ty

deep osprey
#

@slate swan That's not the main problem, The command doesn't execute. (say command)

slate swan
paper sluice
slate swan
#

dont ignore poor ryuga๐Ÿ˜”

#

and you should change to aiohttp so your bot responds to heartbeats when making a request

deep osprey
#
import os
my_secret = os.environ['TOKEN']
import discord
import requests
import json
from discord.ext import commands 

bot = commands.Bot(command_prefix="esk")

@bot.command()
async def say(ctx,arg):
  await ctx.send(arg)

def getquote():
  response = requests.get("https://zenquotes.io/api/random")
  json_data = json.loads(response.text)
  quote = json_data[0]['q'] + " -" + json_data[0]['a']
  return(quote)

@bot.event
async def on_ready():
  print("We have sucessfully logged in as {0.user}".format(bot))

@bot.event
async def on_message(message):
  if message.author == bot.user:
    return
    
  elif message.content.startswith('eskuseme'):
    await message.channel.send('Did somebody call me?' and 'Yes?')

    
bot.run(my_secret)``` @paper sluice Still.
slate swan
#

what version of dpy do you have

deep osprey
#

1.7.3

grim oar
#

1.7.3

slate swan
grim oar
#

Yes

slate swan
#

nova no ones talking to you

grim oar
#

Ok

deep osprey
#

1 what? okimii

slate swan
#

go joke around somewhere else

slate swan
paper sluice
grim oar
#

You are not my dad ok

slate swan
#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").

Example...
slate swan
#

save a line and have repeated events๐Ÿ˜ณ

paper sluice
#

ah yes

deep osprey
#

How can I do that?

slate swan
#

just replace your event decos with listen

grim oar
#

@bot.listen()
async def on_message (): ...

slate swan
grim oar
#

Dont teach me ok

deep osprey
#

for on_ready too?

slate swan
#

atleast give examples that work

slate swan
deep osprey
#

works now but I still don't get it, why @bot.listen made that work?

slate swan
deep osprey
#

thank you โค๏ธ, you too @paper sluice

slate swan
#

pleasure

deep osprey
#
@bot.command()
async def say(ctx, arg1, arg2):
    await ctx.send(arg1, arg2)```
#
Traceback (most recent call last):
  File "/home/runner/MyBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 12, in say
    await ctx.send(arg1, arg2)
TypeError: send() takes from 1 to 2 positional arguments but 3 were given

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/runner/MyBot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/MyBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/runner/MyBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: send() takes from 1 to 2 positional arguments but 3 were given```
fading marlin
#

send isn't like print

#

!d discord.ext.commands.Context.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.

For interaction based contexts this does one of the following...
deep osprey
#

how to make that work?

fading marlin
#

string formatting?

novel blaze
#

Evening all, I've been a lurker here for a while, but always managed to solve it myself, until now :/

Is there a way to have a multiselect, where more than 1 value is already selected?

context: I'm making a games list manager for my local gaming club. I've got a modal to add a brand new game, and a select that lists all the games (read from db) so someone else can select games from the master list that they already own. I'm open to suggestions for alternate ways of managing this using the tools we have available.

deep osprey
#

@fading marlin That works now but I have another question, how to make args depends on number of words that the user says? For example: "User: $say hi" "output: hi" "User: $say two words" "output: two words"

fading marlin
#

consume rest

@bot.command()
async def say(ctx, *, args):
    ...
potent spear
#

.

cold tide
#

Hey im struggling on making the invite link to add my bot to my server can anyone happily help?

livid hinge
#

you are so welcome dude! thanks for the shout out! โค๏ธ

#

by the way i wouldn't have minded if you had actually pinged ๐Ÿ˜‚

minor totem
#

Hey @slate swan how is your wrapper going?

flat solstice
#

I'm looking a example of Discord.py 2.0's discord.SelectOption in use as I want to see all of the attributes of discord.SelectOption in use. I think I understand how the label attribute will work but I'm not sure about the description.

torn sail
flat solstice
#

ohh okay, thanks

#

what would be a usecase for the discord.SelectOption.value?

torn sail
#

so instead of converting the label to the value u need you can just use discord.SelectOption.value

smoky cedar
#

Can anyone look at my discord bot project and tell me what improvements can be made from a structuring standpoint? Like if the bot should be split into multiple files, packaging conventions, etc?

flat solstice
torn sail
flat solstice
#

that's really quite useful

flat solstice
smoky cedar
potent spear
#

open source bots are great examples

lunar moon
#

hey, how can I add reactions when someone uses a command

#

like I have a mute command, when someone uses it, I want it to add reaction to the person who used the command like a โœ…

sick birch
#

Thank you! Seeing this made my day ๐Ÿ˜Š

fading marlin
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 "discord.Emoji").

You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission 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 "(in Python v3.10)") instead of `InvalidArgument`.
snow bloom
#

Oi

lunar moon
#

I think I can use smth like ctx.message.add_reaction right ?

fading marlin
#

correct

snow bloom
#

Alguรฉm aรญ sabe fazer o bot pegar uma coisas de uma planilha do exel em manda em um canal?

fading marlin
#

English please

cursive barn
#

@snow bloomyou can use a library called openpyxl to interact with excel workbooks and import the data to an object you can reference in your bot's code. link for docs here: (https://openpyxl.readthedocs.io/en/stable/)

bright jetty
#

bruh

#

can someone help

#

idk how to setup dpy

cursive barn
#

thats a whole task in itself, can you be a bit more specific with the issue you are struggling with? @bright jetty

bright jetty
#

i know how to setup but uh do i need to install python?

#

im just starting to code with python

cursive barn
#

you can't even begin to install dpy without python installed. its a language specific library

bright jetty
#

ok

bright jetty
#

windows?

cursive barn
#
  1. Download the latest version of Python for the Operating system you use, be it windows or linux.
  2. Download the latest version of discord.py (I believe you need to use the git url for this)
  3. Find an editor you like, personally I use Atom (https://atom.io) and I find it amazing.
  4. Read through the documentation to get a feel for how everything is structured and start simple.
bright jetty
#

no thanks ima just install python and dpy

cursive barn
#

well you kind of need something to write your code with

bright jetty
#

i have vsc

cursive barn
#

vsc is a good tool too

bright jetty
cursive barn
#

it can be a bit tricky to get it setup due to differences between the built-in runtime environment and an actual deployment environment so take that in to account

#

make sure you check "Add to PATH"

#

thats super important

fading marlin
#

I strongly recommend not making dpy your first Python project, specially if you're just starting to learn Python. A lot of complicated concepts are used and you'll probably find them confusing as you go

bright jetty
#

ok

bright jetty
#

cause im making discord bots

#

what next

cursive barn
#

install it

bright jetty
#

customize?

#

i already click install now

cursive barn
# bright jetty i want dpy too

Lee was just letting you know again that d.py tends to have a steep learning curve and it can be challenging for a lot of people, especially those new to coding or OOP. After having experienced this learning curve for myself, I can agree with him.

bright jetty
#

i alr install now

#

how to install dpy

cursive barn
#

there is an installation guide on the documentation

bright jetty
#

idk about python i just started

cursive barn
bright jetty
#

ok

#

brb

cerulean folio
cerulean folio
cerulean folio
bright jetty
#

i type pip install discord.py

#

is that correct

cursive barn
#

depends on the version of discord you want to install

bright jetty
#

i did pip install discord

#

i did

#

my bot is online

jovial urchin
#

Why doesn't this work?

@bot.command(name="unban-user")
async def unban(ctx, member):
    banned_users = await ctx.guild.bans()

    member_name, member_discriminator = member.split("#")
    for ban_entry in banned_users:
        user = ban_entry.user

        if (user.name, user.discriminator) ==  (member_name, member_discriminator):
            await ctx.guild.unban(user)
            await ctx.channel.send(f"Unbanned: {user.mention}")
fading marlin
#

traceback?

jovial urchin
#

No traceback, just doesn't do what its supposed to

fading marlin
#

also, that looks fairly familiar, did you copy that off of YouTube?

jovial urchin
#

Nothing happens

sick birch
#

That's probably why

#

Copying random code from some random website is probably not worth the trouble

#

Also that looks like it's from Lucas's video

fading marlin
#

yeah lmao

jovial urchin
#

Im debuggin it and it seems like it works fine until the if statement

fading marlin
#

anyway, type hint your member parameter with discord.User, and then use ctx.guild.unban and pass in your member param, see where that takes you

jovial urchin
#

It gets the correct correct name and discriminator

sick birch
#

Just use the discord.User typehint

#

No need to mess around with the splitting stuff

#

The whole function should only really be like 1 line

fading marlin
#

^ you'll also be able to pass in IDs

jovial urchin
sick birch
#

Your member argument

#

typehint it to discord.User

jovial urchin
#

And then I remove the splitting line?

jovial urchin
fading marlin
jovial urchin
fading marlin
#

show you what exactly?

jovial urchin
#

Then I end up like this:

@bot.command(name="unban-user")
async def unban(ctx, member: discord.User):
    
    await ctx.guild.unban(member)
    await ctx.channel.send(f"Unbanned: {member.mention}")
fading marlin
#

ctx.send does the same as ctx.channel.send btw

#

and yeah, that'll work, you might need to do some error handling, but in theory it works

jovial urchin
#

And I get this error:
discord.ext.commands.errors.UserNotFound: User "Alfonsalt#2064" not found.
But it is the correct user.

fading marlin
#

try using their ID?

#

also, your bot won't be able to "see" that account if there aren't any other servers it shares with the user

jovial urchin
#

Then it works, but the point of it all was to be able to use the username

pliant gulch
#

And the screenshot you showed shows Afonsalt

fading marlin
jovial urchin
#

yeah ik doesn't matter. Still doesn't work when i copy the username

#

My plan kinda was to get the list of all the banned accounts in that server, check where the username supplied by the one calling the command matches up in the list of banned accounts, and then get the id of that banned account

#

So you could always use the username and let the bot get the id for u

jovial urchin
fading marlin
#

sure, however type hinting discord.User will make it convert to a User object, which is far handier than just having the string. Could you send the full traceback?

jovial urchin
#

of when it doesn't find the username?

#

Ignoring exception in command unban-user:
Traceback (most recent call last):
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 552, in transform
return await self.do_conversion(ctx, converter, argument, param)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 505, in do_conversion
return await self._actual_conversion(ctx, converter, argument, param)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 451, in _actual_conversion
ret = await instance.convert(ctx, argument)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\converter.py", line 254, in convert
raise UserNotFound(argument)
discord.ext.commands.errors.UserNotFound: User "Afonsalt#2064" not found.

pliant gulch
#

Looking at the source code, it'll do searches by name#discrim if given, there is really should be no reason that this errors

#

The possibility is, perhaps an old cache, or something like that but it's pretty much unlikely here

#

The only thing that really would be cause, would be the username, etc

jovial urchin
fading marlin
#

hmm

pliant gulch
#

Just want to make sure the user is cached

#

But yea, again looking back at the source code of the wrapper, it'll do searches by name#discrim when given so

#

That just leads to the user not being cached

#

Actually, have you constructed your bot instance with member intents?

pliant gulch
#

That's the issue then

#

Without member intents, in discord.py you'll have no users

#

As user cache depends on the members intent

#

So the issue you are facing would be fixed by passing member intents to the bot

fading marlin
#

I don't think that'd be the case

jovial urchin
#

Wouldn't it cause this to error aswell:

@bot.command(name="ban-user")
async def ban_user(ctx, member:discord.Member):
    await ctx.guild.ban(member)
snow bloom
#

Does anyone know how to make the bot get things from an exel spreadsheet and send it to a channel?

fading marlin
#

no, because discord.Member represents a user inside a guild

#

discord.User and discord.Member aren't the same thing

pliant gulch
#

If it cannot be found in the cache that is

jovial urchin
#

Wait so whats the solution then

pliant gulch
#

Pass member intents to the bot

jovial urchin
#

how do I do that

pliant gulch
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot 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

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

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

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

jovial urchin
pliant gulch
#

intents.members = True

pliant gulch
jovial urchin
pliant gulch
#

I mean, there is literally 3 intents on the website to pick, and one of them says SERVER MEMBERS INTENT, so. Maybe that one

#

And permissions are different from intents

#

Intents are just flags that you pass when connecting to the gateway, this'll tell the gateway which events to send

#

Permissions are well, permissions

jovial urchin
#
import discord
from discord.ext import commands
from discord import Intents

import  sqlite3

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

activity = discord.Game("!help")
bot = commands.Bot("!", activity=activity, intents=intents)


@bot.event
async def on_ready():
    print(f"Logged in as {bot.user}")

@bot.event 
async def on_message(message):
    await bot.process_commands(message)
    if message.author != bot.user:
       pass

@bot.command(name="purge-channel")
async def purge_channel(ctx):
    await ctx.channel.purge()

@bot.command(name="ban-user")
async def ban_user(ctx, member:discord.Member):
    await ctx.guild.ban(member)

@bot.command(name="unban-user")
async def unban(ctx, member: discord.User):
    
    await ctx.guild.unban(member)
    await ctx.channel.send(f"Unbanned: {member.mention}")



with open("token.txt", "r") as f:
    token = f.read()
bot.run(token)
#

This is the code, ive enabled literally every intent I can and saved changes.

#

And then this:
raceback (most recent call last):
File "c:\Users\Alfons\Programming\Python\Discord\Firstbot\main.py", line 42, in <module>
bot.run(token)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 666, in start
await self.connect(reconnect=reconnect)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 601, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Exception ignored in: <function _ProactorBasePipeTransport.del at 0x000001AA29731FC0>
Traceback (most recent call last):
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in del
self.close()
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 750, in call_soon
self._check_closed()
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed)

cerulean folio
#

hi awesome people o/
I'm having some troubles hosting my bot on replit and i can't bind a credit card nor pay online for long reasons i'm lazy to explain, so i need a free plan no cards.

I know i can't have a free hosting that is good as Robin mentionned one day, but if u guys just knoww hy replit sometimes... idk crashes? or restarts? I'm pinging it every 5 minutes since i implemented a web server on it tho, so that works fine but sometimes (like, once a day sometimes twice?) replit restarts and i find out my bot is offline ><

pliant gulch
# jovial urchin And then this: raceback (most recent call last): File "c:\Users\Alfons\Progra...

"discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead."

Discord Developer Portal

Integrate your service with Discord โ€” whether it's a bot or a game or whatever your wildest imagination can come up with.

#

The error is saying, you did not actually enable the member intents

#

Double check the portal, you probably did not save there

jovial urchin
#

1 sec ill redo the entire thing

#

So then, back to this error:
discord.ext.commands.errors.UserNotFound: User "Afonsalt#2064" not found.

jovial urchin
#

Atleast its not the intent error anymore, but intents wasn't the root of the problem

pliant gulch
jovial urchin
#

the command to unban?

pliant gulch
#

Yes

jovial urchin
#

New code:

@bot.command(name="unban-user")
async def unban(ctx, member: discord.User):
    print(1)
    print(bot.users)
    print(2)
    await ctx.guild.unban(member)
    await ctx.channel.send(f"Unbanned: {member.mention}")
#

Traceback:
Logged in as Onyx#8510
Ignoring exception in command unban-user:
Traceback (most recent call last):
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 552, in transform
return await self.do_conversion(ctx, converter, argument, param)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 505, in do_conversion
return await self._actual_conversion(ctx, converter, argument, param)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 451, in _actual_conversion
ret = await instance.convert(ctx, argument)
File "C:\Users\Alfons\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\converter.py", line 254, in convert
raise UserNotFound(argument)
discord.ext.commands.errors.UserNotFound: User "Afonsalt#2064" not found.

#

Really weird, it doesn't even print 1 or 2

pliant gulch
#

It didn't print 1 or 2 but it still errored?

#

Are you sure you saved the file before running it??

jovial urchin
#

I resaved it thrice

#

and ran it thrice

#

same result

pliant gulch
#

Ok, that is

#

Weird, anyways just print bot.users in on_ready then

jovial urchin
#

Logged in as Onyx#8510
[<ClientUser id=991141705132814356 name='Onyx' discriminator='8510' bot=True verified=True mfa_enabled=False>, <User id=289649835823595520 name='Alfons' discriminator='7577' bot=False>]

pliant gulch
#

Where is your alt account?

#

It's not in the list

#

Oh wait, your unbanning them

jovial urchin
#

yeah

pliant gulch
#

Ok, uban via ID then have the alt rejoin the server

#

Then print bot.users again

#

By restarting

#

I just wanna check that the bot can actually see the alt

jovial urchin
#

k 1 sec

#

bruh wtf

#

Now I can't even get the alt to rejoin

#

It says that its banned when its not? I've manually checked

pliant gulch
#

Okay, I figured out why this issue is happening. When you enabled intents the alt account was still banned right? So when the bot started up it did not cache the user (caching requires member intents). So naturally, this current issue will fix itself when the alt account has rejoined the guild, afterwards you can ban the alt, then unban via the user#discrim format. So the original cause was intents

jovial urchin
#

uh ive made a new server now let em try it

#

It works!!

#

You are amazing for taking the time for this

#

Thank you so much

pliant gulch
#

Keep in mind, it'll only work with name#discrim if the user being unbanned was VISIBLE during the bot's current life-time

#

So, if a user was banned before the bot got turned on. You'll be forced to use the user's ID

jovial urchin
#

So the bot has to at some point see the user to be able to unban them later?

#

So then I can just except the error and tell them they have to use the ID

pliant gulch
#

And you cannot make an API request via name#discrim, so it'll be best to use the ID

#

You can intercept the error using an on_command_error

brazen wind
pliant gulch
#

You cannot just smack a try-except block in the callback

sick birch
brazen wind
#

oh okay

jovial urchin
pliant gulch
#

It's just like your on_message, etc

#

You'll receive ctx and error as the parameters to the event

#

Just isinstance the error, check if it's user not found. Then send a message with ctx

scenic token
#

hello discord.py devs.. i am very confused about this:

import discord
import random
from discord import guild
#Making a variable the bot will reply to
bot = discord.Client()
#Telling the program that these are variables
ownerRole = '<@&978492717220913222>'
botRole = '<@&978488109756977192>'
diceBattle_random = random.randint(1, 6)
members = guild.Member
#Making the bot tell me when its ready and online
@bot.event
async def on_ready():
    print("GO, GO, GO!!")
#Telling the bot to listen for these messages and what to do if it finds them
@bot.event
async def on_message(text):
#Variables that need the (text) information
    ID = text.author
    verifyID = discord.utils.find(lambda role: guild.Role.name == 'Human')
#Hello command
    if (text.content == "$hello"):
        await text.channel.send(f' {text.author.mention} Hi!!')
#Verify command
    if (text.content == "$verify"):
        await ID.add_roles(verifyID)
        await text.channel.send(f' {text.author.mention} was verified!')
#diceBattle commands
    if text.content == "$diceBattle bot":
        await text.channel.send(f' {text.author.mention} got a {diceBattle_random}! And I got a {diceBattle_random}!')
    if text.content == "$diceBattle random":
        print("PLACEHOLD")```
i have excluded the bot.run command altogether (for obvious reasons) and i keep running into this error:
```Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\Bron\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\Bron\OneDrive\Reuben\VS Code stuff\discord bots\python bots\myBot.py", line 21, in on_message
    verifyID = discord.utils.find(lambda role: guild.Role.name == 'Human')
TypeError: find() missing 1 required positional argument: 'seq'```
help will be very much appreciated!
dusky pine
#

try discord.utils.find(lambda role: role.name == 'Human', text.guild.roles)

scenic token
#

ok, thanks!!

dusky pine
#

!d discord.utils.find

unkempt canyonBOT
#

discord.utils.find(predicate, iterable, /)```
A helper to return the first element found in the sequence that meets the predicate. For example:

```py
member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
```  would find the first [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") whose name is โ€˜Mightyโ€™ and return it. If an entry is not found, then `None` is returned.

This is different from [`filter()`](https://docs.python.org/3/library/functions.html#filter "(in Python v3.10)") due to the fact it stops the moment it finds a valid entry.

Changed in version 2.0: Both parameters are now positional-only.

Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.10)")s.
scenic token
#

it works! tysm!!

dusky pine
#

np :P

quaint epoch
unkempt canyonBOT
#

discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find "discord.utils.find").

When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.

To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.

If nothing is found that matches the attributes passed, then `None` is returned.

Changed in version 2.0: The `iterable` parameter is now positional-only.

Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.10)")s...
dusky pine
#

ic

slate swan
#

ive fallen in love with rust ngl๐Ÿ˜

sick birch
#

make a wrapper in rust, best of both worlds

slate swan
#

serenity is a thing

#

maybe ill make an api with rust and wrap it in py cuz why not

minor totem
slate swan
minor totem
#

I am finally starting to make a big bot project with it, but I am finding it equally difficult lmao

slate swan
#

๐Ÿง 

dull terrace
#

is there any reason a bot would start printing random blank lines to a console???

#

i switched from my test bot to my main with the exact same code and it's randomly throwing random blank lines in command prompt

minor totem
slate swan
dull terrace
#

literally all i do is change the token and it does this

#

its still doing it

minor totem
#

The worst part is doubting your own decisions. Like... have I made something stupid? Is this stupid? Should I know that this is stupid? Would anyone want to use this? thinkmon

shrewd apex
#

an empty print() statement somewhere?

dull terrace
#

no, i've gone through every print statement

#

i only have two infinite loops in the code and tried commenting out both

shrewd apex
slate swan
dull terrace
#

wtf

slate swan
# minor totem lmao

watch discord make a new update with their api and then making all of your bots features useless

#

๐Ÿ™‚

shrewd apex
#

that is indeed a think to look out for

dull terrace
#

ok i commented out every print and it fixed it 7739monkathink

shrewd apex
minor totem
#

๐Ÿ˜‚

slate swan
#

give them a monthlemon_imp

daring olive
slate swan
#

the message got pinged from one of my favorite mods, what an honorlemon_hyperpleased

dull terrace
#

unbelievable

#

that's not meant to be there ๐Ÿ˜ค

slate swan
#

olie why use event and no annotations and bad class instance naming๐Ÿ˜”

dull terrace
#

would explain seeing as my test bot isn't in 1k server wheeze

pliant gulch
#

I haven't really seen other libraries where you can define a presence with the constructor, or equivalent tbh

#

I've mostly seen a call in any one of those wrappers on_ready equivalent

#

Starting to make me wonder if on_ready presence changing is just a discord.py ick

slate swan
#

the status is passed to **options in the bot constructor

pliant gulch
#

I'm talking about other languages

slate swan
#

ahhh you ment other libs that use other langs

#

okie

sick birch
#

Yay! It got pinnged

slate swan
#

i'm a happy lemon

sick birch
#

Yes, you are

#

I'll take a deeper read at both yours and Ashley's and suggest any fixes

#

I'd like them to be perfect ๐Ÿ˜‰

slate swan
pliant gulch
#

"PRESENCE gateway event payload" technically speaking, the official documentation refers PRESENCE here as a gateway command

#

The ratelimits should also be dicussed

slate swan
#

ash suggested it like so, my original one was PRESENCE gateway event

pliant gulch
#

As changing presence is a gateway command, it falls under 120/2s ratelimiting

#

But the main thing is. sure discord.py handles the ratelimit here to stop you from instantly disconnecting

#

But it still uses resources on your end and on discord's end

slate swan
pliant gulch
#

Hence why in the official discord api server they actively tell you not to change presence in a loop

#

E.g your changing presence example at the bottom

sick birch
#

Hey @slate swan and @slate swan, would you guys mind making a PR on python-discord/site for both of your respective gists? We can make improvements there via code reviews

shrewd apex
#

is there a way to stop dpy commands when they are executing?

dusky pine
#

wait no hold on sys.exit(0)

shrewd apex
#

no i want to use one command to stop another

dusky pine
shrewd apex
#

sed

pliant gulch
#

Let me write an example real quick

shrewd apex
#

mhm ok thx

pliant gulch
# shrewd apex mhm ok thx
from __future__ import annotations

import asyncio


async def main() -> None:
    event = asyncio.Event() # Event used to wait.
    event.clear() # Turn OFF

    async def command(number: int) -> int:
        await event.wait()

        return await asyncio.sleep(1, number)
    
    loop = asyncio.get_running_loop()
    loop.create_task(command(123)) # Pretend this is you executing the command
    
    # Since event.clear() was called earlier, the command will wait for it to be set first.
    event.set() # Now event is set, the code after await event.wait() will now run


asyncio.run(main())
``` of course, here I'm doing the opposite of what you want, but it can be easily done the other way around too
shrewd apex
#

ic

#

thats helpful thanks a lot

dull terrace
#

my new bot's usage is disappointing 7739monkathink

#

50 depth is approximately 15 mins usage

robust fulcrum
kind plover
#

Does someone know how i could create a command which will randomly disconnect a random member from a voice channel? I just started bot coding. Any help is appreciated

slate swan
#

!d discord.VoiceChannel.members

unkempt canyonBOT
slate swan
#

!d discord.Member.move_to

unkempt canyonBOT
#

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

Moves a member to a new voice channel (they must be connected first).

You must have the [`move_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.move_members "discord.Permissions.move_members") permission to use this.

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").

Changed in version 1.1: Can now pass `None` to kick a member from voice.
kind plover
#

Thank you

#

And to pass in the specific Channel would I need the ID, or could I just specify the channel name

#

As a parameter^

slate swan
#

you can pass those 2 objects or pass None to kick the user as shown above

slate swan
#

๐Ÿ‘

#

anytime

#

anytime ๐Ÿ˜ณ

slate swan
dusky pine
#

Bro

#

I'm shaking and crying rn

slate swan
#

!ot

unkempt canyonBOT
slate swan
#

@slate swan You might want to search for Paramaters in your bot repository and replace with Parameters. Using Search and replace will make it easier.

pliant gulch
#

Also instead of forcing installing uvloop, since you are using poetry you can just do ```toml
uvloop = {version = "^0.16.0", markers = "sys_platform == 'linux'"}

slate swan
#

No problemo

slate swan
cerulean folio
#

guys is there a way to make replit sqlite database sync with an external database somewhere? because what I do is I edit code on vs code then push on github then pull on replit XD
so i lose the database data each time unless I remember to download the db from replit, then push changes, then upload it again

pliant gulch
cerulean folio
#

or a way for it not to get touched by github when i push/pull? :o

slate swan
unkempt canyonBOT
#

__main__.py lines 8 to 11

if os.name != "nt":
    import uvloop

    uvloop.install()```
pliant gulch
slate swan
cerulean folio
#

where should i create it? in .git?

slate swan
#

in your current working directory

cerulean folio
#

aaaa this is so scary I'm so scared i make a mistake and lose something

slate swan
#

it doesn't delete any data or files, that file is just used to tell git that the files mentioned are not to be pushed

#

In that case make a copy of your folder before and save it somewhere

#

does anyone know how to make global chat in discord bot python?

paper sluice
#

create a channel?

slate swan
#

a channel in multiple servers that are all connected

paper sluice
#

wdym by connected?

slate swan
#

just guilds that use webhooks to send messages like a network

slate swan
# paper sluice wdym by connected?

assume there are two servers -> server A and server B
both the servers have channels named as -> global-chat
when a message is sent in global-chat from server A, it should send the same message to global-chat in server B

#

over explanation๐Ÿ˜ตโ€๐Ÿ’ซ

#

no

#

I'm just sleepy

#

lmao

#

it's 6 am ๐Ÿ˜” okimii motivate me to sleep

slate swan
slate swan
#

yup

#

linting check failed for me too ๐Ÿ˜”

#

if i read it right

slate swan
#

sad

#

smh

#

So i have to use a webhook to do it?

shrewd apex
#

not necessarily use a webhook to do it simplest method would just be an on_message event and add a check for channel

slate swan
#

ratelimits โœจ

#

even if you use webhooks, creating webhooks for each user would be pain

pliant gulch
#

Webhooks have no POST ratelimits though, so that's plus

#

iirc

grim oar
#

they do iirc

paper sluice
#

battle of iircs, lets see who remembers correctly

grim oar
#

I remember making post requests to webhooks using ifttt

pliant gulch
#

Prob was 30/60s then

slate swan
#

A channel has a 30 msg/60 sec limit for webhooks yeah

left idol
#

how many people can i role every minute?

maiden fable
slate swan
#

unless you apply certain conditions to the channel

paper sluice
#

69 messages per 420 mins ๐Ÿ’€

dusky pine
#

which is not that bad tbh

bright jetty
#

69

#

very sus

paper sluice
swift pumice
#

an bot.event error handler will always show one error right? like i mean it doesnt show the wrong error right?

paper sluice
#

what wrong error?

#

if there is an error raised, that event is called

sonic flax
#

how would i make a bot give a specific role after you message it a command

livid hinge
#

i think it was more like 60 transactions per second or something

#

but varies depending what you are doing

livid hinge
dull knot
#
from nextcord.ext import commands
from nextcord import Interaction, SlashOption
 
import os
import nextcord 

intents = nextcord.Intents.default()
intents.message_content = True

client = commands.Bot(command_prefix='!',  intents=intents)

@client.slash_command(
  name="Hell",
  description="Will send a \"Welcome to Hell \"response",  
  guild_ids=[...],
)

async def Hell(inter: nextcord.Interaction) -> None:
 await inter.response.send_message("Welcome to Hell")

TOKEN = os.environ['TOKEN']
client.run(TOKEN)

Been at it since yesterday but I just couldn't find the problem. The bot's slash command which is /Hell just won't show up. The code runs fine and so does the bot but the /Hell command won't send the text. I even followed the links that some helpful guys sent me yesterday and tried figuring it out by doing lots of googlingHamptonOhNo

I'm new to Python so go easy on me when explaining MyBad

paper sluice
slate swan
#

the command names should be lowercase too

paper sluice
dull knot
#

Oh... Let me try that

dull knot
slate swan
#

sad

dull knot
slate swan
#

the command doesnt show up or what?

paper sluice
slate swan
#

is dpy even broken or what, my message commands aint even working

paper sluice
dull knot
dull knot
slate swan
slate swan
dusky pine
#

sigh

dull knot
#

Been at it since yesterday

dusky pine
#

slash commands are not just commands with / prefix

dull knot
#

I mean

paper sluice
dull knot
#

It just don't show up

dusky pine
#

you have to wait for the slash command menu to appear

dull knot
upbeat gust
#

nextcord and other forks autosync don't they

paper sluice
dull knot
paper sluice
dull knot
#

I didn't change anything. It's the one I wrote above

#

Couldn't figure it out myself so I figured I'd ask

paper sluice
dull knot
paper sluice
#
@client.slash_command(
  name="hell",
  description="Will send a \"Welcome to Hell \"response",  
  guild_ids=[...],
)

async def hell(inter: nextcord.Interaction) -> None:
 await inter.response.send_message("Welcome to Hell")

do this

and if it still doesn't work, enable the application.command thing i said before, kick ur bot and reinvite

dull knot
#

Oh wait. If I change stuff from the developer portal I'd have to reinvite?

dull knot
#

Ohh. Wait that might've been the problem MyBad

#

Let me try again

slate swan
sonic flax
#

How would I make it so if a channel name starts with a specific string it does what I say

slate swan
#
guild = get_guild(...)
channel = [channel for channel in guild.text_channels if channel.name.startswith("uwu")]
if not channel: "no channel found"
...

?

sonic flax
#

ty

slate swan
#

I'm sure you can use utils.find or smth but not quite sure

sonic flax
#

channel = ctx.channel?

#

wait no

slate swan
#

channel[0]

paper sluice
sonic flax
slate swan
dull knot
#

At this point, I might need to switch from nextcord to disnake

sonic flax
# slate swan ofc?

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: local variable 'channel' referenced before assignment

slate swan
#

sad

sonic flax
#

wahts wrong

paper sluice
#

where did u define channel outside the function?

dull knot
paper sluice
unkempt canyonBOT
#

@paper sluice :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 6, in <module>
003 |   File "<string>", line 3, in foo
004 | UnboundLocalError: local variable 'a' referenced before assignment
slate swan
paper sluice
# sonic flax wahts wrong

change the name to something other than channel, ur trying to reassign the same name in different scopes

paper sluice
cloud dawn
sonic flax
# slate swan

Do i remove chnnel from the loop and the thing at the bottom u highlighted

shrewd apex
sonic flax
shrewd apex
#

send ur code here as text