#discord-bots

1 messages · Page 987 of 1

dull terrace
#

stack overflow, the ultimate teacher

slate swan
#

VOUCH

#

all you need is basic py understanding

placid skiff
#

i studied C and learned Java before moving to python so it was like a walk into the park D_D

sullen pewter
#

Ok ima learn it

dull terrace
#

i didn't really have py understanding at all when i started, but i had messed around with lua scripting and other stuff in the past

#

just need to know basic coding concepts

slate swan
#

okie, thxs

#

How do I make it so if any message in certain channel it reacts

dull terrace
#

async def on_message(message):

dull terrace
#

?

sullen pewter
#

Nvm

cold sonnet
dull terrace
sullen pewter
#

Cuz I thought you didn't say when I started

sullen pewter
#

My bad

dull terrace
#

only been coding in python for like 6 months froggy_chill

slate swan
#

Is it possible to count every message in a channel

slate swan
#

Maybe like int(messages)

sullen pewter
vocal plover
slate swan
vocal plover
#

which is very very slow for large channels and bordering on api abuse

dull terrace
slate swan
#

How can i let my bot say the RGB of the given HEX color? Is there an API for this?

slate swan
grave summit
#

how can i add it so that only people with certain roles can use my bot

vocal plover
pliant ether
#

Hi, do you know how to detect the connection of a member on my server to react to his connection? (not on_member_join which reacts to the 1st connection / registration on the server) Thank you

supple thorn
#

Like is in the guild

slate swan
pliant ether
#

I want the bot to react as soon as a member logs in

slate swan
pliant ether
#

or as soon as he joins one of the channels for example

slate swan
#

`if message.content.lower() == '>register':
con = lite.connect('user_data.db')

        with con:
            cur = con.cursor()

            cur.execute("CREATE TABLE user_data(UserID INT, Cash INT)")
            cur.execute("INSERT INTO user_data VALUES(message.author.id,0)") `
supple thorn
slate swan
supple thorn
#

The bot can't know if a member is looking at a channel

slate swan
#

Yes a bot is like a normal discord user

#

So it can’t see if someone is on a Channel

pliant ether
#

But the bot can react to a message so it could react to a connection?

supple thorn
supple thorn
unkempt canyonBOT
#

@check_once```
A decorator that adds a “call once” global check to the bot.

Unlike regular global checks, this one is called only once per [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") call.

Regular global checks are called whenever a command is called or [`Command.can_run()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command.can_run "discord.ext.commands.Command.can_run") is called. This type of check bypasses that and ensures that it’s called only once, even inside the default help command.

Note

When using this function the [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") sent to a group subcommand may only parse the parent command and not the subcommands due to it being invoked once per [`Bot.invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") call...
supple thorn
#

You could use this check

#

Just check if they have one of the roles you want

#

Return true if they do else return false

slate swan
#

whats the code for getting user id?

slate swan
slate swan
slate swan
#

`with con:
cur = con.cursor()

            #cur.execute("CREATE TABLE user_data(UserID INT, Cash INT)")
            cur.execute("INSERT INTO user_data VALUES(user_object.id

,0)")`

#

like this? @slate swan

slate swan
umbral night
#

can somebody help me?
how would i give somebody a role using the role id

jade jolt
#
role = discord.utils.get(guild.roles, id=123456789)
await member.add_roles(role)
#

replace guild with your guild object

supple thorn
unkempt canyonBOT
#

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

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

so how do i get the id of a user? and print it out?

supple thorn
#

Or do they both loop through all of the guild roles

#

!d discord.utils.get

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/master/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...
slate swan
#

cur.execute("INSERT INTO user_data VALUES(message.author.id,0)")

is this going to work or not? if not how to fix?

dull terrace
#

no

slate swan
dull terrace
#

use placeholders

slate swan
#

pls show me how to do it

dull terrace
#

you were close

slate swan
#

will this make new line, every new user registered?

dull terrace
#

oh wait

#

is it just those two, im spacing on if that's right

slate swan
#

cuz i want the values different not overlay

dull terrace
#

it might be VALUES(your_row_name = ?, etc = ?)

slate swan
#

no.. i want it to write it in the next row, not specify row name, cuz this is for currency bot*

dull terrace
#

yeah it will, if you only want them to be added to the table once you can use the UNIQUE thing when you make the table

dull terrace
slate swan
#

cur.execute("INSERT INTO user_data VALUES(UserNum, UserID, Cash)", (1,message.author.id,0))

#

i want this usernum to increase by 1 each time, someone runs command
and also go to next line

dull terrace
#

cur.execute("INSERT INTO user_data(UserNum, UserID, Cash) VALUES(?, ?, ?)", (1,message.author.id,0))

sullen pewter
#

How can I fix this error

dull terrace
#

the ? is just a placeholder, you could put the values there but then you can't use variables, if you used an f string it would be insecure

boreal ravine
dull terrace
#

each ? is replaced with the corresponding tuple value

sullen pewter
slate swan
dull terrace
#

yeah... you need an id value so you can access it later

dull terrace
#

which you have there

boreal ravine
#

@slate swan just use an ORM if you don't know SQL well..

dull terrace
#

under UserID

dull terrace
sullen pewter
slate swan
#

i still dont get what that values are

#

cur.execute("INSERT INTO user_data(UserNum, UserID, Cash) VALUES(?, ?, ?)", (1,message.author.id,0))
this question mark part

boreal ravine
sullen pewter
dull terrace
#

then the values are used under each column (UserNum, UserID, Cash)

slate swan
#

cur.execute("INSERT INTO user_data(UserNum, UserID, Cash) VALUES(1,message.author.id,0)", (1,message.author.id,0))

like this?

dull terrace
#

yes but you need the question marks so it does it for you...

#

otherwise it would use the string and the middle value would literally be "message.author.id"

slate swan
#

cur.execute("INSERT INTO user_data(UserNum, UserID, Cash) VALUES(?, ?, ?)", (1,message.author.id,0))

so this code will make it add 1 to the usernum each time?
1st person register , usernum=1
2nd person register, usernum=2

placid skiff
#

i know but read it

placid skiff
dull terrace
slate swan
dull terrace
#

when you create UserNum UserNum INTEGER AUTOINCREMENT,

#

i think froggy_chill

slate swan
#

i dont understand where to put it

dull terrace
#

how are you creating your table rn?

hasty stump
#

can anyone assist me with custom prefix using mysql

slate swan
dull terrace
#

yes but the code

#

i'll give you an example and you work it out...

