#discord-bots

1 messages · Page 968 of 1

slate swan
#

just do discord.ButtonSyle.your_type

upbeat gust
#

or discord.ButtonStyle

upbeat gust
slate swan
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

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

summer halo
#

Hello everyone

vale wing
#

Ig it is "Forbidden" or some other HTTPException

slate swan
#

It's a discord.Forbidden

lofty pecan
#

Heyo, i would like to check if a user has a role by id. I have a json containing id's of role and would like to compare the list of roles of the user and the authorized roles but honestly I don't understand how to access the role list of the user and then compare both ids lists

lofty pecan
blissful sparrow
#
async def dbconn():
    try:
        conn = mariadb.connect(
            user="user",
            password="pass",
            host="1.1.1.1",
            port=3306,
            database="bot_whitelisted"
            )
        
    except mariadb.Error as e:
        print(f"Error connecting to MariaDB Platform: {e}")
    sys.exit(1)

    try: 
        cur.execute(f"INSERT INTO whitelisted_guilds {guildids} VALUES (?, ?)", ("Maria","DB")) 
        
    except mariadb.Error as e: 
        print(f"Error: {e}")

    # Get Cursor
    cur = conn.cursor()

@commands.command()
    @commands.is_owner()
    async def wlguild(self,ctx, guildid):
        dbconn()

gives this error

NameError: name 'conn' is not defined even though its defined in the dbconn() function

lofty pecan
#

probably because conn isn't stored

#

the try test if maradb.connect works

#

put your cur = conn.cursor() inside the try

vale wing
#

Maybe sys.exit(1) is indented wrong but that is weird

#

It would just exit

vale wing
blissful sparrow
vale wing
#

Why is cursor defined after execution

lofty pecan
#

yay

vale wing
blissful sparrow
blissful sparrow
vale wing
#

Idk about the mariadb so can't really help, but you certainly need to define cursor before doing anything to it

#

And yeah async functions must be awaited

lofty pecan
#

Heyo, i would like to check if a user has a role by id. I have a json containing id's of role and would like to compare the list of roles of the user and the authorized roles but honestly I don't understand how to access the role list of the user and then compare both ids lists

vale wing
#
any(r.id in roles_ids_list for r in member.roles)```
lofty pecan
#

what if member isn't a variable

vale wing
#

Eh?

#

Name me a situation when it's not accessible

lofty pecan
#

it's not a command that checks, it's a command that needs to check if the user has perm before running

vale wing
#

You always have the ctx both in checks and commands

lofty pecan
#

yes

#

i have the ctx

vale wing
#

ctx.author is how you access member

lofty pecan
#

oki

#

perfect

#

huh

#

why doenst' it work

#
async def addfile(self, ctx):
        """Add file to the server folder"""
        
        id = str(ctx.guild.id)
        id_user = str(ctx.message.author.id)
        Name = str(ctx.guild.name)
        member = ctx.author 
        if (ctx.message.author.guild_permissions.administrator) or (any(r.id in self.idroles for r in member.roles)):
            try:
                f = open(f'database\{id}\{id_user}.json')
                await ctx.send(f'Database for server `{Name}` and user id `{id_user}` already exists')
            except IOError:
                with open(f'database\{id}\{id_user}.json', 'w+') as file:
                    json.dump({}, file)
                n = len((os.listdir(f'database\{id}')))
                await ctx.send(f'New database for server {Name} with id `{id}` created') 
                await ctx.send(f'There are now {str(n+1)} files in directory') 
        else:
            await ctx.send('You do not have the permissions to do that')

full command, when I run it it says I don't have the permission

#

also before that I have of course

def __init__(self, bot):
        self.bot = bot
        self.idroles = fetch('rolesid')```
#

fetch just load the json file

vale wing
#

How are the roles stored

lofty pecan
#

{"464553751030661120": ["816970896841244692", "868787775229558804"], "929126352437772358": []}

vale wing
#

They are strings

lofty pecan
#

like this

vale wing
#

And you need to compare numbers

lofty pecan
#

haa

vale wing
#

Map the roles to int

#
roles_ids = map(int, roles_ids)```
lofty pecan
#

oke oke

vale wing
#

The HTTP exceptions are wrapped

#

Try error.original

#

Iirc it is that

lofty pecan
#

is it my self.idroles?

vale wing
#

Yes

lofty pecan
#

oke oke

#

I wasn't sure hihi

vale wing
#

Wth

#

Do you mean an error handler or something else

#

try-except or on_command_error

#

Oh

lofty pecan
#

yeee

#

thanks exen! it works !

vale wing
#

Try except discord.HTTPException, it is a bit of too general but should work

vale wing
#

!d discord.Guild.ban check the raised exceptions

unkempt canyonBOT
#

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

Bans a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
vale wing
#

Forbidden is most likely raised when you have no ban perms, and HTTPException in most of other cases

#

Ig attempt to ban an administrator is HTTPException

#

Why interaction.response.send_message when you can just interaction.send

#

Those brackets

#

Why do you need the followup tho

#

Oh this doesn't exist in dpy

#

Bad

#

Maybe wrong doc

#

I typically do it like inter.send()

#

It automatically handles everything

#

Again

#

Don't use interaction.response.send

#
await interaction.send(...)```
Or as @slate swan said
```py
await interaction.followup.send(...)```
#

Oh

slate swan
#
project = user.connect_project(project_id=673805769, access_unshared=True)  # Connect a Project

tw_cloud = project.connect_turbowarp_cloud(
    username="Username")  # Connect the Turbowarp cloud with an optional parameter to change the username!

tw_cloud.set_cloud_variable(variable_name="Name", value=0)  # Set a Turbowarp variable

tw_cloud.get_variable_data()
```im making a discord bot but cant get this import to work its called scratchconnect i keep getting errors
#
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 47)
vale wing
#

Yes and also keep only critical statements in "try" for better code readability (the critical statement is kick)

heady sluice
#

(and you're not banning the user, just kicking him)

vale wing
#

Just bring the print and send outside

heady sluice
#

last line launches even if the ban failed

#

I'm dumb

#

missed the returns

sullen shoal
vale wing
#

^

vale wing
#

Last time I tried it failed

#

But I did that like > 1 year ago

sullen shoal
#

maybe not as keys

#

let me just check

vale wing
#

!e py from json import dumps d = {30: "stuff", 59: "yes"} a = dumps(d) print(a)

unkempt canyonBOT
#

@vale wing :white_check_mark: Your eval job has completed with return code 0.

{"30": "stuff", "59": "yes"}
vale wing
#

@sullen shoal see it automatically converts non string keys to strings

#

JSON keys must be strings

sullen shoal
#

!e py from json import loads d = '{30: "stuff", 59: "yes"}' a = loads(d) print(a)

unkempt canyonBOT
#

@sullen shoal :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 |   File "/usr/local/lib/python3.10/json/__init__.py", line 346, in loads
004 |     return _default_decoder.decode(s)
005 |   File "/usr/local/lib/python3.10/json/decoder.py", line 337, in decode
006 |     obj, end = self.raw_decode(s, idx=_w(s, 0).end())
007 |   File "/usr/local/lib/python3.10/json/decoder.py", line 353, in raw_decode
008 |     obj, end = self.scan_once(s, idx)
009 | json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
sullen shoal
#

oops, yeah

#

only in lists then

vale wing
#

"JSON keys are on the left side of the colon. They need to be wrapped in double quotation marks, as in "key", and can be any valid string. Within each object, keys need to be unique."

sullen shoal
#

yep, im sorry as well, i was confused with dicts and json

lofty rock
#

is there a way i can check if a message is sent by a bot or webhook?

unkempt canyonBOT
#

property bot```
Equivalent to [`User.bot`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.bot "discord.User.bot")
#

