#discord-bots
1 messages · Page 987 of 1
i studied C and learned Java before moving to python so it was like a walk into the park 
Would be lmao
Ok ima learn it
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
async def on_message(message):
Ima dm you tutorial
?
Nvm
if message.channel.id == some random number:
why
Cuz I thought you didn't say when I started
Nvm found it
My bad
Is it possible to count every message in a channel
Maybe like int(messages)
Should be
only by fetching every single message
I just want integer
which is very very slow for large channels and bordering on api abuse
https://stackoverflow.com/questions/52214425/how-to-get-how-many-messages-has-been-sent-in-a-channel

LOL I AM ON THAT
How can i let my bot say the RGB of the given HEX color? Is there an API for this?
I kinda need bot event though since it’s gonna be like “there is 4 messages in this channel”
how can i add it so that only people with certain roles can use my bot
There is no other way you can get the message count with a bot
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
So you want your bot to detect when a member is viewing the guild?
Like is in the guild
@bot.command()
@commands.has_role('RoleName')
async def command_name():```
I want the bot to react as soon as a member logs in
But a bot can only react once per message
or as soon as he joins one of the channels for example
`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)") `
A bot can't do that
i dont get what im doing wrong here
The bot can't know if a member is looking at a channel
But the bot can react to a message so it could react to a connection?
He'd have to add that to every command and every new command
!d discord.ext.commands.Bot.check_once
@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...
You could use this check
Just check if they have one of the roles you want
Return true if they do else return false
whats the code for getting user id?
Can someone answer me? Please?
Yes
Do u know where to find that API?
Gimme a sec
`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
"https://api.popcat.xyz/color/{hex_color}"
can somebody help me?
how would i give somebody a role using the role id
role = discord.utils.get(guild.roles, id=123456789)
await member.add_roles(role)
replace guild with your guild object
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
The user’s unique ID.
ty
ty
so how do i get the id of a user? and print it out?
Isn't get_role faster than that since it doesn't loop through all of the roles
Or do they both loop through all of the guild roles
!d discord.utils.get
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...
cur.execute("INSERT INTO user_data VALUES(message.author.id,0)")
is this going to work or not? if not how to fix?
no
how to fix it then?
use placeholders
pls show me how to do it
cur.execute("INSERT INTO user_data VALUES(?, ?)", (message.author.id,0))
you were close
will this make new line, every new user registered?
cuz i want the values different not overlay
it might be VALUES(your_row_name = ?, etc = ?)
no.. i want it to write it in the next row, not specify row name, cuz this is for currency bot*
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
i mean column
example from my code, it's this: "INSERT INTO objects(id, x, y, name, draw) VALUES (?, ?, ?, ?, ?)"
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
cur.execute("INSERT INTO user_data(UserNum, UserID, Cash) VALUES(?, ?, ?)", (1,message.author.id,0))
explain this pls
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
annotation is basically a typehint
each ? is replaced with the corresponding tuple value
?
then how i need to do this?
i want it to be seperate data for each user, so user num needs to be changed*
yeah... you need an id value so you can access it later
which you have there
@slate swan just use an ORM if you don't know SQL well..
under UserID
that's not great advice when SQL is very widely used and needed
what should I do
no i want to use SQL
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
typehint reason
wdym
it's a placeholder
(?, ?, ?) is replaced with (1,message.author.id,0)
then the values are used under each column (UserNum, UserID, Cash)
cur.execute("INSERT INTO user_data(UserNum, UserID, Cash) VALUES(1,message.author.id,0)", (1,message.author.id,0))
like this?
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"
what the hell is this 
SQL
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
i know but read it
this is the correct syntax for python
they're completely new to it, just trying to understand
oh you want autoincrement
yeah, how to do it?
full code?
i dont understand where to put it
how are you creating your table rn?
can anyone assist me with custom prefix using mysql
db file, sqlite3
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
)""",
)```
`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?
read my code more carefully...
you need to look up some tutorials
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?
you can't create a table inside a table 
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 )""", )
like this?
No
how?
i looked at these resources, i just cant understand :/

how to do it then?
bro we gave you everything, you will not learn nothing if we spoonfeed you, if you can't understand you need to study more
pls just teach me once, i will learn 😦
hello, im getting back into python and i was wondering how i can make a discord status?
(like image below)
we did 
you have the query you need to use and the method that you need to use, you need nothing more
!d discord.ext.commands.Bot.change_presence
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...
oh :0
awesome
!d discord.ext.commands.Bot
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.
!d discord.Client too actually
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").
Bot is a client subclass, it has more method than it so it is better 
activity and status attribute
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"]```
for both
use them instead of unnecessary API calls
history
!d discord.TextChannel.history
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...
gets messages in a channel
for your strings, I suppose
f"{message.author}: {message.content}"
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
!d discord.ext.commands.Bot.wait_for
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**...
there are examples on the docs
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
what does your code look like?
Tried that...
There's no easy way to get the username and content of the messages
you have to manually split it
you have the message object though
message.author is a member object which you can convert to str
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]))```
messages = []
async for message in channel.history(limit = 20):
messages.append(f"{message.author}: {message.content}")
```have you tried something like this?
No because I need my code under a on_raw_reaction_add function.
so what's stopping you?
Oh, I see.
Denialism.