c.execute(
    """CREATE TABLE IF NOT EXISTS objects (
        object_id INTEGER PRIMARY KEY AUTOINCREMENT,
        id INTEGER,
        x INTEGER,
        y INTEGER,
        name TEXT,
        draw INTEGER
    )""",
)```
slate swan
#

`if message.content.lower() == '>register':
con = lite.connect('user_data.db')

        with con:
            cur = con.cursor()

            cur.execute("CREATE TABLE user_data(UserNum, UserID TEXT, Cash INT)")
            print(message.author.id)
            message.author.id
            cur.execute("INSERT INTO user_data (UserNum, UserID, Cash) VALUES(?, ?, ?)", (1,message.author.id,0))
            #cur.execute("INSERT INTO user_data VALUES(xx,0)")`
#

this is the code*

#

cur.execute("CREATE TABLE user_data(UserNum, UserID TEXT, Cash INT)"),UserNum INTEGER AUTOINCREMENT,

is it like this?

dull terrace
#

read my code more carefully...

slate swan
#

ok

#

i still dont get it :/

dull terrace
#

you need to look up some tutorials

slate swan
#

c.execute( """CREATE TABLE IF NOT EXISTS objects ("CREATE TABLE user_data(UserNum, UserID TEXT, Cash INT)") UserNum INTEGER PRIMARY KEY AUTOINCREMENT, 1 INTEGER, message.author.id INTEGER, Cash INTEGER UserID TEXT, Cash INT )""", )

#

@dull terrace is it like this?

placid skiff
slate swan
#

c.execute( """CREATE TABLE IF NOT EXISTS objects ("(UserNum, UserID TEXT, Cash INT)") UserNum INTEGER PRIMARY KEY AUTOINCREMENT, 1 INTEGER, message.author.id INTEGER, Cash INTEGER UserID TEXT, Cash INT )""", )

slate swan
placid skiff
slate swan
#

i looked at these resources, i just cant understand :/

placid skiff
slate swan
placid skiff
#

bro we gave you everything, you will not learn nothing if we spoonfeed you, if you can't understand you need to study more

slate swan
#

pls just teach me once, i will learn 😦

halcyon bison
#

hello, im getting back into python and i was wondering how i can make a discord status?
(like image below)

placid skiff
#

we did D_D
you have the query you need to use and the method that you need to use, you need nothing more

placid skiff
unkempt canyonBOT
#

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

Changes the client’s presence.

Example

```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
```   Changed in version 2.0: Removed the `afk` keyword-only parameter...
halcyon bison
cold sonnet
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client"), This class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
cold sonnet
#

!d discord.Client too actually

unkempt canyonBOT
#

class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
placid skiff
#

Bot is a client subclass, it has more method than it so it is better D_D

cold sonnet
#

activity and status attribute

slate swan
#

Is there anyway to get the transcripts (all the messages in a channel) from a discord channel in this format?

["Person#0000: Hello, this is a message", "AnotherPerson#0000: Hello, this is another message"]```
cold sonnet
#

for both

#

use them instead of unnecessary API calls

#

history

#

!d discord.TextChannel.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.

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

Examples

Usage...
cold sonnet
#

gets messages in a channel

#

for your strings, I suppose
f"{message.author}: {message.content}"

austere gust
#

I would like to make that if the white_check_mark is pressed on the message, the mentioned member will get the mentioned role.
(discord.py)
Here is an example:
If I press the white_check_mark @Mylan will get the @Staff role

cold sonnet
#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
cold sonnet
#

there are examples on the docs

austere gust
#

Thank so much !!! You are so helpful!
But I have problems with the coding part too

#

And the attached picture is only an example

#

I want it to work with all roles and all members

cold sonnet
#

what does your code look like?

slate swan
#

There's no easy way to get the username and content of the messages

#

you have to manually split it

cold sonnet
#

you have the message object though

#

message.author is a member object which you can convert to str

slate swan
#

in order to get the message id object you have to do this complicated code:

msg = await channel.fetch_message(int(str(messages[i]).split("=")[1].split(" channel")[0]))```
cold sonnet
#
messages = [] 
async for message in channel.history(limit = 20):
    messages.append(f"{message.author}: {message.content}")
```have you tried something like this?
slate swan
cold sonnet
#

so what's stopping you?

slate swan
#

Oh, I see.

slate swan
cold sonnet
slate swan
#

I'm gonna try.

#

It has fortunately worked.

cold sonnet
#

yay

dull terrace
#

Someone motivate me

lofty pecan
#

hi there, I made a vote command for my bot, and I have a rank command that gives me the leaderboard of my server. The thing is, it's extremely slow and I suspect the for loop to be the reason (or maybe the library table2ascii is very slow), so here is my code, would there be a way to improve it ? ```python
@commands.command()
async def rank(self, ctx):
""" Gives the first 10 most liked OCs """
id = ctx.guild.id
cursor = self.db.cursor()
cursor.execute('SELECT artist_id, oc_name, oc_rank FROM main WHERE guild_id = ? ORDER BY oc_rank DESC LIMIT 10',(id,))
result = cursor.fetchall()
cursor.close()

    Rank = 1
    body = []
    for e in result:
        body.append([Rank, e[1], await self.bot.fetch_user(e[0]), e[2]])
        Rank += 1

    output = t2a(
        header=['Rank', 'Name', 'Artist', 'Vote'],
        body=body,
        first_col_heading=True        
    )
    
    embed = discord.Embed(title=f"List of 10 most popular characters", description=f'``\n{output}\n``' ,colour=discord.Colour(0xfff700))
    await ctx.send(embed=embed)```
velvet compass
dull terrace
#

I know I can do it but zzz froggy_chill

lofty pecan
#

Dew it anakin

slate swan
#

i need someone like brad that supports me😔

#

connecting to the gateway isnt easy😔

lofty pecan
#

considering I'm making a bot for my gf it's a cool motivation

boreal ravine
#

what should I name a discord API wrapper?

dull terrace
slate swan
paper sluice
slate swan
boreal ravine
dull terrace
slate swan
boreal ravine
#

just send heartbeats, then send hello, then send identify easy

slate swan
velvet compass
unkempt canyonBOT
#

weather.py lines 12 to 18

from dotenv import load_dotenv
from loguru import logger
from rapidfuzz import process

root_dir = Path(__file__).parent
load_dotenv(root_dir.joinpath(".env"))
API_KEY = os.environ.get("API_KEY")```
boreal ravine
#

ic

slate swan
velvet compass
lofty pecan
#

but programmer are cooler

slate swan
#

fr

slate swan
dull terrace
#

I'm over 3k lines of code now and every time I look at it my brain go wtf is this

slate swan
#

ill continue my discord api wrapper after i take a 7hour nap after school

lofty pecan
#

bruuuuuh