is_system()```
[`bool`](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)"): Whether the message is a system message.

A system message is a message that is constructed entirely by the Discord API in response to something.

New in version 1.3.
lofty rock
#

thx

serene lynx
#

why does my bot respond 2 times?, that's me running through local host

heady sluice
#

what if

#
@bot.listen()
async def on_message(message):
    await bot.process_commands(message)
supple thorn
serene violet
#

hei i want to make a discord bot that icks a user from the server after a certan amout of time, is that possible and where would i start

crimson compass
#
 role = message.guild.get_role(903973565152526376)
        if role in message.author.roles:
```you know how i can do this with permissions?
#

to check if he has a permission

supple thorn
slate swan
#

Traceback (most recent call last):
File "main.py", line 17, in <module>
from cogs.AntiChannel import AntiChannel
File "/home/runner/BoilingHopefulDiskdrive/venv/lib/python3.8/site-packages/cogs/init.py", line 7, in <module>
from .shell import Shell, ArgDsc, OptDsc, Failure
File "/home/runner/BoilingHopefulDiskdrive/venv/lib/python3.8/site-packages/cogs/shell.py", line 276
except (Failure, IOError, KeyboardInterrupt), exc:
^

supple thorn
#

!d discord.ext.commands.has_permissions

unkempt canyonBOT
#

@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/master/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/master/api.html#discord.Permissions "discord.Permissions").

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

Forgot the damn s

crimson compass
tough notch
#

!d help

unkempt canyonBOT
#

help([object])```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).

This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
slate swan
#

Traceback (most recent call last):
File "main.py", line 17, in <module>
from cogs.AntiChannel import AntiChannel
File "/home/runner/BoilingHopefulDiskdrive/venv/lib/python3.8/site-packages/cogs/init.py", line 7, in <module>
from .shell import Shell, ArgDsc, OptDsc, Failure
File "/home/runner/BoilingHopefulDiskdrive/venv/lib/python3.8/site-packages/cogs/shell.py", line 276
except (Failure, IOError, KeyboardInterrupt), exc:
^
SyntaxError: invalid syntax

supple thorn
#

The comand will work else it'll throw a MissingPermissions error

#

Hello kayya

#

Pog you said full name

slate swan
#

@slate swan can you this for me please?

#

I can give you the invite link

supple thorn
slate swan
#

Can you check error

supple thorn
#

He has

slate swan
#

Still not working

#

Ok dm

unkempt canyonBOT
#

Pasting large amounts of code

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

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

slate swan
#

There

supple thorn
#

Prefer?

slate swan
supple thorn
#

Lmao

slate swan
#

Just click

supple thorn
#

Says no and yet stll sends the link

slate swan
supple thorn
slate swan
#

Bruh

#

I just want check codes are working or not

#

Ok

supple thorn
slate swan
#

Ok

blissful sparrow
#

is it possbile to check if a user is_owner OR has a certain permission to execute a command?

unkempt canyonBOT
#

@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the person invoking this command is the owner of the bot.

This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.is_owner "discord.ext.commands.Bot.is_owner").

This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
blissful sparrow
#

I got that bit, but if I add @commands.is_owner wont it stop the @commands.has_permissions()?

#

or will they run simultaneously?

hasty bison
#

how can i make it so that a new voice channel will be created if a user joins a specific voice channel?

hushed galleon
#

no there's the check_any decorator to combine both conditions

blissful sparrow
#

yikes how would I implement that

hushed galleon
#
@commands.check_any(
    commands.is_owner(),
    commands.has_permissions(...)
)```
blissful sparrow
#

Oh doesnt seem too bad then

#

thanks

hushed galleon
#

if one or more are true then it passes, and if both fail then a CheckAnyFailure is raised

unkempt canyonBOT
#

discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") joins a guild.

This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
hushed galleon
#

if they're in <5 guilds or something like that

#

ah its documented in create_guild,

Bot accounts in more than 10 guilds are not allowed to create guilds.

blissful sparrow
slate swan
#

C:\Users\suraj\Music\dark-sec>python main.py
Traceback (most recent call last):
File "C:\Users\suraj\Music\lark-sec\main.py", line 14, in <module>
from dotenv import load_dotenv
ModuleNotFoundError: No module named 'dotenv'

C:\Users\suraj\Music\lark-sec>

hushed galleon
#

^ you're missing the python-dotenv package

blissful sparrow
hushed galleon
#

hm that should have been wrapped inside a CheckAnyFailure though

#

can you show the code for your command

unkempt canyonBOT
#

Hey @slate swan!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

blissful sparrow
# hushed galleon can you show the code for your command
@commands.command()
    @commands.check_any(
        commands.is_owner(),
        commands.has_permissions(administrator=True)
        )
    async def purge(self, ctx, num):
        try:
            num = int(num)
        except:
            embed = discord.Embed(title=':no_entry: Error Purging!', description='Please input a valid number.\n(`.purge` `<number>`)')
            return
        await ctx.message.delete()
        deleted = await ctx.channel.purge(limit=num, check=lambda msg: not msg.pinned)
        reply = await ctx.send(":bomb: Deleted {} message(s)".format(len(deleted)))
        await reply.delete(delay=10)
unkempt canyonBOT
#

Hey @slate swan!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

slate swan
#

Wht

blissful sparrow
#

The bot even says it

slate swan
#

.txt

blissful sparrow
#

oh wait i may be trying the wrong command is why

hushed galleon
#

o lol

blissful sparrow
#

Ye that worked lmfao, sorry for wasting your time

slate swan
#

Wht?

#

@blissful sparrow ?

blissful sparrow
#

paste to there brainlet

slate swan
blissful sparrow
#

Ive not modified it

slate swan
#

mhm

blissful sparrow
#

his nuke command is amazing as well, it nukes the channel whilst keeping pinned messages

#

posts them as a webhook

crimson compass
#
@client.command()
async def say(ctx, message=None):
    if message.author.guild_permissions.administrator:
        await ctx.send(message)
    else:
        await message.channel.send('**__Access denied for this commands.__**')