yay
Someone motivate me
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)```
You can do it! There is nothing that you cannot do, given enough time, focused attention and guided help when you need it
I know I can do it but zzz 
Dew it anakin
considering I'm making a bot for my gf it's a cool motivation
what should I name a discord API wrapper?
Get to work or else 
but😔
thats motivation
Bobbicord
it is easy
I've done that before, so much better when you're making it for someone else
making a good impl, no
just send heartbeats, then send hello, then send identify easy
it does this btw

its easy but having a good implementation of it is a bit hard
Dotenv is to load environment variables, I generally use it like this: https://github.com/brad90four/weather_cli/blob/main/weather.py#L12-L18
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")```
ic
Programming is cool
I know guy, one second.
You can do it too!
but programmer are cooler
fr
🥺 💜
I'm over 3k lines of code now and every time I look at it my brain go wtf is this
ill continue my discord api wrapper after i take a 7hour nap after school
It's a game with lots of stuff 
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
monkey
no work
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
subclassing is quite easy and lovely
stronk toge'er
it is!
yes
i cant live without oop
you can fart without pooping , but you can't poop without farting
🥺 🙏
` 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)")
`
how do i get the owner of a server?
long second
@dull terrace is this correct now?
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
try python
me dumb it was there
wdym
it doesn't show well
in the name of commands, I feel betrayed
is {ctx.guild.owner} a thing
yes
yes it is
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!")```
im asking if it is correct or not...
and I'm just saying for the future you can use that when you ask here so your code is easier to read
hi, my bot is working properly on my computer but he is doing that on my host 😦
okie
how would i integrate into user = bot.get_user(int(836281762815541329))
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
!d discord.ext.commands.Bot.get_user
get_user(id, /)```
Returns a user with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
🥳
Returns True if a user can time out other members.
New in version 2.0.
doesnt work
what did you try
what's the error
what's your code, how did you invoke it
where does it stop
@commands.has_permissions(moderate_members = True)
that's what i used
but it does not work.
owner
that's good
You can't do anything to owners by the way
i know.
do you have an error
yes
that's good
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
what's your dpy version
L
moderate_members is only in the 2.0 version right
yeah
right
Yeah
yes
Upgrade to 2.0 or do manage_roles
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
did you ask in the pycord server?
Try one of those:
InteractionResponse.edit_message
interaction.response.edit_message
`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)
""")`
message.author.id does not work in SQL value, how do i fix this??
You showed half an error + your token
Token is resetted already
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
?
The {} are empty, usually you have a variable in them
You need to enable intents read the middle.
You are importing uvloop but do not have it installed
How to install it
pip install --loop
@velvet compass
Is --loop the same as uvloop?
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
umm guys
You can just search for packages and install them, although I think they have to be on PyPi
Im new to python how do you make a bot that can only be used in one channel in a server?
Ahhh I see. Given how popular it is I should probably learn about it lol
Like u can only used it a one channel
My, good luck, I guess
It's pretty much a wrapped pip
@velvet compass
Oh
At least, I think this is replit
Maybe I'm blind
Nope it says right there in the URL bar
Try pip install uvloop
Yeah it looks like you haven't installed a few dependencies
Should i try pip install aioredis
So you will need to pip install them. Usually projects have a requirements.txt or use a package manager
Yup
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
oo
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
When I get home, I will show
A 403 error is usually due to authentication failing, or wrong permissions
No this means the bot has no permission not the user.
I use fork
"if it has a requirements.txt file"
Oh
Ohh ok so i need to give it all permission on discord server?
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 **
You need to pass it as value you can't just paste in the variable like that.
how to pass it as value?
How to get that
...(INSERT INTO user_data VALUES(?, 0), (message.author.id,))
thxs a lot
??
its still error
A KeyError coming from a dictionary or something?
or i need to use try
variable not existing in database
I would suggest a try / except block, and if it is not critical, just log the error and the key that wasn't found
can someone pls help me with this?? :/
its a must lol cuz its a rpg bot
Check out pandabweer's answer
if not the player wont get any output
and they wont know what is happening
it didnt work
so i cant use on_command_error for that?
Is it a command error?
Could you show what you have done?
` 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,)
""")`
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)
okok
what have i done wrongly here? @cloud dawn
use a message event as a command first of all 
You put the entire execute inside the string even the format
And with con:?
yeah
@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
tbh put a try except inside an error handler isn't the best 
why would you even do that?
cuz i need to define ctx and idk how to define it
if its not in a function
wdym?
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`')
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)
""")```
You want to catch the KeyError?
if its outside function its like this
ye
anyone can help me? with my code
whats with this `
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
then i need to put it outside?
i edited it now
the try except must be inside the function which could raise the keyerror
every function may raise that
can i just put it at last
like here
read the description of the error ;-;
@placid skiff is it possible to use message.author.id in sql insert into?
just check its return type or just change its return type?
Uhm well the easiest way to do it is to add the try except in every function you need it
https://paste.pythondiscord.com/xuquxiyagi This doesn't right. Do you know how to fix it?
gg
i rather do harder thing than repetitive work
:D
a server is generally referred to as a guild , so replace server with guild everywhere
hola blvck
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
I thought so too
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
I usually subclass commands.CommandError cause I have on_command_error for most of exceptions
i just copy paste? cuz my brain is not functioning rn
he doesn't have it in commands
well no you have to adapt it to your code lol
i create a new class call myError?
do you have to call the class? cuz i forgor
Question
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
I cant use object string in await function right?
the important thing is that the class is a subclass of DiscordException
okok
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
@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
@placid skiff 😔 never?
sorry Ashley i was frying my brain, hello btw xD
what is my_value and my_object
Pretty outdated way to send messages
Use member.send(...)
??
And yeah you have a typo
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.
Fair
discord.py KEKW
if you raise KeyError i assume that you would try to access a value which doesn't exists 
I defined it don’t worry
Why the hell do you call all the methods on bot
how to make avatar slash command?
erm
await Member.send()
await Bot.wait_for("message", check=custom_check, timeout=100)
actually i have no idea what this does
Sorry isn't that dead or abandoned
can u guide me ;-;
you don't know what KeyError does? 
who told u =.=
@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
Can someone help
ik i mean the code u gave me
!d discord.abc.User.avatar you can get avatar data from here, there are several attributes
property avatar```
Returns an Asset that represents the user’s avatar, if present.
I read on git that the author had left the project
well just substitute everything with the variables you have
it was an example i don't know your code
`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 :/
there is tons of variable
like 50+
- Create an embed (since that looks uwu)
- grab the member's/author's avatar using the
avatar.url(dpy2) [avatar_urlfor older versions] on the Member/User object - use the
set_imagemethod on the embed object - send it
give me a part of your code where it could raise a KeyError
Why not bot.send
More like #databases question and this is not how you use injections
And this is not how you make commands
i know this part but it does not works on "/"
how do i get the channel id of where the command was executed?
item.cooked_pogchop may be the key error
Use a decorator
Author.id should work on its own
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
then how to use it? teach me pls
ctx.channel.id```
Same for interactions
oh....
@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
LOL
what is item.cooked_pogchop lol
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']
Hello
that wont work, it must be message.author.id
to see who send the msg
Shortly
con.execute("INSERT INTO users (id, name) VALUES (?, ?)", (123, "nice name"))```
Assuming you are using sqlite
this is a small part of item
You basically put ? into the query and provide a tuple of args as another arg to execute
can u explain this?
but wait that code is a command
technically you can catch it in on_command_error
Well lemme find it in docs
its basically the same thing, everything else works, just the variable that does not work

im deleting that damn file
F
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
@vale wing
okok
thanksssssss
@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
but then the other parts will have error
What parts
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
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
cursor.execute 😔 con is generally used for connection
Sry haven't used sqlite for a while
`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*
and?
!d discord.ext.commands.Bot.command
@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").
Non cog implementation
second one?
Second is completely nonsense queries
You usually create tables on initialization
Not on command usage
then can u help me re-write the code pls? so that i can understand*
I am trying to explain it to you so you can rewrite it by yourself
@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)
That's the modern pedagogy concept
well if i use commands i will need to change up my entire bot script*
You would better change it not to suffer from it in the future
Any help would be appreciated
which i have worked on for so long, and so much features, that will need to change
member.add_roles(role)```
Not the bot.add_roles
The bot adds the Roles tho? Nvm
instead of changing the entire code*
Member has add_roles method not the Bot
And the bot doenst message the user on join
Help with that?
Always using old ways will keep you at the same place without progress, good developers should always learn the newer and better ways to implement stuff
could u pls teach me how to do it in my current way? cuz its gonna take forever to change it*
Personally I rewrited several huge projects with bad code to the normal ones
so is there any way to change it in the current way?
There is but it is inconvenient and confusing
@vale wing it’s not messaging user on join would ctx be better then member in my situation
it will be ok, could you please teach me the incovenient and confusing way of doing it?
May I ask what's your python knowledge level
Intermediate
i dont mind doing it the confusing way for now
First, bring out the CREATE TABLE statements to on_ready and make them CREATE TABLE IF NOT EXISTS and in commands use the statements like this
cur.execute("INSERT INTO user_data (UserID, Cash) VALUES (?, ?)", (message.author.id, 0)")```
Bad naming convention, bad db setup and a non perfect way of implementing db interactions but you asked for it
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
Sheesh
Nice project
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(),
)```
thxs ima try it now
Things like this
seems like that your website scripts screwed up
heck that to_str() method wtf did i do
or you were using a venv when you coded that project
Does Modals only work for slash commands?
well tbh venv are usefull but you have to remind to import them too when you export the project lol
For components as well
Basically for all interactions
idk how to do that..
It might appear randomly sometimes and people are wondering wth happened to their packages
my friend setup my venv
I use a other prefix then /
yeah but now my bot doesnt work
Venv setup is screwed in windows
how owuld i fix that
i use linux
Those "execution policies"
Oh cool
and now nothing is working anymore
how do i fix it
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)") ```
do you have that venv in your machine now?
since I created this modal
Do you have a folder like "venv" in your project folder?
@vale wing like this?
my friend made me move the stuff that was in my folder to a folder for a repo
That's weird code
And that's way you should learn a new way of making bots
but does it work?
@umbral night so again
With that syntax no
not anymore?
then how do i do it?
you have to find the venv folder bro or you'll have to setup the whole project dependencies again xD
oh :0, this bot was made 1-3 years ago thats why
@slate swan this one is good (I'd personally recommend going with disnake) https://vcokltfre.dev
A tutorial to help you make better Discord bots.
do you think its worth rewriting the code? its a few thousand lines*
Totally worth
Gotta tell you if you get really experienced you will rewrite it not even once
okie i will look at that
:0
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
Requests + aiohttp fire combo but wtf
Just use aiohttp
And make sure you get success status code
I-
i wonder if that guy finds his venv or he is setting up dependencies again
hi
why are you using requests for one request and aiohttp for another ;-;
Gonna publish first stable version of AIAS soon it's gonna be hot
Yes
what it is?
very well
I mean, elaborate
AI AntiSpam shortly
Cool
Currently has bugs but I almost fixed them all
congrats 
Thx
i just want a command send random tickle images
Replit?
Those are against TOS and we can’t help you with those here in accordance with rule 5
Purely hypothetical
haha XD
spamming in general is against discord ToS, weather is an user account or a normal one
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
Don't try to solicit help on ToS breaking projects. Thanks
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
As long as i dont get the help on this server everything is fine.
Right
Is my english that bad?
But you know do it at your own risk
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
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
While that may or may not be true it could easily be adapted for… other purposes
Let's move on
Ok
.topic
none lmao
Hentai
what?
Let’s try to keep it appropriate
I was honest
Ok
And, how do i make spam bots for twitch?
Nah, just kidding XD
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
Stop so
!mute 274822366708629505 3d I'll help you to not ask about ToS breaking projects on this server for a little while.
:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1650722346:f> (2 days and 23 hours).
Cool
Anyone have any bot ideas?
Make chess
Make a suggest command
chess is a good concept
Ye complex too
but its too long
Yes
all the rules
theres already lots of chess bots out there so no.
Add ludo xD
you have to think outside of the box there mate
Boring
one time use but still useful
Add antinuke
Dashboard stuff u mean
website for a bot?
Yo mee7
hi
yes
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
Yea
Seems like it's every other day that someone comes in with an issue regarding API bans with repl.it
just a question: how do you set a time like that ? Like a limit
A discord timestamp?
The .epoch command can help, but it is like this: <t:1651069269:D> -> <t:1651069269:D>
If you have a datetime.datetime object you can use discord.py's helper method
!d discord.utils.format_dt
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...
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?
int("ffffff", 16), the # should not be there tho
can i not have the bot change its presence within a task loop?
You ofcourse can
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)
0xffffff
Thank you! That worked for me
We don't help with API abuse.
bro?
you are setting up a task for 5 seconds for status and using sleep in that too ;-;
for changing the activity twice
If you increase the time it switches by * 600 then it's better. I also recommend to await asyncio sleep.
lol
so basically updating the presence twice in every 5 seconds
ok whatever i dont need it
also also, How do I make a Custom Exception for my commands?
just make a class and raise the class on error
I mean, do i inherit another one or not?
you need to inherit the Exception class
I mean, is this right?
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 ?
yeah, I really thought that would be a better choice
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 ?
on_command (event)
well, its correct :D
you can make a custom check
ho?
!d discord.ext.commands.Bot.add_check
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.
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 ?
json file 😔
ah well
yep, if it returns True, the command will function
else, its supposed to raise a CheckFailure error, or you can raise your own error class
so hum, does that mean that in every command I need to add that line that check the id ?
Bot.add_check adds it to your complete bot
each command would get that check automatically
you should rename it to InvalidType, also why is the error message all capital letters
for example in my main.py file where I gather all the cogs and run the bot I add bot.add_check?
idk :kek: and thanks
I'm confused by how i'm supposed to implement it lol
yessir, you can do it anywhere
@bot.check
async def blacklist(ctx):
return ctx.author.id in get_user_blacklist()```
like that?
Sure
and then I need to define get_user_blacklist()
Iirc that's how it works
nice :3
Well a list would be easier
return ctx.author.id in user_blacklist
I mean, if I make a json file I need to fetch that file ?
what does get_user_blacklist return?
He has to code it
I already have a fetch command anyway so it's not hard
@lofty pecan make sure the function returns a list
yes yes
oh well, then he can just return the list, or enter that list right there directly
not a dictionnary lol
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)
alright thanks ^^
U can return a dict too, it will check for dict keys
yes yes but that's annoying lol
Indeed
set_image(url=)
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Also, your error handler is eating the errors
bot.get(member.avatar.url) ? and the url is a keyword argument in set_image
That too
Can I store a list in a jason file ?
i dont understand
yes but ive never learned how, nobody will explain that to me
you know what a keyword argument is right?
Sure
ho nice
U can store it directly
that's nice !
{
"list_of_ids" : [1,2,3]
}```
well it makes it easier haha
sort of? i dont remember exactly... ik what an argument is, but i dont remember what it is if keyword comes before it
No need
isn't that a dictionnary ?
I was thinking storing in the json a list directly without any key required
thats a json content
which is basically same as a dictionary
@slate swan
you need to provide the argument name, then its value
no need of?
embed.set_image(url=self.bot.get(member.avatar.url))?
yes, what's self.bot.get tho? your own method?
The dict. He can directly save the list
uh its in a cog is that not how it works?
never knew json works that way too
I would love to see what it is 👀
is this illegal lol that's all I am asking
self.bot is correct but it does not have any get attribute
No
url = member.avatar.url is all you need
don't forget the string formatting I am not sure not using `f'Here is {member}'s avatar:' will work
okay great !
still no work
@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)
your error handler is probably eating your error
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)
Yes
I had the same issue
Add
else:
raise error
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
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
guys pls help me in #help-pear
@slate swan
theres the error i got when i remove my error handler
did you mention an member? or provide the userid /name
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]
XD i feel like that all the time
Code
Can u print data?
?
elif isinstance(error, commands.errors.CheckFailure):
pass
``` maybe this is missing
in my event cogs
anyone know how to make an imbeded message?
with open() as data:
print(data)
return json.load(data)
!d discord.Embed
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`.
No
yes doesn't work lol
Yo
It doesn't print anything?
Whats type
if I add that there is no error showing and the command doesn't work
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Ik ik
Remove that
i did
it prints the list lol
Show
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.
Can u print json.load(data)
it breaks my code
Eh?
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
{}
!jsondecodeerror
Bruhhhh i hate it when that happens
Anyways
!d
Add {} to the JSON file
Ye
U mean !tags
» dict-get
» dictcomps
» docstring
» dotenv
» dunder-methods
» empty-json
» enumerate
» environments
» except
» exit()
» f-strings
» faq
» floats
» foo
» for-else
it needs a key
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.
I don't want to make a dictionnary
Then why ur using json
It won't work if you don't have a key
why are you a using json file then? just use a regular list
Bro remove the {}
Use a txt file instead?
He's storing a list
lmao
Store in txt file ez
Sorry bruv, I'm confused what's happening with yr code rn 
Just remove the json.load(data) and return the data directly and u will be fine
I just made a list inside my code
Imagine bot crash
still doesn't work
Error?
discord.ext.commands.errors.CheckFailure: The global check functions for command leaderboard failed.
Lmao use sqlite... more eligent way of doing things
still the same
I am already for something else
Wait wait wait wait
but that's so small I don't need a fancy database
By any chance... is it your ID in the JSON?
no
Why are you using a json then?
because I don't need to make a fancy sqlite database file for 3 ids lmao
Txt file!!
If it's only 3 then store it locally in the code
omg fortunately i'd be so annoyed
Idk
that's what I did
If its in mutal server u can msg ig
@lofty pecan i have an idea
yes yes
In .py file... Not json
I fricking forgot how checks worked, but i have another way
hmm

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)
Cool
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.
so cog listener ?