#

3k how

dull terrace
#

It's a game with lots of stuff froggy_chill

lofty pecan
#

I also have a lot of lines, but it's in cogs, it's so much better, I was really annoyed by cogs, I thought it was hard, then I tried and damn actually it"s really straight forward

slate swan
#

monkey

cold sonnet
#

no work

lofty pecan
#

and then I was json, instead of SQL, got annoyed by SQL some years ago basically, then I decided to try and damn it's so much better

slate swan
lofty pecan
lofty pecan
slate swan
slate swan
lofty pecan
slate swan
#

🥺 🙏

#

` if message.content.lower() == '>register':
con = lite.connect('user_data.db')

        with con:
            cur = con.cursor()
            
            cur.execute("CREATE TABLE user_data(UserNum, UserID TEXT, Cash INT)")
            print(message.author.id)
            message.author.id
            
            CREATE TABLE user_data (
                UserNum INTEGER PRIMARY KEY AUTOINCREMENT,
                UserID TEXT
                Cash INTEGER

            );
            
            cur.execute("INSERT INTO user_data(UserNum, UserID, Cash)", (1,message.author.id,0))
            #cur.execute("INSERT INTO user_data VALUES(xx,0)")

`

halcyon bison
#

how do i get the owner of a server?

cold sonnet
slate swan
halcyon bison
#

like for my suggest command i have to manually add a userid per server but i want it to automatically go to everyone who have either owner or a specific permission

cold sonnet
slate swan
lofty pecan
#

it doesn't show well

cold sonnet
lofty pecan
#

it shows your code better

halcyon bison
#

is {ctx.guild.owner} a thing

cold sonnet
#

yes

lofty pecan
#

yes it is

eternal apex
#

i'm trying to make my bot send buttons but it says ImportError: cannot import name 'InteractionType' from 'discord_components

from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType
@bot.command()
async def button(ctx):
  await ctx.send("Press Button",
                 components = [
    Button(style=ButtonStyle.blue,
           label="CLICK Me!")
    ]
  )
  rest = await bot.wait_for("button_click")
  await rest.respond(type=InteractionEventType.ChannelMessagewithSource,
                     content="Clicked!")```
slate swan
#

im asking if it is correct or not...

lofty pecan
slate swan
#

hi, my bot is working properly on my computer but he is doing that on my host 😦

halcyon bison
lofty pecan
#

await

#

mayhaps

#

it's a coroutine

#

also ! it's fetch

#

await bot.fetch_user(id)

#

and self.bot if you're inside a class in a cog of course

umbral night
#

is timeout_members not a permission

#

? what do i use instead

cold sonnet
unkempt canyonBOT
cold sonnet
#

🥳

unkempt canyonBOT
umbral night
#

doesnt work

cold sonnet
#

what did you try

#

what's the error

#

what's your code, how did you invoke it

#

where does it stop

umbral night
#
@commands.has_permissions(moderate_members = True)
#

that's what i used

#

but it does not work.

cold sonnet
#

why

#

what do you expect

#

what happened

#

what permissions do you have

umbral night
#

owner

cold sonnet
#

that's good

brazen raft
#

You can't do anything to owners by the way

umbral night
#

i know.

cold sonnet
#

do you have an error

umbral night
#

yes

cold sonnet
#

that's good

umbral night
#
Traceback (most recent call last):
  File "/home/rore/quack/main.py", line 166, in <module>
    @commands.has_permissions(moderate_members = True)
  File "/home/rore/quack/env/lib/python3.9/site-packages/discord/ext/commands/core.py", line 1779, in has_permissions
    raise TypeError('Invalid permission(s): %s' % (', '.join(invalid)))
TypeError: Invalid permission(s): moderate_members
cold sonnet
#

what's your dpy version

umbral night
#

L

supple thorn
#

moderate_members is only in the 2.0 version right

umbral night
#

yeah

cold sonnet
#

right

supple thorn
#

Yeah

cold sonnet
#

yes

supple thorn
frozen patio
#

Isn’t it ctx.reply()

#

Ah

#

I use nextcord 😅

olive osprey
#

Try to input it into a variable & edit it.

msg = await ctx.respond("hi")
await msg.edit("hello")

Maybe this works, atleast in discord.py it does

boreal ravine
#

did you ask in the pycord server?

olive osprey
#

Try one of those:

InteractionResponse.edit_message

interaction.response.edit_message

slate swan
#

`if message.content.lower() == '>register':
con = lite.connect('user_data.db')

        with con:
            cur = con.cursor()
            cur.executescript("""
                DROP TABLE IF EXISTS user_data;
                CREATE TABLE user_data(UserID TEXT, Cash INT);
            
                INSERT INTO user_data VALUES(message.author.id,0)
                """)`
little ivy
#

why do i get this error?

slate swan
cloud dawn
little ivy
#

Token is resetted already

surreal ruin
#
python bot.py
File "bot.py", line 79
 self.load_extension(f"cogs.{}")
SyntaxError: f-string: empty expression not allowed
exit status 1```
#

Anyone

#

To fix it

#

?

velvet compass
surreal ruin
#

Now this

#

This error

cloud dawn
velvet compass
surreal ruin
#

How to install it

velvet compass
#

Usually with pip

#

Like a normal python package from pypi

surreal ruin
#

pip install --loop

surreal ruin
velvet compass
#

Is --loop the same as uvloop?

surreal ruin
#

Ops

#

pip install --uvloop

velvet compass
#

The format I usually use to install is py -m pip install <whatever package>. But from your screenshot it looks like you are on mobile, and I have never used python on mobile before so can't speak to the differences

brazen raft
#

It's replit

#

They have a package manager tab

slate swan
#

umm guys

brazen raft
#

You can just search for packages and install them, although I think they have to be on PyPi

slate swan
#

Im new to python how do you make a bot that can only be used in one channel in a server?

velvet compass
slate swan
#

Like u can only used it a one channel

cloud dawn
surreal ruin
#

@velvet compass

brazen raft
#

At least, I think this is replit

#

Maybe I'm blind

#

Nope it says right there in the URL bar

velvet compass
surreal ruin
#

Thanks

#

Now this

#

@velvet compass see

velvet compass
#

Yeah it looks like you haven't installed a few dependencies

surreal ruin
#

Should i try pip install aioredis

velvet compass
#

So you will need to pip install them. Usually projects have a requirements.txt or use a package manager

velvet compass
boreal ravine
#

if you're using a fork of a bot and it has a requirements.txt file do pip install -r requirements.txt to install all the required packages

jade tartan
#

Hi i keep getting this error everytime i run this command