blissful sparrow
#

I was just testing a kick command in my friends server without permissions, and when I tried to use the kick command it says discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions is this to prevent abuse?

#

i used the @commands.check_any()

slate swan
slate swan
spice adder
#

Is it possible to kick a user from a guild on ban in another guild?

maiden fable
#

Yea

crimson compass
maiden fable
#

As long as the bot is in both the servers

hushed galleon
maiden fable
pliant gulch
#

Non-documented features as in private/internal methods?

#

Wouldn't they just document them later?

#

If it's exposed API

magic ore
#

CommandTree is documented

pliant gulch
#

I mean, if you decide to use something that's in alpha, isn't that pretty much on you?

slate swan
#

hi so im working on a bot with some ppl and we encountered a warning that we are not aware of
we dont really know if this warning is an issue or not but we were worried so we tried finding solution

main.py:17: RuntimeWarning: coroutine 'Command.__call__' was never awaited
  print("BOT ONLINE XD")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

the code near line 17:

15. @bot.event
16. async def on_ready():
17.   print("BOT ONLINE XD")
18.   await bot.change_presence(activity=discord.Game(name="P.help | Phizo"))

we tried googling it but we are unable to find the solution

wicked atlas
slate swan
blissful sparrow
#

So in my kick command, Im trying to get the bot to display the kicked user's avatar as the thumbnail, when I do like this is gives an error

embed.set_thumbnail(member.avatar)

what am i doing wrong?

wicked atlas
spice adder
blissful sparrow
#
    @commands.command()
    @commands.has_permissions(kick_members=True)
    async def kick(self, ctx, member: discord.Member, *, reason=None):
        if reason==None:
            reason=" No reason provided"
        
        embed = discord.Embed(title=':White_check_mark: Successfully Kicked!', description=f'{member.display_name} has been kicked. Reason: `{reason}`.', color=0xff0000)
        embed.set_thumbnail(url=member.avatar.url)
        embed.set_footer(text="Requested by: {}".format(ctx.author.display_name), icon_url=ctx.author.avatar)
        await ctx.send(embed=embed)
        await ctx.guild.kick(member)
blissful sparrow
#

no they removed that in dpy 2.0

#

i think its member.avatar

wicked atlas
#

are you in 2.0?

blissful sparrow
#

ye

#

I installed it yesterday

wicked atlas
#

If the user does not have a traditional avatar, None is returned. If you want the avatar that a user has displayed, consider display_avatar.

#

use member.display_avatar

arctic gyro
#

Hi , can anyobody pls tell me how to import Buttonstyle

maiden fable
#

from discord import ButtonStyle

blissful sparrow
#

Whats do u call for a user's name to display their name and tag?

arctic gyro
blissful sparrow
torn sail
blissful sparrow
#

Ah ok thanks

#

How would i use in the case of an f string

arctic gyro
blissful sparrow
#

Capital s on style

arctic gyro
#

I put a capital s on style only

#

but its still showing this in the console

slate swan
#

then you didnt save the file

arctic gyro
#

im on replit

heady sluice
#

who would've thought

torn sail
slate swan
#

How to get user id from username in discord py

torn sail
#

Use a converter then get id

#

!d discord.ext.commands.UserConverter.convert

unkempt canyonBOT
#

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

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError") derived exception as it will properly propagate to the error handlers.
lofty tinsel
#

Hi, I would like to know how to take a random name from a text file containing many names.
Do a command >name and the bot will choose a random name from the file. I know how to open a file etc but to choose a random data I don't know

heady sluice
#

random_name = random.choice(file.readlines())

lofty tinsel
#

just this line is enough?

heady sluice
#

it chooses a random line from the read lines of the file

lofty tinsel
#

hmmm understand

#

I'll try

#

ty bro

slate swan
torn sail
#

commands.UserConverter().convert(ctx, “some name”)

torn sail
slate swan
#

Can bot delete a channel?

For example:
If I used this code to create a channel
await create_channel(name)

And then I want to delete the same channel the bot just created in this command
Is this possible?

torn sail
slate swan
#

@torn sail

torn sail
slate swan
#

displaying entered username 💀

lofty tinsel
#

i dont understand the error line31

torn sail
# slate swan

Do member = commands.MemberConverter().convert(ctx, “name”) then get the id with member.id

slate swan
slate swan
#

tysm

#

!d discord.Guild.get_member_named

unkempt canyonBOT
#

get_member_named(name, /)```
Returns the first member found that matches the name provided.

The name can have an optional discriminator argument, e.g. “Jake#0001” or “Jake” will both do the lookup. However the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work.

If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not lookup the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique.

If no member is found, `None` is returned.

Changed in version 2.0: `name` parameter is now positional-only.
slate swan
#

🙂

lofty tinsel
slate swan
#

..

slate swan
lofty tinsel
#

ik but before Can u help me to chose one name randomly?

slate swan
lofty tinsel
#

done

blissful sparrow
#

Is there a way to mute members using timeout? I can't find when searching the documentation. It being up the heartbeat timeout stuff

slate swan
blissful sparrow
#

Dpy 2

slate swan
#

!d discord.Member.timeout

unkempt canyonBOT
#

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

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").

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

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

exists

lofty tinsel
#

i did the command in discord and i have this error

#
file = open('ListTagsChecked.txt', 'r')

@client.command(name="4gen")
async def four_gen(ctx):
    random_tag = random.choice(file.readlines())
await ctx.send(random_tag)
gilded zephyr
#

Hey so I have a hex color as a string: "ffffff"
How do I turn it into a color? Ex: 0xffffff

scarlet aurora
#
    @commands.Cog.listener("on_command_error")
    async def error_h(self, ctx: commands.Context, exc):
        if isinstance(exc, ErrorClass): 
            print("error")
        elif isinstance(exc, ErrorClass):
            print("error2")``` How do I define ErrorClass ??
gilded zephyr
lofty tinsel
#

what this error means?

slate swan
#

!d discord.ext.commands.MemberNotFound like this one

unkempt canyonBOT
#

exception discord.ext.commands.MemberNotFound(argument)```
Exception raised when the member provided was not found in the bot’s cache.

This inherits from [`BadArgument`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BadArgument "discord.ext.commands.BadArgument")

New in version 1.5.
scarlet aurora
#

sys.pycache_prefix what does this do?

final iron
#

!d sys.pycache_prefix

unkempt canyonBOT
#

sys.pycache_prefix```
If this is set (not `None`), Python will write bytecode-cache `.pyc` files to (and read them from) a parallel directory tree rooted at this directory, rather than from `__pycache__` directories in the source code tree. Any `__pycache__` directories in the source code tree will be ignored and new .pyc files written within the pycache prefix. Thus if you use [`compileall`](https://docs.python.org/3/library/compileall.html#module-compileall "compileall: Tools for byte-compiling all Python source files in a directory tree.") as a pre-build step, you must ensure you run it with the same pycache prefix (if any) that you will use at runtime.

A relative path is interpreted relative to the current working directory.
silver burrow
#

hello, how i can use this event, without creating another ( i already have 1 event )

async def on_member_join(member):
    channel = alfred.get_channel(790274325533378682)
    embed=discord.Embed(title="Welcome!",description=f"{member.mention} Just Joined")
    await channel.send(embed=embed)```
slate swan
#

what

#

@bot.event, and alfred.get_channel
what's alfred there?

vale wing
#

!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/master/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...
boreal ravine
lofty tinsel
#

it's good I succeeded it didn't come from there I forgot encoding utf8

blissful sparrow
lofty tinsel
#

how to fix this error:

#
Command raised an exception: IndexError: Cannot choose from an empty sequence```
#
file = open('ListTagsChecked.txt', 'r', encoding='utf8')

@client.command(name="4gen")
async def four_gen(ctx):
    random_tag = random.choice(file.readlines())
    await ctx.send(random_tag)
    embed = discord.Embed(title="TAG GENERATOR v1.0", colour=0x298FE3)
    embed.add_field(name="\u2800", value=f"├ #️⃣TAG ➝ {random_tag}\n├ 📝Name ➝ ...\n├ 🏡TownHall ➝ ...")
    await ctx.send(embed=embed)
#

this is the code I'm using

torn sail
#

Is it possible to make a role icon the emoji in a select menu or can it only be an emoji?

cloud dawn
#

Capital M

#

It's a class

unkempt canyonBOT
cloud dawn
#

!d discord.Member.unban

unkempt canyonBOT
#

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

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

!d kivy

unkempt canyonBOT
#

Kivy is an open source library for developing multi-touch applications. It is cross-platform (Linux/OSX/Windows/Android/iOS) and released under the terms of the MIT License.

It comes with native support for many multi-touch input devices, a growing library of multi-touch aware widgets and hardware accelerated OpenGL drawing. Kivy is designed to let you focus on building custom and highly interactive applications as quickly and easily as possible.

With Kivy, you can take full advantage of the dynamic nature of Python. There are thousands of high-quality, free libraries that can be integrated in your application. At the same time, performance-critical parts are implemented using Cython.

See http://kivy.org for more information.

cloud dawn
# unkempt canyon

Whom ever is spamming reactions, it gets you rate limited pretty easy.

dull terrace
#

is there a way to make a slash command that is only visible to me?

cloud dawn
dull terrace
#

froggy_chill specific channel?

dull terrace
#

pretty annoying if you wanna make moderation controls on the bots main server

cloud dawn
#

Just a guild.

dull terrace
#

can restrict it so only i can use it but still messy

slate swan
#

But u can run ur slash command in ur bot's dms

cloud dawn
slate swan
torn sail
dull terrace
torn sail
#

but it will just be grayed out

torn sail
#

users will be able to see all commands

slate swan
dull terrace
#

i like having a moderation channel that people can view but not send messages in froggy_chill

#

that way they can see stuff like whos getting banned but i guess i can reroute messages and stuff if i really wanted

stiff nexus
#
    async def on_error(self, error: Exception, item: discord.ui.Item, interaction: discord.Interaction) -> None:
        if interaction.response.is_done():
            await interaction.followup.send(f'{utily.error} An unknown error occurred.\n**Error:** {error}', ephemeral=True)
        else:
            await interaction.response.send_message(f'{utily.error} An unknown error occurred.\n**Error:** {error}', ephemeral=True)
        raise error
``` not working 
like i am getting error but its not sending it
cloud dawn
torn sail
cloud dawn
final iron
#

!d random.choice

unkempt canyonBOT
#

random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
lofty tinsel
#

you know why the command is done only once and after that puts this error message?

slate swan
lofty tinsel
lofty tinsel
hoary cargo
#

is the file empty? 🗿

lofty tinsel
#

no

slate swan
# lofty tinsel no

dunno what's causing the issue then tbh, you should try running the command again

maiden fable
lofty tinsel
#

idk I can't try rn i dont have my computer

cloud bison
#

Can I get message object in view class?

oblique adder
#

how do I disable all 5 buttons if 1 of them have been clicked ?

heady sluice
#

.

oblique adder
heady sluice
#

yes

cloud bison
#

I mean I have command that has button to delete a message elsewhere with the message id but i can't get the message object in view class with id

heady sluice
#

and you have to edit the message

#

with the new edited view

minor totem
# maiden fable Can u print `file.readlines()`?

Oh wow there's little activity here.. anyways the issue is that after the first time, reading more from the file is reading from its end so to Python the file might as well be empty. You need to add .seek(0)

oblique adder
oblique adder
maiden fable
heady sluice
#

yeah it's not an instance, it's a class

maiden fable
unkempt canyonBOT
#

stop()```
Stops listening to interaction events from this view.

This operation cannot be undone.
heady sluice
#

you should've made something like my_view = ShopButton()

#

then in your command or dunno, await ctx.send(view=my_view)

#

and you can edit the buttons through

for button in my_view.children:

or, if in the view,

for button in self.children:
cloud bison
#

yeah but if I use this i'll delete the button message but that's not what I want

desert pilot
#

Anyone help, I’m tryna do a python discord bot and getting this error when doing the command

sick birch
# cloud bison Can I get message object in view class?
class MyView(ui.View):
  ...
  def some_function(self):
    print(self.message.id) # You can access message inside the view subclass

@bot.command()
async def my_command(...):
  view = MyView()  
  view.message = await ctx.send(view) # this is important!
sick birch
silent ridge
#

what am I doing wrong/

sick birch
slate swan
#

bro

sick birch
#

is that valid

silent ridge
#

@sick birch I am getting this right now

sick birch
#

Well

slate swan
#
def a
    puts "bro"
end
a
sick birch
#

"'Await' outside function"

slate swan
#

😏

sick birch
#

I don't think it could be any more clear

silent ridge
#

oh wait, it is ctx instead of xtx

#

lmao, srry

sick birch
#

That's not the issue

#

The issue is using await outside of asynchronous functions (coroutines)

silent ridge
#

I can't code 😭 , thats the problem

#

just copied a yt video, but doesnt work

sick birch
#

Youtube videos for discord.py suck, I don't know how they keep getting away with terrible code

silent ridge
#

How did u learned coding?

sick birch
#

Me? I learn by doing, not by following tutorials

#

That might not work for everyone however

silent ridge
#

but how can u start doing when u have no idea what u should do

sick birch
#

many people learn by making discord bots, which is a fantastic way to learn

sick birch
unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

sick birch
silent ridge
#

is there also a documentation for giveaway bots?

sick birch
#

Documentation outlines what functions and classes do

#

You need to compose said functions and classes to make cool things

slate swan
#

learn some basic python before trying to make a bot or you'll get confused very quickly

sick birch
#

Giveaway bots aren't that hard. I've made plenty in my time, I have faith you'll get it as well :)

silent ridge
#

alright, will look into it! Thanks guys. Doing this to learn myself coding discord bots for nft servers haha

sick birch
#

I believe that videos are inherently flawed in terms of medium

sick birch
silent ridge
#

😎 , speek to you soon! 👊

sick birch
sick birch
silent ridge
#

❤️

slate swan
sick birch
#

Is this not working?

#

It LGTM

stuck oyster
stuck oyster
sick birch
#

The code itself looks good to me

junior verge
#

Yeah looks fine

sick birch
#

Are you getting any errors?

stuck oyster
#

I was doing it wrongly

slate swan
#

why does it use a {0}?

#

this is from the documentation^

junior verge
#

Python 0 is an indicator of the format method that you need to be replaced by the format’s first (index zero) parameter. It is used to execute a string formatting operation. The formatted string argument contains a literal text or replacement fields delimited by braces { }.

#

No clue lol

sick birch
slate swan
#

how can i make a per send embed message it count? like this

slate swan
sick birch
unkempt canyonBOT
#

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

Hello, my name is John Doe, and I am 42 years old.
sick birch
#

As opposed to

first_name = "John"
last_name = "Doe"
age = 42

print("Hello, my name is {0} {1}, and I am {2} years old.".format(first_name, last_name, age))
slate swan
#

ahhh! I get it thansk

#

ayo this is fun

sick birch
#

Indeed it is!

slate swan
#

😄

slate swan
sick birch
#

On what you're counting

slate swan
sick birch
slate swan
#

Aight thanks !

dull terrace
#

what would be the best way to check if a number is in a constant changing range of numbers i.e.

if number in range(0, 10):
if number in range(100, 110):
if number in range(200, 210):```
sick birch
#

Can we get some context?

dull terrace
#

trying to get a map to generate an image at a steady rate but not all the time

#

so every 100 levels they see x

#

for 10 levels

#

without having to save data would be best, but the maths is

#

if number in range 0,210 would generate the image for 0 to 210

#

i want it every time they hit a multiple of 100 for 10 levels or similar

unkempt canyonBOT
#

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

001 | 0 10
002 | 100 110
003 | 200 210
004 | 300 310
005 | 400 410
006 | 500 510
007 | 600 610
008 | 700 710
009 | 800 810
010 | 900 910
dull terrace
desert pilot
dull terrace
#
for i in range(0, 1000, 100):
    if i + 10 > map_level > i:```
this works but it's an infinitely generating map
#

so it would have to in theory check from 0, infinity

#

i could divide it by 100 and then use the remainders

#

if map_level % 100 < 10:

#

would this work suspicious

#

that would require saving counts for every player

slate swan
#

@slate swan how can u type that with these colors

#
count = 0
while True:
    if number in range(count, count+10):
        ...
    count += 100```
pliant gulch
#

Checking it in a range would be pretty in-efficient though right?

dull terrace
#

i think the remainder system will work if im not being dumb

slate swan
#

!e

for i in range(0, 1000, 100):
    print(i, i+10)```
pliant gulch
#

Wouldn't it be best to do if 0 < n < 10:

unkempt canyonBOT
#

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

001 | 0 10
002 | 100 110
003 | 200 210
004 | 300 310
005 | 400 410
006 | 500 510
007 | 600 610
008 | 700 710
009 | 800 810
010 | 900 910
dull terrace
#

100/100 = 0, 100/101 = 1 and 1 left over etc.

#

so if map_level % 100 < 10

#

should work right suspicious

#

ill test it with smaller numbers

#

yeah it works

unkempt canyonBOT
#

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.

slate swan
#
print('Hello world!')
#

damn, sheeesh didnt knew that

junior venture
#

How do I enable the message content intent?

final iron
unkempt canyonBOT
#

Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:

• The message was sent by the client

• The message was sent in direct messages

• The message mentions the client

This applies to the following events...

vale wing
sick birch
#

It's off by default

vale wing
#

And it will be enforced since august 31

sick birch
#

So unless you turn it on you won't get message content

#

Even for bots in < 75 guilds

vale wing
#

Well I don't have that intent on in disnake (because of some inner disnake errors) and I can still receive messages content

sick birch
#

I meant on the dashboard

vale wing
#

Oh

#

So you have to enable it on dashboard but don't have to tell the gateway you need events with that intent?

sick birch
#

You have to do both

#

.default() includes it I think

vale wing
#

Oh wait I confused something

#

I am using it forget it

slate swan
#

Is there anyone to help?

sick birch
slate swan
sick birch
#

I'm not seeing how that's related to discord bots

slate swan
#

server.py:688: DeprecationWarning: There is no current event loop
asyncio.get_event_loop().run_until_complete(start_server)

sick birch
slate swan
#

server.py:689: DeprecationWarning: There is no current event loop
asyncio.get_event_loop().run_forever()

sick birch
junior verge
#
with open('logs.json', 'r') as f:
      log_channels = json.load(f)

@client.command(name="logchannel", aliases=["setlog","setlogchannel"],description="Sets the log channel for your server logs")
@commands.has_permissions(administrator = True)
async def modlog(ctx, channel = None):
  log_channels[str(ctx.guild.id)] = channel.split()
  with open('logs.json', 'w') as f:
    json.dump(logs.json, f)
  await ctx.send(f'Log channel set to {channel}')
``` anything wrong with this?
sick birch
#

Hard to tell; any errors?

junior verge
#

Yeah one like I've never seen it before

sick birch
#

Let's see it

junior verge
#

It's HTML code lol look

junior venture
#

Should I do pip install discord or pip install discord.py?

junior verge
#

Both work

sick birch
junior verge
junior verge
sick birch
#

You're getting ratelimited

junior verge
#

oh

#

On what and why

sick birch
#

Are you using replit or heroku?

junior verge
#

Replit atm

sick birch
#

makes sense

#

Replit is terrible, get off it

junior verge
#

I mean theres no other way for me right now to do it, I was using heroku but I just want to use json files for some things

#

I don't understand databases that well yet

junior venture
sick birch
#

Why not just do it locally?

junior verge
#

Won't run 24/7

junior verge
sick birch
#

Hm, look into free tiers of reputable service providers like like AWS then

sick birch
junior verge
#

I mean I know replit is just bad but yeah

sick birch
junior verge
#

How do they work with discord bots?

sick birch
#

Install python on them, and run the python file like you would normally

junior venture
#

How do I update from 1.7.3 to latest?

sick birch
#

That's what I'm doing at the moment

junior verge
#

So also json files work on that

sick birch
#

Well, i'm using docker but same concept

sick birch
#

They're just regular computers in the cloud that you can "rent"

vale wing
junior verge
#

Ah nice

sick birch
#

It's a regular computer like any other, it has an OS and everything you need

vale wing
#

If you need a guide on VPS setup for hosting discord bots I can give you one

sick birch
#

I'm using t3.small

sick birch
#

AWS interface isn't the most intuitive but you'll get it

vale wing
sick birch
vale wing
#

Choose ubuntu when selecting AMI or smth

sick birch
sick birch
#

amazon linux sucks

sick birch
#

I'm not all that big on devops and I'm rubbish with devops tools

vale wing
junior venture
#

How do I update from 1.7.3 to latest?

junior verge
#

I'm going to a uni with the name: expert it systems and devices, pretty cool

vale wing
#

Ty 👍

sick birch
#

Maybe you can make one for docker too

vale wing
#

That would require some explanation about docker

junior verge
boreal ravine
vale wing
#

Shortly: google "git", go to git website, find download tab, download and install

junior venture
sick birch
#

Of course

junior verge
vale wing
#

Yes

#

Imho aws interface is aids

sick birch
#

yeah

#

you need to create a new instance, pick the specs, that sort of stuff

#

making security groups

#

all that fun stuff

junior verge
#

So it's basicaly just a vps?

sick birch
#

Not really

vale wing
#

Find EC2 -> instances -> new instance -> ubuntu -> t2.micro -> skip to the end -> launch instance

#

I think that

junior verge
sick birch
#

AWS is one of the largest hosting providers in the world, with over 200+ services

#

Some of the largest companies use them which explains the terrible interface for regular users

#

You figure out how to find your way around soon enough though

sick birch
junior verge
#

Uh im on my laptop rn do I gotta be on pc

vale wing
#

Digitalocean has good interface but you can use it for free only for 2 months

sick birch
vale wing
#

Tho you can get a very good server

junior verge
#

I don't have my code here tho

sick birch
#

that's fine just set it up and do the code later

junior verge
#

Sure, let me try and do it

sick birch
#

iirc they give you 700 hours of t2.micro instances every month

junior verge
#

That should be enough

sick birch
#

That's about how many hours are in a month so they're effectively locking you into only using one instance

vale wing
#

You can expand its 8gb volume as well

#

Still will be free I think

sick birch
vale wing
#

8gb is very little

sick birch
#

Since most of the components of an instance are isolated

slate swan
#

can u invoke a slash command inside code

sick birch
#

for example you have to allocate an elastic IP and associate it to your instance

junior verge
#

I need to add a billing adress...

sick birch
slate swan
#

Alright

vale wing
junior verge
#

I mean I don't have that, I'm 15.

sick birch
junior verge
#

I got my dutch bank but they don't accept that

sick birch
#

That's unfortunate

vale wing
#

Why tho

junior verge
#

Why what

vale wing
#

They should accept your bank

sick birch
#

Your billing address, as in your credit card info?

junior verge
#

I don't have a credit card

vale wing
#

Afaik only USA has address card verification

vale wing
sick birch
#

If you stay below the limit they won't bill you anyway

junior verge
#

Is there any other way?

vale wing
sick birch
#

Most decent hosts will require it

junior verge
#

I'm just stuck with my heroku

sick birch
#

very unfortunate

junior verge
#

I like want custom log channel but I just don't know how to do that, and with mongodb you can only use 1 database

sick birch
#

A logging feature isn't that hard, I have one for my bot

#

though it uses postgres

#

the data model is pretty different

junior verge
junior verge
sick birch
#

Me neither. I usually just feed the connection URL into an ORM like prisma and it handles everything for me

#

Actually that's exactly what I did for my bot

junior verge
#

I just got no clue what to do

sick birch
#

Replit won't let you set up an sql server so you have to figure out how to get that in heroku

junior verge
#

With heroku I don't use replit

#

I just use visual studio code with git connected to my repository

junior verge
sick birch
#

Not that I know of. I've never used heroku, thankfully

junior verge
#

It works fine

#

What

slate swan
junior verge
#

Well, got any idea for me on how to do what I want

slate swan
#

whats ur issue?

sick birch
junior verge
slate swan
#

im not really using await ctx.invoke

sick birch
#

That's for text commands

#

You can't invoke slash commands from within your code

slate swan
#
async def coolCallback(ctx, a, b):
  s = a + b
  await ctx.respond(f"Like bro, {a} + {b} is {s}.")

@bot.slash_command()
async def functionOne(ctx, a: int, b: int):
  await coolCallback(ctx, a, b)

@bot.slash_command()
async def functionTwo(ctx, a: int):
  b = a * 2
  await coolCallback(ctx, a, b)
``` eexample and id just share the results of coolcallback
sick birch
#

Ah you're taking that approach

slate swan
#

Is their something wrong with it?

sick birch
#

I thought you actually wanted to call the slash command from discord

vale wing
#

Why not just call command function from a command and parse interaction manually to there (that's weird but works)

desert pilot
#

I don’t have a ss but in getting the error on my bot now of get_config after using the command

#

I’m not on laptop rn so can’t ss

slate swan
junior verge
vale wing
#

Idk what library you use

sick birch
junior verge
#

I mean like both yeah, with using heroku it must be a online database

slate swan
#

google cloud should be better than heroku

vale wing
#

😳

sick birch
#

anything is better than heroku

slate swan
#

even leaving your pc on all night?

sick birch
slate swan
#

replit hacker plan is

junior verge
sick birch
#

i do that a lot

slate swan
#

replit hacker plan is 24/7 running code

junior verge
#

What should I use to host my bot then for free

sick birch
slate swan
#

its only 2$

junior verge
#

without billing adress

slate swan
#

their isnt much

sick birch
#

Heavy initial investment but worth it over time

junior verge
#

How then host on it lol

sick birch
#

The one I got was $120 but I'm pretty sure some of the older models are ~ $40

vale wing
#

You can do other stuff to it as well

sick birch
junior verge
#

Yeah I was planning on buying one

#

Just for other fun stuff too, just to play around with it

sick birch
#

for sure

vale wing
#

In summer I am gonna build a server from my old motherboard and host bots there

junior verge
sick birch
#

Upload your bot files to github, install github on raspberry pi, then git clone

vale wing
#

If you install ubuntu to it that guide would still be suitable

junior verge
#

With a rasberry pi you connect it with a usb to your pc right?

sick birch
#

no need

#

You can ssh onto it

junior verge
#

What's that?

sick birch
#

secure shell

#

It's a way to log in to other computers over the network

junior verge
#

Oh from your pc?

vale wing
#

Basically connecting to the server, executing commands and receiving their output

sick birch
#

Say your raspberry pi had an internal ipv4 of 192.168.1.69, you can log onto using the following command:

ssh root@192.168.1.69
#

From there you have access to the raspberry pi's root account

junior verge
#

Seems hard

sick birch
#

So you can do anything to it as if you physically had a keyboard and mouse hooked up to it

vale wing
sick birch
junior verge
sick birch
#

Or a laptop

junior verge
#

Oh yeah that seems obviously

#

And what do you plug then in your rasberry pi?

sick birch
#

Yeah you'd just boot up a terminal on your computer or laptop and use the ssh command to log into it

sick birch
junior verge
#

Not even ethernet?

sick birch
#

The newer ones have wifi

junior verge
#

ah

junior venture
#

Why do I receive this error when trying to use cogs (first time)?

  bot.load_extension(f'cogs.{filename[:-3]}')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
junior verge
#

Go for it Robin

sick birch
#

You need to await them now

junior venture
#

Oh ok

sick birch
#

Now your next question would probably be where, since you can't await outside async functions

#

The answer to that would be in the setup_hook which was introduced in 2.0 as well

junior venture
#

So what should I do for a fix?

sick birch
junior venture
#

Can't await outside of function.

elfin pagoda
#

just got raided by 661 accounts in a server i run, any simple code i can get just to grab all the user ids that joined between 2 timestamps? or perhaps you know of a bot already

sick birch
#

If so discord has a native prune feature

elfin pagoda
#

yeah they are

#

just mass dming people upside_down_smile_of_greatness

junior venture
elfin pagoda
sick birch
sick birch
unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @worn onyx until <t:1649630187:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 186 newlines in 10s).

junior venture
#

wdym, like this?

await bot.load_extension(f'cogs.{filename[:-3]}')
slate swan
#

yes its a coroutine

#
Traceback (most recent call last):
  File "/home/runner/tester/venv/lib/python3.8/site-packages/discord/ui/view.py", line 371, in _scheduled_task
    await item.callback(interaction)
  File "/home/runner/tester/cogs/rostermenu.py", line 23, in my_callback
    await getros(ctx,role=select.values[0])
  File "/home/runner/tester/roster.py", line 51, in rostercall
    await ctx.respond(embed=embed, ephemeral=True)
AttributeError: 'Context' object has no attribute 'respond'
```!?
#

the Context object doesnt have that attr

#

only Interaction

#

i tried interaction aswell

junior venture
#
    await bot.load_extension(f'cogs.{filename[:-3]}')
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: 'await' outside function
``````py
for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        await bot.load_extension(f'cogs.{filename[:-3]}')
slate swan
#

it needs to be in a coroutine

slate swan
# slate swan only Interaction
Traceback (most recent call last):
  File "/home/runner/tester/venv/lib/python3.8/site-packages/discord/ui/view.py", line 371, in _scheduled_task
    await item.callback(interaction)
  File "/home/runner/tester/cogs/rostermenu.py", line 23, in my_callback
    await getros(ctx,role=select.values[0])
  File "/home/runner/tester/roster.py", line 51, in rostercall
    await interaction.response.send_message(embed=embed, ephemeral=True)
AttributeError: 'Context' object has no attribute 'response'
``` getting this error for interaction
#

also if your wondering getros is a function

#

async def rostercall(ctx, *,role):

#

i am usig pycord, and im using it inside a dropdown menu command

#

alright

#

what is the hex code for colorless embeds

#

just dont add a color

#

thats not colorless

#

theres no such thing as a colorless embed

#

there is..

#

show

#

its called, same hex as discord background

#

which is what im asking for

slate swan
#

it seems odd to me

#

lmaoo

slate swan
#

bro, i know how embeds work. im asking for something specific. if you dont have it then as rude as it sounds move along :/

#

im not being rude?

#

i know, im just saying

#

ik what i want and ik its a thing, i just dk what the hex is

#

that still wont be invisible for all clients

#

ty

slate swan
#

idk about iphone

slate swan
pliant gulch
#

Modded client users trembling rn

slate swan
#

yeah

#

but who uses light theme ya know

#

me

#

jk😳

#

ew

#

light theme is a meme

slate swan
#

feels like an r6 flash bang

#

same bro

slate swan
#

Light theme is like this generations gore

#

@slate swan

#

top one i found on reddit, bottom is yours. i think its actually colorless

#

bro

#

look at the borders if u dont know what i mean

#

one is squary one is round

#

idk its weird

slate swan
slate swan
#

The embeds are so clean

#

embeds are cleaner in light mode for sure

cloud dawn
#

lmfao light and compact mode

slate swan
#

ik i see it but

#

How do you make the embeds so perfectly square??

#

imposter

balmy python
#

Hi

blissful sparrow
#
db = sqlite3.connect(bot.sqlite)
    cursor = db.cursor()
    cursor.execute('''CREATE TABLE IF NOT EXISTS main(
        guild_id TEXT
       guild_name TEXT
        )
        ''')

Gives me the error db = sqlite3.connect(bot.sqlite) NameError: name 'bot' is not defined

Im following a tutorial and I've done exactly what hes done but idk why its not working

sick birch
#

I hate to be blunt but most of them suck. The one you're following clearly does because they suggested you use sqlite3

blissful sparrow
#

what else would I use?

sick birch
#

The documentation

blissful sparrow
#

for a db I mean

sick birch
#

Oh, you'd use aiosqlite

wary hatch
#

how do i fetch the reactions on a single message? i tried fire_reactions = get(game_message.reactions, emoji=fire) but it always returns none for some reason

sick birch
#

Or aiohttp if you want to go for a RESTful graphql-like system

blissful sparrow
#

no Im keeping it local

sick birch
#

Then you'd use aiosqlite

blissful sparrow
#

bot will only be in 3 maybe 5 max servers

sick birch
#

I don't know why the youtuber thought it was a good idea to suggest using sqlite

unkempt canyonBOT
wary hatch
final iron
#

Then it has no reactions

wary hatch
#

well that can't be right cause i can see 2 reactions on it

final iron
#

Don't know what to tell you

#

The API doesn't lie

wary hatch
#

ah well thank you anyways

#

i'll keep testing stuff

#

would it matter if game_message = await ctx.send("blahblah")?

final iron
#

send() returns a message object

#

So if it had reactions it should still say so

blissful sparrow
#

Anyone able to help me setup a guild whitelist command where it puts the guild id in an aiosqlite db after using a command like .wlguild <guildid>

final iron
blissful sparrow
#

setting up the db, and not sure whether to define it globally or within each command that im going to do

#

this is my first time dabbling in dbs and python

#
@commands.command()
@commands.is_owner()
async def addwl(self,ctx, guild=str()):
  db = await aiosqlite.connect(guildwl.db)
  db.execute('''CREATE TABLE IF NOT EXISTS "guildwl"(
           "guils_ids"     INTEGER,
           "guild_name"    TEXT)
       );''')
  cursor= await db.cursor()
#

this is what i have rn

final iron
#

I see a few things wrong with this

#

Why are you calling str()?

#

db.execute() isn't awaited

blissful sparrow
final iron
#

Still don't need to be calling int

#

And why make it default to a data type?

#

Also I don't think what you posted is valid SQL

#

Don't take my word on that though, I haven't used it in a couple of months

#

Oh yeah, you should be using cursor (Your database cursor) to execute SQL code, not db (Your database connection)

visual island
final iron
#

So something like

db = await aiosqlite.connect("ma path")
cursor = await db.cursor()
await cursor.execute("my SQL code")
final iron
#

So what's the point of creating a cursor object?

wary hatch
#
                    fire = "🔥"
                    flop = "🗿"
                    game_message = await game_channel.send(
                        f"Is this pattern a {flop} or {fire}? Vote open for 2 minutes.")
                    await game_message.add_reaction(flop)
                    await game_message.add_reaction(fire)
                    await asyncio.sleep(1)
                    await game_channel.send("Vote over in 60 seconds.")
                    await asyncio.sleep(1)
                    await game_channel.send("Vote over in 10 seconds.")
                    await asyncio.sleep(1)
                    fire_reactions = game_message.reactions
                    flop_reactions = game_message.reactions

is there anything glaringly wrong about this snippet of code? game_message.reactions always returns [] even when i react to it before it checks the reactions

#

disregard the incorrect sleep times

visual island
final iron
#

Ah

#

I guess this is what I get from watching tutorials and not documentation

#

I do hate the aiosqlite documentation theme though. It's completely unreadable to me

blissful sparrow
#

now im more lost lol

#

I have no idea where to start with that since its my first time with sql in python

#

well i was using sqlite3 but someone said to use aiosqlite

#

so im using that now

#

or well...trying to

slate swan
umbral night
#
@client.event
async def on_command_error(ctx, error):
  if isinstance(error, commands.MissingRequiredArgument):
    await ctx.send('wrong command')

why doesnt this work?

strong vessel
#

why do you recommend PostgreSQL for discord bot?

#

thanks

cloud dawn
#

I mean sqlite is fine tough.

umbral night
#

thanks

cloud dawn
umbral night
#

all my other commands work fine

strong vessel
#

i'm avoiding advanced stuff, even the basics is too advanced for me atm

umbral night
#

no error in the ide, nothing happens in the channel

cloud dawn
umbral night
#

any?

#

all

cloud dawn
cloud dawn
umbral night
#

i thought itd work

cloud dawn
# umbral night idk

"Exception raised when parsing a command and a parameter that is required is not encountered."

cloud dawn
umbral night
#

say 'wrong command'

#

when i type an incorrect command

#

such as !asdiasdai

#

or idk

#

a typo

cloud dawn
#

Thats would raise

#

!d discord.ext.commands.CommandNotFound

unkempt canyonBOT
#

exception discord.ext.commands.CommandNotFound(message=None, *args)```
Exception raised when a command is attempted to be invoked but no command under that name is found.

This is not raised for invalid subcommands, rather just the initial main command that is attempted to be invoked.

This inherits from [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError").
strong vessel
#

thanks

umbral night
#

@cloud dawn

cloud dawn
umbral night
#

like this?

#

no

#

idk

umbral night
#

yes?

#

what

cloud dawn
# umbral night yes?

Well there you used the event and used isinstance to compare the 2 objects.
It's the same for this exception.

#

!d discord.ext.commands.Bot.on_command_error

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 prints to [`sys.stderr`](https://docs.python.org/3/library/sys.html#sys.stderr "(in Python v3.10)") 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.
cloud dawn
umbral night
#

is ext short for exception

umbral night
#

i have this

#

is this right?

cloud dawn
umbral night
#

oh

cloud dawn
cloud dawn
umbral night
#

do i have to import anything else

cloud dawn
# umbral night oh

async def on_command_error(ctx, error): you are already defining it here.

umbral night
#

ok

cloud dawn
#

And by the looks if it you do.

umbral night
#

oh

#

i got it

umbral night
slate swan
#

how long do slash commands take to sync

cloud dawn
slate swan
#

on bot startup or

cloud dawn
slate swan
#

ofc, does it take 1 hour from bot startup or

#

my bot hasnt been up for an hour

cloud dawn
slate swan
#

ye thats why, ill let it sync

umbral night
#
@client.event
async def on_message(msg : discord.Message):
  if msg.author.id == client.user.id:
    return
  if msg.content == 'owner':
    await msg.channel.send('@umbral night')
    await client.process_commands(msg)
#

so at the moment, whenever i say 'owner' it pings me

#

how could i make it so that when someone says 'the owner' or just includes the word 'owner' in their sentence, it'll also work?

#

im not sure how to do that

cloud dawn
#

Switch them

umbral night
#

wdym

cloud dawn
#

if 'owner' in msg.content:

#

!d in

unkempt canyonBOT
#
in

6.10.2. Membership test operations

The operators in and not in test for membership. x in s evaluates to True if x is a member of s, and False otherwise. x not in s returns the negation of x in s. All built-in sequences and set types support this as well as dictionary, for which in tests whether the dictionary has a given key. For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y is equivalent to any(x is e or x == e for e in y).

For the string and bytes types, x in y is True if and only if x is a substring of y. An equivalent test is y.find(x) != -1. Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True.

cloud dawn
#

!e ```py
p = [1, 2 ,3]

if 1 in p:
print("Yes 1 is in list p")

unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your eval job has completed with return code 0.

Yes 1 is in list p
umbral night
#

ah

#

thx

heavy folio
#

how do i check if an Asset is of a certain file format

cloud dawn
slate swan
#

and how can i get total number of members in all the guilds my bot is in?

cloud dawn
heavy folio
#

ah

#

idk if there's any other ways
im trying to make an avatar cmd and if the member's avatar is animated, it'll format the avatar url to a jpg
and for static avatars it'll format it to be a png (just an example)

cloud dawn
unkempt canyonBOT
#

is_animated()```
[`bool`](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)"): Returns whether the asset is animated.
heavy folio
#

oo

slate swan
#
time = datetime.now()
time = time + timedelta(minutes=30)

in this code i want the (minutes=30) to be user input meaning that the amount of time to be added can be user input

green bluff
#

excuse me but why is my db locking for such a simple command

#

i literally did ;setup and it locked the db

#

all my command does is insert ONE SINGLE value

slate swan
#

wouldnt even work

cloud dawn
#

After using it does one of the 2 messages appear?

slate swan
#

you arent committing the changes

green bluff
#

oh TEA

slate swan
green bluff
#

oh yea ty i was dumb

slate swan
#

👍

cloud dawn
slate swan
cloud dawn
# slate swan yes

You could just have a var for the int and add an arg to the command

cloud dawn
#

pg doesn't even have commit it just does it lol

slate swan
#

i see nothing about it in docs

umbral night
#
@client.event
async def on_message(msg : discord.Message):
  if msg.author.id == client.user.id:
    return
  if msg.content == 'owner':
    await msg.channel.send('@umbral night')
    await client.process_commands(msg)

why does this make all my other commands not work?