#
Traceback (most recent call last):
  File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\thoma\OneDrive\Desktop\discord server bot\Bot2.py", line 237, in afk
    await ctx.author.edit(nick=f"[AFK] {ctx.author.mention}")
  File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\member.py", line 681, in edit
    await http.edit_member(guild_id, self.id, reason=reason, **payload)
  File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 248, in request        
    raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

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

Traceback (most recent call last):
  File "C:\Users\thoma\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\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\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: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
austere gust
velvet compass
jade tartan
#

So?

#

Do i need to give this command a manage permission?

cloud dawn
surreal ruin
#

I use fork

boreal ravine
surreal ruin
jade tartan
slate swan
#

INSERT INTO user_data VALUES(message.author.id,0)

error when use cmd:
sqlite3.OperationalError: no such column: message.author.id

**how to fix this? pls help me tysm **

cloud dawn
slate swan
surreal ruin
cloud dawn
#

...(INSERT INTO user_data VALUES(?, 0), (message.author.id,))

jade tartan
#

??

loud junco
#

how do i make an error handling for keyerror

#

can i used on_command_error?

velvet compass
#

A KeyError coming from a dictionary or something?

loud junco
#

or i need to use try

loud junco
velvet compass
#

I would suggest a try / except block, and if it is not critical, just log the error and the key that wasn't found

slate swan
loud junco
velvet compass
loud junco
#

if not the player wont get any output
and they wont know what is happening

slate swan
loud junco
velvet compass
cloud dawn
loud junco
#

i dont have error sample now

slate swan
#

` if message.content.lower() == '>register':
con = lite.connect('user_data.db')

        with con:
            cur = con.cursor()
            cur.executescript("""
                DROP TABLE IF EXISTS user_data;
                CREATE TABLE user_data(UserID TEXT, Cash INT);
                INSERT INTO user_data VALUES(?, 0), (message.author.id,)
                """)`
velvet compass
# loud junco just key error

Then I would use a try / except block for it, unless on_command_error does what you want (can always try both and see what you prefer)

slate swan
placid skiff
cloud dawn
#

And with con:?

slate swan
#

yeah

loud junco
#
@bot.event
async def on_command_error(ctx, error):
  if isinstance(error, commands.CommandOnCooldown):
    seccd = round(error.cooldown.get_retry_after())
    mincd = 0
    hrcd = 0
    rseccd = 0
    rmincd = 0

    if seccd > 59:  
      rseccd = int(seccd % 60)
      mincd = int((seccd - rseccd) / 60)
      if mincd > 59:
        rmincd = int(mincd % 60)
        hrcd = int((mincd - rmincd) / 60)
    else:
      rseccd = seccd
    await ctx.send(f'''
Dont spam :/ 
Try again in another **{hrcd}h {rmincd}m {rseccd}s**
''')
  elif isinstance(error, commands.CommandNotFound):
    await ctx.send(f'**{ctx.author.name}**, this command doesnt exist, check your spellling maybe??')
  else:
    raise error
    
  try:
    pass
  except KeyError:
    await ctx.send(f'**{ctx.author.name}**, your account is either not created yet or is not in the latest version. Try `rpm start`')
```is this even legal
#

the try except part

placid skiff
#

tbh put a try except inside an error handler isn't the best D_D

#

why would you even do that?

loud junco
#

cuz i need to define ctx and idk how to define it
if its not in a function

placid skiff
#

wdym?

loud junco
#

if i put it outside ctx will be undefined

#
try:
  pass
except KeyError:
  await ctx.send(f'**{ctx.author.name}**, your account is either not created yet or is not in the latest version. Try `rpm start`')
slate swan
#
        if message.content.lower() == '>register':
            con = lite.connect('user_data.db')

            with con:
                cur = con.cursor()
                cur.executescript("""
                    DROP TABLE IF EXISTS user_data;
                    CREATE TABLE user_data(UserID TEXT, Cash INT);
                    INSERT INTO user_data VALUES(message.author.id,0)
                    """)```
placid skiff
#

You want to catch the KeyError?

loud junco
loud junco
slate swan
loud junco
#

whats with this `

placid skiff
#

well it will not work here anyway because if you are tryin to catch it outside a command the on_command_error will not be triggered

loud junco
slate swan
placid skiff
#

the try except must be inside the function which could raise the keyerror

loud junco
#

can i just put it at last

#

like here

slate swan
#

why catch a key error

#

just use dict.get?

loud junco
#

read the description of the error ;-;

slate swan
slate swan
placid skiff
jade tartan
placid skiff
#

but if you want to try something a little bit harder

#

then there could be a way

loud junco
#

i rather do harder thing than repetitive work

loud junco
slate swan
#

hola blvck

placid skiff
#

well then, this is what you can do:
you'll have to create a class and make it a subclass of DiscordException, this way you will have a discord error which represents the key error

placid skiff
#

in your function where there could be a keyerror, instead of catching the key error you will raise that class, like this:

class myError(DiscordException):
  ...

def my_function():
  if my_value not isinstance(my_object):
    raise myError()
#

when you've done this, you can catch your custom error with the on_error event

vale wing
#

I usually subclass commands.CommandError cause I have on_command_error for most of exceptions

loud junco
placid skiff
placid skiff
loud junco
slate swan
jade tartan
#

Question

vale wing
#

Just create a new class inheriting some discord exception class, you may even leave it empty but I'd recommend initialising it with a message

jade tartan
#

I cant use object string in await function right?

placid skiff
placid skiff
#

Take note that i'm telling you all of this basing on my experience, i've never tried this so i don't know at 100% how it works xD

#

but it should work

slate swan
#

@bot.event
async def on_member_join(member):
    await bot.send_message(member, f"reply to this message with key: ||{key}||")
    m = await bot.wait_for_message(author=member, channel=member)
    if m.content == key :
        await bot.add_roles(memberr, roll)
        await bot.send_message(member, 'Role added')
    else:
        await bot.send_message(member, 'Incorrect key')

Everything is defined but it won’t Dm member on join

slate swan
placid skiff
#

sorry Ashley i was frying my brain, hello btw xD

loud junco
#

what is my_value and my_object

vale wing
jade tartan
vale wing
#

Use member.send(...)

jade tartan
#

??

vale wing
#

And yeah you have a typo

frozen elk
#

I'm getting started with a discord bot and i see there are so many lib to choose from
Anyone who is familiar with it please enlighten me.

slate swan
vale wing
#

memberr

#

Eh hold up

placid skiff
slate swan
vale wing
#

Why the hell do you call all the methods on bot

swift crane
#

how to make avatar slash command?

slate swan
loud junco
#

actually i have no idea what this does

frozen elk
loud junco
#

can u guide me ;-;

placid skiff
#

you don't know what KeyError does? D_D

loud junco
swift crane
#
@bot.command()
async def avatar(ctx, *,  avamember : discord.Member=None):
    username_1 = ctx.message.author.name
    avatar_1 = ctx.message.author.avatar_url
    userAvatarUrl = avamember.avatar_url
    embed=discord.Embed(title="Avatar")
    embed.set_author(name=f"requested by {username_1}", icon_url=avatar_1)
    embed.set_image(url=userAvatarUrl)
    await ctx.message.delete()
    await ctx.send(embed=embed)
#

this on normal version

jade tartan
#

Can someone help

loud junco
vale wing
unkempt canyonBOT
jade tartan
frozen elk
placid skiff
#

it was an example i don't know your code

slate swan
#
        `if message.content.lower() == '>register':
            con = lite.connect('user_data.db')

            with con:
                cur = con.cursor()
                cur.executescript("""
                    DROP TABLE IF EXISTS user_data;
                    CREATE TABLE user_data(UserID TEXT, Cash INT);
                    INSERT INTO user_data VALUES(message.author.id,0)
                    """)```

anyone can help with the message.author.id part? it doesnt work :/
loud junco
slate swan
# swift crane how to make avatar slash command?
  • Create an embed (since that looks uwu)
  • grab the member's/author's avatar using the avatar.url (dpy2) [avatar_url for older versions] on the Member/User object
  • use the set_image method on the embed object
  • send it
placid skiff
vale wing
vale wing
#

And this is not how you make commands

swift crane
heavy tangle
#

how do i get the channel id of where the command was executed?

loud junco
#

item.cooked_pogchop may be the key error

vale wing
#

Use a decorator

loud junco
#
class Item():  
  def __init__(self, ctx):  
    self.userid = str(ctx.author.id)
    self.pogchop = db[self.userid + 'pogchop']
    self.cooked_pogchop =  db[self.userid + 'cooked_pogchop']
    self.beef =  db[self.userid + 'beef']
```this is small part of item
slate swan
vale wing
#

Same for interactions

heavy tangle
loud junco
# placid skiff give me a part of your code where it could raise a KeyError
@bot.command(name='daily')
@commands.cooldown(1, 86400, commands.BucketType.user)
async def daily(ctx):
  item = Item(ctx)
  stats = Stats(ctx)
  db[stats.userid + 'cooked_pogchop'] = item.cooked_pogchop + 10
  db[stats.userid + 'steak'] = item.steak + 10
  await ctx.send(f'**{ctx.author.name}** has claimed daily kit')
```here u go
`item.cooked_pogchop` may be the key error
slate swan
placid skiff
loud junco
#
class Item():  
  def __init__(self, ctx):  
    self.userid = str(ctx.author.id)
    self.pogchop = db[self.userid + 'pogchop']
    self.cooked_pogchop =  db[self.userid + 'cooked_pogchop']
    self.beef =  db[self.userid + 'beef']
jade tartan
#

Hello

slate swan
vale wing
loud junco
#

this is a small part of item

vale wing
#

You basically put ? into the query and provide a tuple of args as another arg to execute

placid skiff
#

technically you can catch it in on_command_error

vale wing
#

Well lemme find it in docs

slate swan
#

its basically the same thing, everything else works, just the variable that does not work

loud junco
#

POGGERS

placid skiff
loud junco
#

im deleting that damn file

placid skiff
#

F

loud junco
#

so how do i put it inside

#
try:
  pass
except KeyError:
  await ctx.send(f'**{ctx.author.name}**, your account is either not created yet or is not in the latest version. Try `rpm start`')
```i still have this
placid skiff
#

Just like the others

#
if isinstance(error, KeyError):
  ...
loud junco
vale wing
#

@slate swan so basically this query INSERT INTO users (id, name) VALUES (?, ?) with args (123, "nice name") turns into INSERT INTO users (id, name) VALUES (123, 'nice name') idk how to explain this simplier

#

The question marks are correspondingly replaced with args

#

From your code I could only see that as an issue

slate swan
#

but then the other parts will have error

vale wing
#

What parts

slate swan
#

can u pls help rewrite the code for me?

#

so that i can understand it better*

#

as i said only the variable part is the issue which errors

vale wing
#

I would make a whole different and more complicated system because I never do sql interactions with raw queries in each command

#

OOP is just op

slate swan
vale wing
#

Sry haven't used sqlite for a while

slate swan
#
        `if message.content.lower() == '>register':
            con = lite.connect('user_data.db')

            with con:
                cur = con.cursor()
                cur.executescript("""
                    DROP TABLE IF EXISTS user_data;
                    CREATE TABLE user_data(UserID TEXT, Cash INT);
                    INSERT INTO user_data VALUES(message.author.id,0)
                    """)```
#

this my code*

vale wing
#

There are 2 very big issues

#

First is for god's sake do commands using a decorator

slate swan
#

and?

vale wing
#

!d discord.ext.commands.Bot.command

unkempt canyonBOT
#

@command(*args, **kwargs)```
A shortcut decorator that invokes [`command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
vale wing
#

Non cog implementation

slate swan
#

second one?

vale wing
#

Second is completely nonsense queries

#

You usually create tables on initialization

#

Not on command usage

slate swan
#

then can u help me re-write the code pls? so that i can understand*

vale wing
#

I am trying to explain it to you so you can rewrite it by yourself

slate swan
#

@bot.event
async def on_member_join(member):
    await member.send(member, f"reply to this message with key: ||{key}||")
    m = await bot.wait_for_message(author=member, channel=member)
    if m.content == key :
        await bot.add_roles(memberr, roll)
        await member.send(member, 'Role added')
    else:
        await member.send(member, 'Incorrect key')```
Bot won’t message user (don’t worry everything is defined)
vale wing
#

That's the modern pedagogy concept

slate swan
vale wing
#

You would better change it not to suffer from it in the future

slate swan
#

which i have worked on for so long, and so much features, that will need to change

vale wing
#

Not the bot.add_roles

slate swan
#

bcz im using an old way of doing python discord*

#

so is there any way to do it?

slate swan
#

instead of changing the entire code*

vale wing
slate swan
#

Help with that?

vale wing
slate swan
vale wing
#

Personally I rewrited several huge projects with bad code to the normal ones

slate swan
#

so is there any way to change it in the current way?

vale wing
#

There is but it is inconvenient and confusing

slate swan
#

@vale wing it’s not messaging user on join would ctx be better then member in my situation

slate swan
vale wing
slate swan
#

i dont mind doing it the confusing way for now

vale wing
#

I hope you will learn how to improve it

#

As for now, you can look at my project to see how you could implement database interaction

#

It's very simple and not the best but still better than making queries in commands

slate swan
#

Nice project

umbral night
#

help

#

apparently these dont work anymore

unkempt canyonBOT
#

modules/bot.py lines 93 to 98

async def set_birthday(self, user: User, bday: Date):
    await self.execute(
        "INSERT OR REPLACE INTO users (id, birthday) VALUES (?, ?)",
        user.id,
        bday.to_str(),
    )```
vale wing
#

Things like this

placid skiff
vale wing
#

heck that to_str() method wtf did i do

placid skiff
#

or you were using a venv when you coded that project

umbral night
#

was i not supposed to

#

lol?

narrow grail
#

Does Modals only work for slash commands?

placid skiff
#

well tbh venv are usefull but you have to remind to import them too when you export the project lol

vale wing
#

Basically for all interactions

vale wing
umbral night
#

my friend setup my venv

narrow grail
umbral night
vale wing
#

Venv setup is screwed in windows

umbral night
#

how owuld i fix that

umbral night
vale wing
#

Those "execution policies"

vale wing
narrow grail
umbral night
slate swan
#
        if message.content.lower() == '>register':
            con = lite.connect('user_data.db')

            with con:
                cur = con.cursor()
                on_ready CREATE TABLE IF NOT EXISTS user_data(UserID TEXT, Cash INT);
                cur.execute("INSERT INTO user_data (UserID, Cash) VALUES (?, ?)", (message.author.id, 0)") ```
placid skiff
narrow grail
vale wing
slate swan
umbral night
#

my friend made me move the stuff that was in my folder to a folder for a repo

vale wing
#

And that's way you should learn a new way of making bots

umbral night
#

so he could do PRs

#

i think ive messed everything up

slate swan
vale wing
vale wing
umbral night
slate swan
placid skiff
vale wing
#

Learn the new way of making bots

#

Lemme find that tutorial

slate swan
vale wing
slate swan
#

do you think its worth rewriting the code? its a few thousand lines*

vale wing
#

Totally worth

#

Gotta tell you if you get really experienced you will rewrite it not even once

shell wing
#
Ignoring exception in command guide:
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/runner/new-server/guides.py", line 72, in guide
    await Paginator(bot=self.bot,
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/dinteractions_Paginator/_Paginator.py", line 315, in Paginator
    await button_context.edit_origin(
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/context.py", line 618, in edit_origin
    _json = await self._http.edit(_resp, self._token, files=files)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 216, in request
    raise HTTPException(r, data)
discord.errors.HTTPException: 429 Too Many Requests (error code: 0): <!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js ie6 oldie" lang="en-US"> <![endif]-->
<!--[if IE 7]>    <html class="no-js ie7 oldie" lang="en-US"> <![endif]-->
<!--[if IE 8]>    <html class="no-js ie8 oldie" lang="en-US"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en-US"> <!--<![endif]-->
<head>
<title>Access denied | discord.com used Cloudflare to restrict access</title>
<meta charset="UTF-8" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link rel="stylesheet" id="cf_styles-css" href="/cdn-cgi/styles/main.css" type="text/css" media="screen,projection" />
``` getting this error in a button paginator
vale wing
#

Requests + aiohttp fire combo but wtf

#

Just use aiohttp

#

And make sure you get success status code

slate swan
#

I-

placid skiff
#

i wonder if that guy finds his venv or he is setting up dependencies again

tall pecan
slate swan
# tall pecan hi

why are you using requests for one request and aiohttp for another ;-;

vale wing
#

Gonna publish first stable version of AIAS soon it's gonna be hot

vale wing
#

Yes

slate swan
slate swan
vale wing
#

AI AntiSpam shortly

placid skiff
#

Cool

vale wing
#

Currently has bugs but I almost fixed them all

placid skiff
#

congrats partycat

vale wing
#

Thx

tall pecan
slate swan
#

How do i make discord spam bots? thanks btw ;D

sick birch
slate swan
#

Purely hypothetical

#

haha XD

#

spamming in general is against discord ToS, weather is an user account or a normal one

velvet compass
# slate swan Purely hypothetical

Hypothetically I would hate to have a spam bot used somewhere I am, and would hypothetically do my best to make sure no one ever makes one

slate swan
#

If someone wants to help. Dm's are open ;D ty

#

haha XD

velvet compass
unkempt canyonBOT
#

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

slate swan
#

As long as i dont get the help on this server everything is fine.

sick birch
#

Right

slate swan
sick birch
#

But you know do it at your own risk

slate swan
#

😭

#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

slate swan
#

Well, i know there are tools. But the good ones cost a lot of money.

#

Why u want spam bot

#

Haha.. just for trolling good friends 😉

#

..

#

hahaha

sick birch
velvet compass
#

Let's move on

slate swan
#

Ok

sick birch
#

.topic

lament depotBOT
#
**What unique features does your bot contain, if any?**

Suggest more topics here!

sick birch
#

none lmao

slate swan
sick birch
#

well

#

that’s certainly unique

slate swan
#

what?

sick birch
#

Let’s try to keep it appropriate

slate swan
#

I was honest

#

Ok

#

And, how do i make spam bots for twitch?

#

Nah, just kidding XD

#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

slate swan
#

Stop so

velvet compass
#

!mute 274822366708629505 3d I'll help you to not ask about ToS breaking projects on this server for a little while.

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1650722346:f> (2 days and 23 hours).

slate swan
#

Cool

boreal ravine
#

Anyone have any bot ideas?

slate swan
boreal ravine
#

boring

#

but interesting

slate swan
ripe fulcrum
#

chess is a good concept

slate swan
#

Ye complex too

ripe fulcrum
#

but its too long

slate swan
#

Yes

ripe fulcrum
#

all the rules

boreal ravine
#

theres already lots of chess bots out there so no.

ripe fulcrum
#

and move and directions

#

there's enough of all bots out there

slate swan
ripe fulcrum
#

you have to think outside of the box there mate

slate swan
#

Ludo is medium

#

Cuz there are not much rules

ripe fulcrum
#

how about a graph making bot xd

#

or mathemathical stuff bot

slate swan
#

Boring

ripe fulcrum
#

one time use but still useful

slate swan
#

Add antinuke

ripe fulcrum
#

hmm

#

can you make a website with a bot?

#

that might be cool

slate swan
#

Dashboard stuff u mean

ripe fulcrum
#

no,not really

#

like a homepage of some sort

tall pecan
#

website for a bot?

slate swan
#

Yo mee7

tall pecan
#

hi

boreal ravine
ripe fulcrum
#

then do it

#

everyone will be interested in making website

#

especially discord users for their mod applications

#

server advertisement

#

server info

#

games on website which is connected to a duscord bot

shell wing
pliant gulch
#

Seems like it's every other day that someone comes in with an issue regarding API bans with repl.it

boreal ravine
#

R. Danny just got verified

pure sparrow
velvet compass
#

A discord timestamp?

#

The .epoch command can help, but it is like this: <t:1651069269:D> -> <t:1651069269:D>

pliant gulch
#

If you have a datetime.datetime object you can use discord.py's helper method

#

!d discord.utils.format_dt

unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
humble granite
#

Hello! I have a little problem with discord.Color in embeds. I want the color to be a string. (e.g: #ffffff) But It looks like discord does not accepts these strings. Is there any way to like convert the string into an hex so discord accepts it?

slate swan
opal cosmos
#

can i not have the bot change its presence within a task loop?

slate swan
#

You ofcourse can

opal cosmos
#

not working tho

#
@tasks.loop(seconds=5.0)
async def status():
  await bot.change_presence(status=discord.Status.online, activity=discord.Game("~help"))
  asyncio.sleep(1)
  await bot.change_presence(status=discord.Status.online, activity=discord.Game("repl.it"))
  asyncio.sleep(1)
humble granite
cloud dawn
opal cosmos
#

fine

slate swan
#

for changing the activity twice

cloud dawn
# opal cosmos bruh

If you increase the time it switches by * 600 then it's better. I also recommend to await asyncio sleep.

opal cosmos
#

lol

slate swan
opal cosmos
slate swan
#

also also, How do I make a Custom Exception for my commands?

#

just make a class and raise the class on error

slate swan
#

you need to inherit the Exception class

slate swan
#

even though I dont expect it to be right

#

it is right by why did you make the Error class? just for being specific that those error classes are custom ?

slate swan
lofty pecan
#

Hi there, is there a way to have a global event type or something like that to blacklist certain people from the bot ? so they can't use it ?

slate swan
slate swan
#

which would be global

lofty pecan
#

ho?

slate swan
#

!d discord.ext.commands.Bot.add_check

unkempt canyonBOT
#

add_check(func, /, *, call_once=False)```
Adds a global check to the bot.

This is the non-decorator interface to [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.check "discord.ext.commands.Bot.check") and [`check_once()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.check_once "discord.ext.commands.Bot.check_once").

Changed in version 2.0: `func` parameter is now positional-only.
lofty pecan
#

how can I do that?

#

it's like, I go see in a json if the id of the user is there

#

and I return a True or False statement ?

slate swan
#

json file 😔

lofty pecan
#

otherwise I use sqlite

slate swan
#

ah well

slate swan
#

else, its supposed to raise a CheckFailure error, or you can raise your own error class

lofty pecan
#

so hum, does that mean that in every command I need to add that line that check the id ?

slate swan
#

Bot.add_check adds it to your complete bot

#

each command would get that check automatically

lofty pecan
#

hoooo

#

so no need to add anything nice !

boreal ravine
lofty pecan
#

for example in my main.py file where I gather all the cogs and run the bot I add bot.add_check?

lofty pecan
#

I'm confused by how i'm supposed to implement it lol

lofty pecan
#
@bot.check
async def blacklist(ctx):
    return ctx.author.id in get_user_blacklist()```
#

like that?

lofty pecan
#

and then I need to define get_user_blacklist()

maiden fable
#

Iirc that's how it works

lofty pecan
#

nice :3

maiden fable
#

return ctx.author.id in user_blacklist

lofty pecan
#

I mean, if I make a json file I need to fetch that file ?

maiden fable
#

Where user_blacklist is a list

#

Ah yes

slate swan
#

what does get_user_blacklist return?

maiden fable
lofty pecan
#

I already have a fetch command anyway so it's not hard

maiden fable
#

@lofty pecan make sure the function returns a list

lofty pecan
#

yes yes

slate swan
#

oh well, then he can just return the list, or enter that list right there directly

lofty pecan
#

not a dictionnary lol

opal cosmos
#

im trying to set up an avatar command where the bot sends an embed with the image of someones pfp, but it wont send the embed. theres no error or anything it just doesnt send

  @commands.command(name="avatar", aliases=["av"])
  async def avatar(self, ctx: commands.Context, member=discord.Member):
    embed=discord.Embed(title="Here is {member}'s avatar:'", description="** **")
    embed.set_image(self.bot.get(member.avatar.url))
    await ctx.send(embed=embed)
lofty pecan
#

alright thanks ^^

maiden fable
lofty pecan
maiden fable
#

Indeed

maiden fable
#

!d discord.Embed.set_image

unkempt canyonBOT
#

set_image(*, url)```
Sets the image for the embed content.

This function returns the class instance to allow for fluent-style chaining.
maiden fable
#

Also, your error handler is eating the errors

slate swan
maiden fable
#

That too

lofty pecan
#

Can I store a list in a jason file ?

lofty pecan
#

like [...] or do I have to use {...} ?

#

and then put the list

opal cosmos
slate swan
maiden fable
lofty pecan
#

ho nice

maiden fable
#

U can store it directly

lofty pecan
#

that's nice !

slate swan
lofty pecan
#

well it makes it easier haha

opal cosmos
maiden fable
lofty pecan
#

I was thinking storing in the json a list directly without any key required

slate swan
#

which is basically same as a dictionary

slate swan
slate swan
opal cosmos
slate swan
#

yes, what's self.bot.get tho? your own method?

maiden fable
opal cosmos
slate swan
#

never knew json works that way too

maiden fable
lofty pecan
#

is this illegal lol that's all I am asking

slate swan
maiden fable
slate swan
#

url = member.avatar.url is all you need

lofty pecan
lofty pecan
opal cosmos
#
  @commands.command(name="avatar", aliases=["av"])
  async def avatar(self, ctx: commands.Context, member=discord.Member):
    embed=discord.Embed(title=f"Here is {member}'s avatar:'", description="** **")
    embed.set_image(url=member.avatar.url)
    await ctx.send(embed=embed)
slate swan
#

your error handler is probably eating your error

opal cosmos
#

this one?

  @commands.Cog.listener()
  async def on_command_error(self, ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
      emoji = self.bot.get_emoji(id=966153503556898816)
      msg = f":no_entry_sign: __**On cooldown**__, please try again in `{round(error.retry_after, 2)}s`"
      await ctx.send(msg)
maiden fable
#

Yes

lofty pecan
#

I had the same issue

maiden fable
#

Add

else:
    raise error
lofty pecan
#

add an else statement

#
async def on_command_error(self, ctx, error):
        if isinstance(error, commands.CommandOnCooldown):
            retry = error.retry_after
            remaining_time = str(datetime.timedelta(seconds=int(retry)))
            embed = discord.Embed(title=":clock1: Slow Down!!", description=f'{ctx.author.mention}, you can use this command again in ' + str(remaining_time), color=0xE74C3C)
            await ctx.send(embed=embed)
        else:
            raise error``` Here is an example of cooldown error being raised just to showcase the else
opal cosmos
# slate swan your error handler is probably eating your error
Ignoring exception in command avatar:
Traceback (most recent call last):
  File "/home/runner/Delta/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 467, in _actual_conversion
    return converter(argument)
TypeError: __new__() missing 2 required positional arguments: 'bases' and 'namespace'

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

Traceback (most recent call last):
  File "/home/runner/Delta/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/Delta/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 855, in invoke
    await self.prepare(ctx)
  File "/home/runner/Delta/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 789, in prepare
    await self._parse_arguments(ctx)
  File "/home/runner/Delta/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 697, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "/home/runner/Delta/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 552, in transform
    return await self.do_conversion(ctx, converter, argument, param)
  File "/home/runner/Delta/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 505, in do_conversion
    return await self._actual_conversion(ctx, converter, argument, param)
  File "/home/runner/Delta/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 476, in _actual_conversion
    raise BadArgument('Converting to "{}" failed for parameter "{}".'.format(name, param.name)) from exc
discord.ext.commands.errors.BadArgument: Converting to "ABCMeta" failed for parameter "member".
#

error

normal jasper
opal cosmos
#

theres the error i got when i remove my error handler

slate swan
#

did you mention an member? or provide the userid /name

opal cosmos
#

yeah

#

mention

lofty pecan
#

welp I got this CheckFailure: The global check functions for command ocrandom failed.

#

using this

@bot.check
async def blacklist(ctx):
    return ctx.author.id in get_user_blacklist()

and

def fetch(filename: str):
    """ Fetch file """
    try:
        with open(f'{filename}.json', encoding='utf8') as data:
            return json.load(data)
    except FileNotFoundError:
        raise FileNotFoundError(f"{filename} wasn't found")```
#
def get_user_blacklist():
    return fetch('blacklist')```
#

and that's the blacklist
[170957367427596288]

maiden fable
#

That's the issue

#

Don't use a dict

lofty pecan
#

wait I'm an idiot

#

I thought that was the issue but a return was missing initially

opal cosmos
lofty pecan
#

doesn't work either

maiden fable
#

Code

lofty pecan
#

I modified the one above

#

easier

maiden fable
#

Can u print data?

lofty pecan
#

?

#
elif isinstance(error, commands.errors.CheckFailure):
            pass
``` maybe this is missing
#

in my event cogs

spice folio
#

anyone know how to make an imbeded message?

maiden fable
#
with open() as data:
    print(data) 
    return json.load(data) 
maiden fable
unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") for you.

Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
lofty pecan
#

yes doesn't work lol

slate swan
#

Yo

maiden fable
slate swan
lofty pecan
maiden fable
lofty pecan
#

i did

lofty pecan
maiden fable
#

Show

lofty pecan
#

so that works

#

[_the id that I won't show_] Ignoring exception in on_command_error Traceback (most recent call last): File "D:\Anaconda\envs\DiscordPy\lib\site-packages\discord\client.py", line 343, in _run_event await coro(*args, **kwargs) File "e:\Bobot\BotTheFourth - SQL\cogs\events.py", line 47, in on_command_error raise error File "D:\Anaconda\envs\DiscordPy\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke await ctx.command.invoke(ctx) File "D:\Anaconda\envs\DiscordPy\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke await self.prepare(ctx) File "D:\Anaconda\envs\DiscordPy\lib\site-packages\discord\ext\commands\core.py", line 777, in prepare if not await self.can_run(ctx): File "D:\Anaconda\envs\DiscordPy\lib\site-packages\discord\ext\commands\core.py", line 1072, in can_run raise CheckFailure('The global check functions for command {0.qualified_name} failed.'.format(self)) discord.ext.commands.errors.CheckFailure: The global check functions for command ocrandom failed.

maiden fable
#

Can u print json.load(data)

lofty pecan
#

it breaks my code

maiden fable
#

Eh?

lofty pecan
#

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

slate swan
#

{}

maiden fable
#

Bruhhhh i hate it when that happens

#

Anyways

slate swan
#

!d

maiden fable
#

Add {} to the JSON file

slate swan
#

Ye

maiden fable
slate swan
#

Idk

#

!tags

unkempt canyonBOT
#
Available tags

» dict-get
» dictcomps
» docstring
» dotenv
» dunder-methods
» empty-json
» enumerate
» environments
» except
» exit()
» f-strings
» faq
» floats
» foo
» for-else

lofty pecan
boreal ravine
frozen elk
#

I'm thinking of getting started with discord bots but there are so many lib out there can anyone help me out and explain the pros and cons of popular ones.

lofty pecan
slate swan
#

Then why ur using json

frozen elk
boreal ravine
maiden fable
slate swan
#

Use a txt file instead?

maiden fable
lofty pecan
#

lmao

slate swan
#

Store in txt file ez

maiden fable
lofty pecan
#

I just made a list inside my code

slate swan
#

Imagine bot crash

lofty pecan
#

still doesn't work

slate swan
#

Error?

lofty pecan
#

discord.ext.commands.errors.CheckFailure: The global check functions for command leaderboard failed.

frozen elk
#

Lmao use sqlite... more eligent way of doing things

lofty pecan
#

still the same

lofty pecan
lofty pecan
#

but that's so small I don't need a fancy database

maiden fable
#

By any chance... is it your ID in the JSON?

lofty pecan
#

no

frozen elk
lofty pecan
#

because I don't need to make a fancy sqlite database file for 3 ids lmao

slate swan
#

Txt file!!

velvet haven
#

is it not possible to send dm when someone leeaves the server

#

on member_leave

frozen elk
lofty pecan
#

omg fortunately i'd be so annoyed

slate swan
#

Idk

lofty pecan
slate swan
#

If its in mutal server u can msg ig

maiden fable
#

@lofty pecan i have an idea

lofty pecan
#

yes yes

frozen elk
maiden fable
#

I fricking forgot how checks worked, but i have another way

velvet haven
#

hmm

slate swan
maiden fable
#

Use a client.event and do smth like:

@client.event
async def on_message(m):
    if m.author.id not in blacklist:
        await client.process_commands(m) 
slate swan
#

Cool

exotic kite
#

guys how can i make the code that when my bot joins or leaves a server it tells me in a channel like this
I was invited to Server name.