#discord-bots
1 messages · Page 968 of 1
or discord.ButtonStyle
Yeah
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Hello everyone
Ig it is "Forbidden" or some other HTTPException
It's a discord.Forbidden
Heyo, i would like to check if a user has a role by id. I have a json containing id's of role and would like to compare the list of roles of the user and the authorized roles but honestly I don't understand how to access the role list of the user and then compare both ids lists
the condition would look like that if (ctx.message.author.guild_permissions.administrator) or (check role):
async def dbconn():
try:
conn = mariadb.connect(
user="user",
password="pass",
host="1.1.1.1",
port=3306,
database="bot_whitelisted"
)
except mariadb.Error as e:
print(f"Error connecting to MariaDB Platform: {e}")
sys.exit(1)
try:
cur.execute(f"INSERT INTO whitelisted_guilds {guildids} VALUES (?, ?)", ("Maria","DB"))
except mariadb.Error as e:
print(f"Error: {e}")
# Get Cursor
cur = conn.cursor()
@commands.command()
@commands.is_owner()
async def wlguild(self,ctx, guildid):
dbconn()
gives this error
NameError: name 'conn' is not defined even though its defined in the dbconn() function
probably because conn isn't stored
the try test if maradb.connect works
put your cur = conn.cursor() inside the try
The things here are not in correct order
thats worked
Why is cursor defined after execution
yay
Worked? Or just gave no errors 
I got it off mariadb website lol. Im testing if it connects to the db first. Then I want it to read, write and remove data such as whitelisted guilds and whitelisted ids but Im not sure where to start
Gave no errors lol
Idk about the mariadb so can't really help, but you certainly need to define cursor before doing anything to it
And yeah async functions must be awaited
Heyo, i would like to check if a user has a role by id. I have a json containing id's of role and would like to compare the list of roles of the user and the authorized roles but honestly I don't understand how to access the role list of the user and then compare both ids lists
any(r.id in roles_ids_list for r in member.roles)```
what if member isn't a variable
it's not a command that checks, it's a command that needs to check if the user has perm before running
You always have the ctx both in checks and commands
ctx.author is how you access member
oki
perfect
huh
why doenst' it work
async def addfile(self, ctx):
"""Add file to the server folder"""
id = str(ctx.guild.id)
id_user = str(ctx.message.author.id)
Name = str(ctx.guild.name)
member = ctx.author
if (ctx.message.author.guild_permissions.administrator) or (any(r.id in self.idroles for r in member.roles)):
try:
f = open(f'database\{id}\{id_user}.json')
await ctx.send(f'Database for server `{Name}` and user id `{id_user}` already exists')
except IOError:
with open(f'database\{id}\{id_user}.json', 'w+') as file:
json.dump({}, file)
n = len((os.listdir(f'database\{id}')))
await ctx.send(f'New database for server {Name} with id `{id}` created')
await ctx.send(f'There are now {str(n+1)} files in directory')
else:
await ctx.send('You do not have the permissions to do that')
full command, when I run it it says I don't have the permission
also before that I have of course
def __init__(self, bot):
self.bot = bot
self.idroles = fetch('rolesid')```
fetch just load the json file
How are the roles stored
{"464553751030661120": ["816970896841244692", "868787775229558804"], "929126352437772358": []}
They are strings
like this
And you need to compare numbers
haa
oke oke
what isyour roles_ids btw
is it my self.idroles?
Yes
Wth
Do you mean an error handler or something else
try-except or on_command_error
Oh
Try except discord.HTTPException, it is a bit of too general but should work
Np
!d discord.Guild.ban check the raised exceptions
await ban(user, *, reason=None, delete_message_days=1)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
Forbidden is most likely raised when you have no ban perms, and HTTPException in most of other cases
Ig attempt to ban an administrator is HTTPException
Why interaction.response.send_message when you can just interaction.send
Those brackets
Why do you need the followup tho
Oh this doesn't exist in dpy
Bad
Maybe wrong doc
I typically do it like inter.send()
It automatically handles everything
Again
Don't use interaction.response.send
await interaction.send(...)```
Or as @slate swan said
```py
await interaction.followup.send(...)```
Oh
project = user.connect_project(project_id=673805769, access_unshared=True) # Connect a Project
tw_cloud = project.connect_turbowarp_cloud(
username="Username") # Connect the Turbowarp cloud with an optional parameter to change the username!
tw_cloud.set_cloud_variable(variable_name="Name", value=0) # Set a Turbowarp variable
tw_cloud.get_variable_data()
```im making a discord bot but cant get this import to work its called scratchconnect i keep getting errors
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 47)
Yes and also keep only critical statements in "try" for better code readability (the critical statement is kick)
(and you're not banning the user, just kicking him)
Just bring the print and send outside
there's no need of casting every item of the json file to int. You can just store them as int in the json file instead.
^
Does it really support the ints as keys
Last time I tried it failed
But I did that like > 1 year ago
i remember doing it back in the days though
maybe not as keys
let me just check
!e py from json import dumps d = {30: "stuff", 59: "yes"} a = dumps(d) print(a)
@vale wing :white_check_mark: Your eval job has completed with return code 0.
{"30": "stuff", "59": "yes"}
@sullen shoal see it automatically converts non string keys to strings
JSON keys must be strings
!e py from json import loads d = '{30: "stuff", 59: "yes"}' a = loads(d) print(a)
@sullen shoal :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | File "/usr/local/lib/python3.10/json/__init__.py", line 346, in loads
004 | return _default_decoder.decode(s)
005 | File "/usr/local/lib/python3.10/json/decoder.py", line 337, in decode
006 | obj, end = self.raw_decode(s, idx=_w(s, 0).end())
007 | File "/usr/local/lib/python3.10/json/decoder.py", line 353, in raw_decode
008 | obj, end = self.scan_once(s, idx)
009 | json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
"JSON keys are on the left side of the colon. They need to be wrapped in double quotation marks, as in "key", and can be any valid string. Within each object, keys need to be unique."
yep, im sorry as well, i was confused with dicts and json
is there a way i can check if a message is sent by a bot or webhook?
property bot```
Equivalent to [`User.bot`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.bot "discord.User.bot")
is_system()```
[`bool`](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)"): Whether the message is a system message.
A system message is a message that is constructed entirely by the Discord API in response to something.
New in version 1.3.
thx
why does my bot respond 2 times?, that's me running through local host
what if
@bot.listen()
async def on_message(message):
await bot.process_commands(message)
😳
hei i want to make a discord bot that icks a user from the server after a certan amout of time, is that possible and where would i start
role = message.guild.get_role(903973565152526376)
if role in message.author.roles:
```you know how i can do this with permissions?
to check if he has a permission
Well you can check the author
Traceback (most recent call last):
File "main.py", line 17, in <module>
from cogs.AntiChannel import AntiChannel
File "/home/runner/BoilingHopefulDiskdrive/venv/lib/python3.8/site-packages/cogs/init.py", line 7, in <module>
from .shell import Shell, ArgDsc, OptDsc, Failure
File "/home/runner/BoilingHopefulDiskdrive/venv/lib/python3.8/site-packages/cogs/shell.py", line 276
except (Failure, IOError, KeyboardInterrupt), exc:
^
!d discord.ext.commands.has_permissions
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Forgot the damn s
Anyone?
👍
!d help
help([object])```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).
This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
Traceback (most recent call last):
File "main.py", line 17, in <module>
from cogs.AntiChannel import AntiChannel
File "/home/runner/BoilingHopefulDiskdrive/venv/lib/python3.8/site-packages/cogs/init.py", line 7, in <module>
from .shell import Shell, ArgDsc, OptDsc, Failure
File "/home/runner/BoilingHopefulDiskdrive/venv/lib/python3.8/site-packages/cogs/shell.py", line 276
except (Failure, IOError, KeyboardInterrupt), exc:
^
SyntaxError: invalid syntax
Yeah this checks the author's perms if he has the permissions you're looking for
The comand will work else it'll throw a MissingPermissions error
Hello kayya
Pog you said full name

Are you asking him to write code for you
He has
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Prefer?
@slate swan 
Lmao
Just click
Says no and yet stll sends the link

Why else would you send the link if you don't want him to wite code for you?
Well kayya can check it here
Ok
is it possbile to check if a user is_owner OR has a certain permission to execute a command?
@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the person invoking this command is the owner of the bot.
This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.is_owner "discord.ext.commands.Bot.is_owner").
This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
I got that bit, but if I add @commands.is_owner wont it stop the @commands.has_permissions()?
or will they run simultaneously?
how can i make it so that a new voice channel will be created if a user joins a specific voice channel?
no there's the check_any decorator to combine both conditions
yikes how would I implement that
@commands.check_any(
commands.is_owner(),
commands.has_permissions(...)
)```
if one or more are true then it passes, and if both fail then a CheckAnyFailure is raised
anyone can help?
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
if they're in <5 guilds or something like that
ah its documented in create_guild,
Bot accounts in more than 10 guilds are not allowed to create guilds.
despite not having perms im still unable to execute the command even though commands.is_owner is true
C:\Users\suraj\Music\dark-sec>python main.py
Traceback (most recent call last):
File "C:\Users\suraj\Music\lark-sec\main.py", line 14, in <module>
from dotenv import load_dotenv
ModuleNotFoundError: No module named 'dotenv'
C:\Users\suraj\Music\lark-sec>
any error in the console?
^ you're missing the python-dotenv package
that i don't have admin perms
hm that should have been wrapped inside a CheckAnyFailure though
can you show the code for your command
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
@commands.command()
@commands.check_any(
commands.is_owner(),
commands.has_permissions(administrator=True)
)
async def purge(self, ctx, num):
try:
num = int(num)
except:
embed = discord.Embed(title=':no_entry: Error Purging!', description='Please input a valid number.\n(`.purge` `<number>`)')
return
await ctx.message.delete()
deleted = await ctx.channel.purge(limit=num, check=lambda msg: not msg.pinned)
reply = await ctx.send(":bomb: Deleted {} message(s)".format(len(deleted)))
await reply.delete(delay=10)
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Wht
o lol
Ye that worked lmfao, sorry for wasting your time
why convert num to an int? just type hint it
Its a snippet from a friend
Ive not modified it
mhm
his nuke command is amazing as well, it nukes the channel whilst keeping pinned messages
posts them as a webhook
@client.command()
async def say(ctx, message=None):
if message.author.guild_permissions.administrator:
await ctx.send(message)
else:
await message.channel.send('**__Access denied for this commands.__**')
I was just testing a kick command in my friends server without permissions, and when I tried to use the kick command it says discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions is this to prevent abuse?
i used the @commands.check_any()
anyone?
whats the problem?
Done now?
Is it possible to kick a user from a guild on ban in another guild?
Yea
if message.author.guild_permissions.administrator:
AttributeError: 'str' object has no attribute 'author'**
**```
As long as the bot is in both the servers
you can listen for the on_member_ban event and then find the other guilds they're in with .mutual_guilds (not sure if this property requires the members intent according to the source the member cache is used, so members intent is required)
Did u define message = ... somewhere?
Non-documented features as in private/internal methods?
Wouldn't they just document them later?
If it's exposed API
CommandTree is documented
I mean, if you decide to use something that's in alpha, isn't that pretty much on you?
hi so im working on a bot with some ppl and we encountered a warning that we are not aware of
we dont really know if this warning is an issue or not but we were worried so we tried finding solution
main.py:17: RuntimeWarning: coroutine 'Command.__call__' was never awaited
print("BOT ONLINE XD")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
the code near line 17:
15. @bot.event
16. async def on_ready():
17. print("BOT ONLINE XD")
18. await bot.change_presence(activity=discord.Game(name="P.help | Phizo"))
we tried googling it but we are unable to find the solution
Do you have another function named print in your code?
yes my partnerchanged that i noticed it thank u
So in my kick command, Im trying to get the bot to display the kicked user's avatar as the thumbnail, when I do like this is gives an error
embed.set_thumbnail(member.avatar)
what am i doing wrong?
Try
embed.set_thumbnail(url=member.avatar.url)
So if I was wanting to have it kick the user in all mutual guilds, I assume I would get that and then loop kick on that?
line 68, in kick embed.set_thumbnail(url=member.avatar.url) AttributeError: 'NoneType' object has no attribute 'url'
@commands.command()
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, member: discord.Member, *, reason=None):
if reason==None:
reason=" No reason provided"
embed = discord.Embed(title=':White_check_mark: Successfully Kicked!', description=f'{member.display_name} has been kicked. Reason: `{reason}`.', color=0xff0000)
embed.set_thumbnail(url=member.avatar.url)
embed.set_footer(text="Requested by: {}".format(ctx.author.display_name), icon_url=ctx.author.avatar)
await ctx.send(embed=embed)
await ctx.guild.kick(member)
sorry, member.avatar_url
are you in 2.0?
If the user does not have a traditional avatar, None is returned. If you want the avatar that a user has displayed, consider display_avatar.
use member.display_avatar
Hi , can anyobody pls tell me how to import Buttonstyle
from discord import ButtonStyle
Whats do u call for a user's name to display their name and tag?
str(user)
ok thx
no i mean in terms of member.(what goes here?)
Use str will give you name#1234
module 'discord' has no attribute 'Buttonstyle'
Its showing this :(
Capital s on style
then you didnt save the file
im on replit
who would've thought
I don’t see why u couldn’t use str but f”{user.name}#{user.discriminator}”
How to get user id from username in discord py
await convert(ctx, argument)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError") derived exception as it will properly propagate to the error handlers.
Hi, I would like to know how to take a random name from a text file containing many names.
Do a command >name and the bot will choose a random name from the file. I know how to open a file etc but to choose a random data I don't know
random_name = random.choice(file.readlines())
just this line is enough?
it chooses a random line from the read lines of the file
how
commands.UserConverter().convert(ctx, “some name”)
await it
still not working
Can bot delete a channel?
For example:
If I used this code to create a channel
await create_channel(name)
And then I want to delete the same channel the bot just created in this command
Is this possible?
What’s it showing
Try replacing UserConverter with MemberConverter
displaying entered username 💀
i dont understand the error line31
Do member = commands.MemberConverter().convert(ctx, “name”) then get the id with member.id
finally
tysm
!d discord.Guild.get_member_named
get_member_named(name, /)```
Returns the first member found that matches the name provided.
The name can have an optional discriminator argument, e.g. “Jake#0001” or “Jake” will both do the lookup. However the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work.
If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not lookup the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique.
If no member is found, `None` is returned.
Changed in version 2.0: `name` parameter is now positional-only.
🙂
a little bit i'm still a beginner
..
You should learn python first at least basics
ik but before Can u help me to chose one name randomly?
Use f.readlines() on line 31
done
Is there a way to mute members using timeout? I can't find when searching the documentation. It being up the heartbeat timeout stuff
ic
what library are you using?
Dpy 2
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").
You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to use this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.edit "discord.Member.edit").
exists
i did the command in discord and i have this error
file = open('ListTagsChecked.txt', 'r')
@client.command(name="4gen")
async def four_gen(ctx):
random_tag = random.choice(file.readlines())
await ctx.send(random_tag)
Hey so I have a hex color as a string: "ffffff"
How do I turn it into a color? Ex: 0xffffff
@commands.Cog.listener("on_command_error")
async def error_h(self, ctx: commands.Context, exc):
if isinstance(exc, ErrorClass):
print("error")
elif isinstance(exc, ErrorClass):
print("error2")``` How do I define ErrorClass ??
int("ffffff", 16)
Thanks! 👍
you dont define that, discord has predefined error classes
!d discord.ext.commands.MemberNotFound like this one
exception discord.ext.commands.MemberNotFound(argument)```
Exception raised when the member provided was not found in the bot’s cache.
This inherits from [`BadArgument`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BadArgument "discord.ext.commands.BadArgument")
New in version 1.5.
sys.pycache_prefix what does this do?
!d sys.pycache_prefix
sys.pycache_prefix```
If this is set (not `None`), Python will write bytecode-cache `.pyc` files to (and read them from) a parallel directory tree rooted at this directory, rather than from `__pycache__` directories in the source code tree. Any `__pycache__` directories in the source code tree will be ignored and new .pyc files written within the pycache prefix. Thus if you use [`compileall`](https://docs.python.org/3/library/compileall.html#module-compileall "compileall: Tools for byte-compiling all Python source files in a directory tree.") as a pre-build step, you must ensure you run it with the same pycache prefix (if any) that you will use at runtime.
A relative path is interpreted relative to the current working directory.
hello, how i can use this event, without creating another ( i already have 1 event )
async def on_member_join(member):
channel = alfred.get_channel(790274325533378682)
embed=discord.Embed(title="Welcome!",description=f"{member.mention} Just Joined")
await channel.send(embed=embed)```
By using @bot.listen() instead of @bot.event
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").
Example...
are you using the open function?
it's good I succeeded it didn't come from there I forgot encoding utf8
thanks
how to fix this error:
Command raised an exception: IndexError: Cannot choose from an empty sequence```
file = open('ListTagsChecked.txt', 'r', encoding='utf8')
@client.command(name="4gen")
async def four_gen(ctx):
random_tag = random.choice(file.readlines())
await ctx.send(random_tag)
embed = discord.Embed(title="TAG GENERATOR v1.0", colour=0x298FE3)
embed.add_field(name="\u2800", value=f"├ #️⃣TAG ➝ {random_tag}\n├ 📝Name ➝ ...\n├ 🏡TownHall ➝ ...")
await ctx.send(embed=embed)
this is the code I'm using
Is it possible to make a role icon the emoji in a select menu or can it only be an emoji?
• gitpython
• ipython
• kivy
• lark
• matplotlib
• more_itertools
!d discord.Member.unban
await unban(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Unbans this member. Equivalent to [`Guild.unban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.unban "discord.Guild.unban").
!d kivy
Kivy is an open source library for developing multi-touch applications. It is cross-platform (Linux/OSX/Windows/Android/iOS) and released under the terms of the MIT License.
It comes with native support for many multi-touch input devices, a growing library of multi-touch aware widgets and hardware accelerated OpenGL drawing. Kivy is designed to let you focus on building custom and highly interactive applications as quickly and easily as possible.
With Kivy, you can take full advantage of the dynamic nature of Python. There are thousands of high-quality, free libraries that can be integrated in your application. At the same time, performance-critical parts are implemented using Cython.
See http://kivy.org for more information.
Whom ever is spamming reactions, it gets you rate limited pretty easy.
is there a way to make a slash command that is only visible to me?
To a specific guild yes not user.
specific channel?
nope
pretty annoying if you wanna make moderation controls on the bots main server
Just a guild.
can restrict it so only i can use it but still messy
But u can run ur slash command in ur bot's dms
Well just one guild and making a bot check is not that much work tbh.
And u can make it only works in the dms(for u only u)
once permissions v2 comes out dpy will make something like this
it's more the visuals of everyone on that server seeing all the dev controls
but it will just be grayed out
users will be able to see all commands
U can create a private server just for u

i like having a moderation channel that people can view but not send messages in 
that way they can see stuff like whos getting banned but i guess i can reroute messages and stuff if i really wanted
async def on_error(self, error: Exception, item: discord.ui.Item, interaction: discord.Interaction) -> None:
if interaction.response.is_done():
await interaction.followup.send(f'{utily.error} An unknown error occurred.\n**Error:** {error}', ephemeral=True)
else:
await interaction.response.send_message(f'{utily.error} An unknown error occurred.\n**Error:** {error}', ephemeral=True)
raise error
``` not working
like i am getting error but its not sending it
How? Afaik there is nothing in the API for that.
yeah its not in it yet
Oh i read it wrong.
!d random.choice
random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
you know why the command is done only once and after that puts this error message?
code?
I read that but i dont understand
is the file empty? 🗿
no
dunno what's causing the issue then tbh, you should try running the command again
Can u print file.readlines()?
idk I can't try rn i dont have my computer
Can I get message object in view class?
how do I disable all 5 buttons if 1 of them have been clicked ?
.
do I replace view with the class for the nextcord.ui.View
yes
I mean I have command that has button to delete a message elsewhere with the message id but i can't get the message object in view class with id
Oh wow there's little activity here.. anyways the issue is that after the first time, reading more from the file is reading from its end so to Python the file might as well be empty. You need to add .seek(0)
for button in ShopButton.children:
button.disabled = True
await interaction.message.edit(view=ShopButton(interaction.user))```
like this ?
I think so
wait
AttributeError: type object 'ShopButton' has no attribute 'children'
Ah, weird. Never knew that can be an issue. Always thought Python read from the start
yeah it's not an instance, it's a class
!d discord.ui.View.stop exists
stop()```
Stops listening to interaction events from this view.
This operation cannot be undone.
you should've made something like my_view = ShopButton()
then in your command or dunno, await ctx.send(view=my_view)
and you can edit the buttons through
for button in my_view.children:
or, if in the view,
for button in self.children:
yeah but if I use this i'll delete the button message but that's not what I want
Anyone help, I’m tryna do a python discord bot and getting this error when doing the command
class MyView(ui.View):
...
def some_function(self):
print(self.message.id) # You can access message inside the view subclass
@bot.command()
async def my_command(...):
view = MyView()
view.message = await ctx.send(view) # this is important!
You need to actually install discord.py. Also, could you send the traceback in a codeblock, rather than a picture?
You need a : at the end of functions
at the end of the function signature!
bro
is that valid
@sick birch I am getting this right now
Well
def a
puts "bro"
end
a
"'Await' outside function"
😏
I don't think it could be any more clear
That's not the issue
The issue is using await outside of asynchronous functions (coroutines)
that explains it
Youtube videos for discord.py suck, I don't know how they keep getting away with terrible code
How did u learned coding?
Me? I learn by doing, not by following tutorials
That might not work for everyone however
but how can u start doing when u have no idea what u should do
many people learn by making discord bots, which is a fantastic way to learn
The documentation and examples are a good place to start
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
https://github.com/Rapptz/discord.py/tree/master/examples examples are here
is there also a documentation for giveaway bots?
Not quite how it works
Documentation outlines what functions and classes do
You need to compose said functions and classes to make cool things
And here's the official docs: https://discordpy.readthedocs.io/en/stable/
learn some basic python before trying to make a bot or you'll get confused very quickly
Giveaway bots aren't that hard. I've made plenty in my time, I have faith you'll get it as well :)
alright, will look into it! Thanks guys. Doing this to learn myself coding discord bots for nft servers haha
I believe that videos are inherently flawed in terms of medium
That's great - learning by doing something you like is one of the best ways to learn something
😎 , speek to you soon! 👊
Because of this, it's difficult to create good tutorials, for something such as discord.py, using the medium
Yup. Feel free to ask if you get stuck along the way, we're all here to help each other out, at the end of the day
❤️
how are you using the term medium here
?
Hm?
Is this not working?
It LGTM
no
?
The code itself looks good to me
Yeah looks fine
Are you getting any errors?
Python 0 is an indicator of the format method that you need to be replaced by the format’s first (index zero) parameter. It is used to execute a string formatting operation. The formatted string argument contains a literal text or replacement fields delimited by braces { }.
No clue lol
It's better to use f strings
how can i make a per send embed message it count? like this
do you have a example?
!e
first_name = "John"
last_name = "Doe"
age = 42
print(f"Hello, my name is {first_name} {last_name}, and I am {age} years old.")
@sick birch :white_check_mark: Your eval job has completed with return code 0.
Hello, my name is John Doe, and I am 42 years old.
As opposed to
first_name = "John"
last_name = "Doe"
age = 42
print("Hello, my name is {0} {1}, and I am {2} years old.".format(first_name, last_name, age))
Indeed it is!
😄
can someone help me with this?
It's a confession bot, I wanna make a message counting sent by the bot
You could store confessions in a database, and use SQL's count feature to count them
Aight thanks !
what would be the best way to check if a number is in a constant changing range of numbers i.e.
if number in range(0, 10):
if number in range(100, 110):
if number in range(200, 210):```
Can we get some context?
trying to get a map to generate an image at a steady rate but not all the time
so every 100 levels they see x
for 10 levels
without having to save data would be best, but the maths is
if number in range 0,210 would generate the image for 0 to 210
i want it every time they hit a multiple of 100 for 10 levels or similar
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | 0 10
002 | 100 110
003 | 200 210
004 | 300 310
005 | 400 410
006 | 500 510
007 | 600 610
008 | 700 710
009 | 800 810
010 | 900 910

How do I install discord py on python 3.10
for i in range(0, 1000, 100):
if i + 10 > map_level > i:```
this works but it's an infinitely generating map
so it would have to in theory check from 0, infinity
i could divide it by 100 and then use the remainders
if map_level % 100 < 10:
would this work 
that would require saving counts for every player
@slate swan how can u type that with these colors
count = 0
while True:
if number in range(count, count+10):
...
count += 100```
Checking it in a range would be pretty in-efficient though right?
i think the remainder system will work if im not being dumb
!e
for i in range(0, 1000, 100):
print(i, i+10)```
Wouldn't it be best to do if 0 < n < 10:
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | 0 10
002 | 100 110
003 | 200 210
004 | 300 310
005 | 400 410
006 | 500 510
007 | 600 610
008 | 700 710
009 | 800 810
010 | 900 910
100/100 = 0, 100/101 = 1 and 1 left over etc.
so if map_level % 100 < 10
should work right 
ill test it with smaller numbers
yeah it works
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
How do I enable the message content intent?
!d discord.Intents.message_content
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
• The message was sent by the client
• The message was sent in direct messages
• The message mentions the client
This applies to the following events...
Why do you need to enable it? It won't do anything until it is enforced I think
It's off by default
And it will be enforced since august 31
Well I don't have that intent on in disnake (because of some inner disnake errors) and I can still receive messages content
I meant on the dashboard
Oh
So you have to enable it on dashboard but don't have to tell the gateway you need events with that intent?
Is there anyone to help?
Go ahead
I'm not seeing how that's related to discord bots
server.py:688: DeprecationWarning: There is no current event loop
asyncio.get_event_loop().run_until_complete(start_server)
I can see that, but it's probably best to ask in #async-and-concurrency
server.py:689: DeprecationWarning: There is no current event loop
asyncio.get_event_loop().run_forever()
Yes, I can see the error, but again, best to ask in #async-and-concurrency
with open('logs.json', 'r') as f:
log_channels = json.load(f)
@client.command(name="logchannel", aliases=["setlog","setlogchannel"],description="Sets the log channel for your server logs")
@commands.has_permissions(administrator = True)
async def modlog(ctx, channel = None):
log_channels[str(ctx.guild.id)] = channel.split()
with open('logs.json', 'w') as f:
json.dump(logs.json, f)
await ctx.send(f'Log channel set to {channel}')
``` anything wrong with this?
Hard to tell; any errors?
Yeah one like I've never seen it before
Let's see it
It's HTML code lol look
Should I do pip install discord or pip install discord.py?
Both work
The docs say to use discord.py
And after that it's just html
pip install discord will work too
You're getting ratelimited
Are you using replit or heroku?
Replit atm
I mean theres no other way for me right now to do it, I was using heroku but I just want to use json files for some things
I don't understand databases that well yet
I do that but it doesn't install the latest
Why not just do it locally?
Won't run 24/7
Any idea for how long that is tho
Hm, look into free tiers of reputable service providers like like AWS then
From my experience approx 30 minutes
That free?
I mean I know replit is just bad but yeah
The t2.micro instances are free, yes
How do they work with discord bots?
They're virtual computers in the cloud, so you can SSH in and run anything you want on them
Install python on them, and run the python file like you would normally
How do I update from 1.7.3 to latest?
That's what I'm doing at the moment
So also json files work on that
Well, i'm using docker but same concept
Yes, if you can do it on your local computer you can do it there
They're just regular computers in the cloud that you can "rent"
That's basically a computer but with command line interface
Ah nice
It's a regular computer like any other, it has an OS and everything you need
For free?
If you need a guide on VPS setup for hosting discord bots I can give you one
Yes, t2.micro instances are free. Everything up costs money
I'm using t3.small
Sure, is that for AWS?
AWS interface isn't the most intuitive but you'll get it
Oh about docker, can you tell me how to mount a single file into the container
https://aws.amazon.com/ec2/ more info here
Choose ubuntu when selecting AMI or smth
Oh lol, I've never messed with mount points and binding i wouldn't be able to tell you :(
Ok ☹️
I'm not all that big on devops and I'm rubbish with devops tools
Or, should I say, #dev-oops
@junior verge setup guide here (python should be installed on amazon) https://gist.github.com/Exenifix/a8aa68a4976389757ff3121e6daadcf6
How do I update from 1.7.3 to latest?
I'm going to a uni with the name: expert it systems and devices, pretty cool
Very cool guide!
Ty 👍
Maybe you can make one for docker too
That would require some explanation about docker
pip install -U git+https://github.com/Rapptz/discord.py/
true
Enter this command in your shell ```py
pip install -U git+https://github.com/Rapptz/discord.py.git
https://github.com/git-guides/install-git#:~:text=To install Git%2C run the,installation by typing%3A git version If you want to know how to install git
Shortly: google "git", go to git website, find download tab, download and install
Ok, I have installed that. Should I do import discord in my code?
Of course
But therefor I need to do things on aws first right
yeah
you need to create a new instance, pick the specs, that sort of stuff
making security groups
all that fun stuff
So it's basicaly just a vps?
Not really
Find EC2 -> instances -> new instance -> ubuntu -> t2.micro -> skip to the end -> launch instance
I think that
seems hard
AWS is one of the largest hosting providers in the world, with over 200+ services
Some of the largest companies use them which explains the terrible interface for regular users
You figure out how to find your way around soon enough though
make sure to download .pem and keep it safe
Uh im on my laptop rn do I gotta be on pc
Digitalocean has good interface but you can use it for free only for 2 months
it's all online
Tho you can get a very good server
I don't have my code here tho
that's fine just set it up and do the code later
Sure, let me try and do it
iirc they give you 700 hours of t2.micro instances every month
That should be enough
That's about how many hours are in a month so they're effectively locking you into only using one instance
Yeah the cool thing is you can expand the volume while keeping all of its contents
8gb is very little
Since most of the components of an instance are isolated
can u invoke a slash command inside code
for example you have to allocate an elastic IP and associate it to your instance
I need to add a billing adress...
Unfortunately no
Alright
Yes that's ok
I mean I don't have that, I'm 15.
If you already have an amazon prime account that should work as well
I got my dutch bank but they don't accept that
That's unfortunate
Why tho
Why what
They should accept your bank
Your billing address, as in your credit card info?
I don't have a credit card
Afaik only USA has address card verification
Oh
If you stay below the limit they won't bill you anyway
Is there any other way?
I think they require the card credentials to create an account
Not that I know of
Most decent hosts will require it
very unfortunate
I like want custom log channel but I just don't know how to do that, and with mongodb you can only use 1 database
A logging feature isn't that hard, I have one for my bot
though it uses postgres
the data model is pretty different
Yeah heroku got it I saw but no clue on how to use that lol
I mean just a command like .logchannel #bot-commands and for example I can load in my cogs just like channel.send etc if you get me
Me neither. I usually just feed the connection URL into an ORM like prisma and it handles everything for me
Actually that's exactly what I did for my bot
I just got no clue what to do
Replit won't let you set up an sql server so you have to figure out how to get that in heroku
With heroku I don't use replit
I just use visual studio code with git connected to my repository
Yeah well, are there any tutorials on how to do what I am looking for with postgres?
Not that I know of. I've never used heroku, thankfully
i may have found a way!
Well, got any idea for me on how to do what I want
whats ur issue?
Not sure about that. I'm 99% sure that's not possible
Don't really have a issue
im not really using await ctx.invoke
async def coolCallback(ctx, a, b):
s = a + b
await ctx.respond(f"Like bro, {a} + {b} is {s}.")
@bot.slash_command()
async def functionOne(ctx, a: int, b: int):
await coolCallback(ctx, a, b)
@bot.slash_command()
async def functionTwo(ctx, a: int):
b = a * 2
await coolCallback(ctx, a, b)
``` eexample and id just share the results of coolcallback
Ah you're taking that approach
Is their something wrong with it?
I thought you actually wanted to call the slash command from discord
pep8 moment
Why not just call command function from a command and parse interaction manually to there (that's weird but works)
I don’t have a ss but in getting the error on my bot now of get_config after using the command
I’m not on laptop rn so can’t ss
i want to invoke a slash_command and this is the best way too do it ** I THINK**
@sick birch Any idea
Idk what library you use
What, setting up a database or a log channel command?
I mean like both yeah, with using heroku it must be a online database
google cloud should be better than heroku
😳
lol it IS
anything is better than heroku
even leaving your pc on all night?
yup
replit hacker plan is
Not needed with heroku lol
i do that a lot
replit hacker plan is 24/7 running code
What should I use to host my bot then for free
Buy a raspberry pi
its only 2$
without billing adress
their isnt much
Heavy initial investment but worth it over time
The one I got was $120 but I'm pretty sure some of the older models are ~ $40
You can do other stuff to it as well
ssh onto it, run your python file
Yeah I was planning on buying one
Just for other fun stuff too, just to play around with it
for sure
In summer I am gonna build a server from my old motherboard and host bots there
How will you run your python file on it there?
Upload your bot files to github, install github on raspberry pi, then git clone
If you install ubuntu to it that guide would still be suitable
With a rasberry pi you connect it with a usb to your pc right?
What's that?
Oh from your pc?
Basically connecting to the server, executing commands and receiving their output
Say your raspberry pi had an internal ipv4 of 192.168.1.69, you can log onto using the following command:
ssh root@192.168.1.69
From there you have access to the raspberry pi's root account
Seems hard
So you can do anything to it as if you physically had a keyboard and mouse hooked up to it
You can use SSH UI interface app such as termius
Well that's the standard way to control remote computers
So you will need to have a keyboard and mouse plugged in the rasberry pi?
No, into your computer
Or a laptop
Yeah you'd just boot up a terminal on your computer or laptop and use the ssh command to log into it
Just the power cable
Not even ethernet?
The newer ones have wifi
ah
Why do I receive this error when trying to use cogs (first time)?
bot.load_extension(f'cogs.{filename[:-3]}')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Go for it Robin
They updated load_extensions to be coroutines in 2.0
You need to await them now
Oh ok
Now your next question would probably be where, since you can't await outside async functions
The answer to that would be in the setup_hook which was introduced in 2.0 as well
So what should I do for a fix?
Await load_extension
Can't await outside of function.
just got raided by 661 accounts in a server i run, any simple code i can get just to grab all the user ids that joined between 2 timestamps? or perhaps you know of a bot already
Are those accounts still in your server?
If so discord has a native prune feature
Sorry I'm confused on what to do for a fix tho.
if you're referring to the one in the members tab i dont really want to use that.
You need to append await in front of load_extension
Oh. In that case you can loop through all of the members in your server, and check the time they joined
:incoming_envelope: :ok_hand: applied mute to @worn onyx until <t:1649630187:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 186 newlines in 10s).
wdym, like this?
await bot.load_extension(f'cogs.{filename[:-3]}')
yes its a coroutine
Traceback (most recent call last):
File "/home/runner/tester/venv/lib/python3.8/site-packages/discord/ui/view.py", line 371, in _scheduled_task
await item.callback(interaction)
File "/home/runner/tester/cogs/rostermenu.py", line 23, in my_callback
await getros(ctx,role=select.values[0])
File "/home/runner/tester/roster.py", line 51, in rostercall
await ctx.respond(embed=embed, ephemeral=True)
AttributeError: 'Context' object has no attribute 'respond'
```!?
the Context object doesnt have that attr
only Interaction
i tried interaction aswell
await bot.load_extension(f'cogs.{filename[:-3]}')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: 'await' outside function
``````py
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
await bot.load_extension(f'cogs.{filename[:-3]}')
it needs to be in a coroutine
Traceback (most recent call last):
File "/home/runner/tester/venv/lib/python3.8/site-packages/discord/ui/view.py", line 371, in _scheduled_task
await item.callback(interaction)
File "/home/runner/tester/cogs/rostermenu.py", line 23, in my_callback
await getros(ctx,role=select.values[0])
File "/home/runner/tester/roster.py", line 51, in rostercall
await interaction.response.send_message(embed=embed, ephemeral=True)
AttributeError: 'Context' object has no attribute 'response'
``` getting this error for interaction
also if your wondering getros is a function
async def rostercall(ctx, *,role):
i am usig pycord, and im using it inside a dropdown menu command
alright
what is the hex code for colorless embeds
just dont add a color
thats not colorless
theres no such thing as a colorless embed
there is..
show
its called, same hex as discord background
which is what im asking for
@slate swan is this an embed?
it seems odd to me
lmaoo
because embed always have a color i.e here its default
bro, i know how embeds work. im asking for something specific. if you dont have it then as rude as it sounds move along :/
im not being rude?
i know, im just saying
ik what i want and ik its a thing, i just dk what the hex is
that still wont be invisible for all clients
ty
mobile and desktop client yes
Modded client users trembling rn
more like a csgo flash bang lmaoo
Light theme is like this generations gore
@slate swan
top one i found on reddit, bottom is yours. i think its actually colorless
bro
look at the borders if u dont know what i mean
one is squary one is round
idk its weird
should be black because of your bots pfp!
How do you make it like that?
The embeds are so clean
embeds are cleaner in light mode for sure
lmfao light and compact mode
Hi
db = sqlite3.connect(bot.sqlite)
cursor = db.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS main(
guild_id TEXT
guild_name TEXT
)
''')
Gives me the error db = sqlite3.connect(bot.sqlite) NameError: name 'bot' is not defined
Im following a tutorial and I've done exactly what hes done but idk why its not working
Don't follow tutorials
I hate to be blunt but most of them suck. The one you're following clearly does because they suggested you use sqlite3
what else would I use?
The documentation
for a db I mean
Oh, you'd use aiosqlite
how do i fetch the reactions on a single message? i tried fire_reactions = get(game_message.reactions, emoji=fire) but it always returns none for some reason
Or aiohttp if you want to go for a RESTful graphql-like system
no Im keeping it local
Then you'd use aiosqlite
bot will only be in 3 maybe 5 max servers
I don't know why the youtuber thought it was a good idea to suggest using sqlite
!d discord.Message.reactions
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
tried doing what the docs say but game_message.reactions always returns []
Then it has no reactions
well that can't be right cause i can see 2 reactions on it
ah well thank you anyways
i'll keep testing stuff
would it matter if game_message = await ctx.send("blahblah")?
Anyone able to help me setup a guild whitelist command where it puts the guild id in an aiosqlite db after using a command like .wlguild <guildid>
Which part do you specifically need help with?
setting up the db, and not sure whether to define it globally or within each command that im going to do
this is my first time dabbling in dbs and python
@commands.command()
@commands.is_owner()
async def addwl(self,ctx, guild=str()):
db = await aiosqlite.connect(guildwl.db)
db.execute('''CREATE TABLE IF NOT EXISTS "guildwl"(
"guils_ids" INTEGER,
"guild_name" TEXT)
);''')
cursor= await db.cursor()
this is what i have rn
I see a few things wrong with this
Why are you calling str()?
db.execute() isn't awaited
I was going to change that to int
Still don't need to be calling int
And why make it default to a data type?
Also I don't think what you posted is valid SQL
Don't take my word on that though, I haven't used it in a couple of months
Oh yeah, you should be using cursor (Your database cursor) to execute SQL code, not db (Your database connection)
aiosqlite.Connection has execute method too, returns Cursor object
So something like
db = await aiosqlite.connect("ma path")
cursor = await db.cursor()
await cursor.execute("my SQL code")
It does?
So what's the point of creating a cursor object?
fire = "🔥"
flop = "🗿"
game_message = await game_channel.send(
f"Is this pattern a {flop} or {fire}? Vote open for 2 minutes.")
await game_message.add_reaction(flop)
await game_message.add_reaction(fire)
await asyncio.sleep(1)
await game_channel.send("Vote over in 60 seconds.")
await asyncio.sleep(1)
await game_channel.send("Vote over in 10 seconds.")
await asyncio.sleep(1)
fire_reactions = game_message.reactions
flop_reactions = game_message.reactions
is there anything glaringly wrong about this snippet of code? game_message.reactions always returns [] even when i react to it before it checks the reactions
disregard the incorrect sleep times
You need Cursor to fetch stuff, cause you can't fetch with Connection
Ah
I guess this is what I get from watching tutorials and not documentation
I do hate the aiosqlite documentation theme though. It's completely unreadable to me
now im more lost lol
I have no idea where to start with that since its my first time with sql in python
well i was using sqlite3 but someone said to use aiosqlite
so im using that now
or well...trying to

@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('wrong command')
why doesnt this work?
@slate swan
no
I mean sqlite is fine tough.
thanks
Does the error still get raised?
nothing happens at all
all my other commands work fine
i'm avoiding advanced stuff, even the basics is too advanced for me atm
no error in the ide, nothing happens in the channel
In what command do you expect MissingRequiredArgument to be triggered?
Plus about sqlite is that it's convenient to use it's light and easily transferable.
Where as PG is really meant to operate at one place. PG is easier to get started with thanks to it's UI
How so?
"Exception raised when parsing a command and a parameter that is required is not encountered."
What exactly do you want it to do?
say 'wrong command'
when i type an incorrect command
such as !asdiasdai
or idk
a typo
exception discord.ext.commands.CommandNotFound(message=None, *args)```
Exception raised when a command is attempted to be invoked but no command under that name is found.
This is not raised for invalid subcommands, rather just the initial main command that is attempted to be invoked.
This inherits from [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError").
thanks
Same way you coded the other exception.
@client.event
async def on_command_error(ctx, error):
exception
discord.ext.commands.CommandNotFound(message=None, *args)
await ctx.send('wrong command')
like this?
no
idk
Use this reference.
Well there you used the event and used isinstance to compare the 2 objects.
It's the same for this exception.
!d discord.ext.commands.Bot.on_command_error
await on_command_error(context, exception, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default command error handler provided by the bot.
By default this prints to [`sys.stderr`](https://docs.python.org/3/library/sys.html#sys.stderr "(in Python v3.10)") however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
Changed in version 2.0: `context` and `exception` parameters are now positional-only.
If any discord.py error occurs this events get raised and the exception object will be passed along with the context.
is ext short for exception
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await on_command_error(context, exception, /)
await ctx.send('wrong command')
i have this
is this right?
ext is short for extended since that how discord.py is constructed.
oh
Yes but instead of MissingRequiredArgument use CommandNotFound
await on_command_error(context, exception, /) this is not right.
do i have to import anything else
async def on_command_error(ctx, error): you are already defining it here.
ok
If you have commands imported no
And by the looks if it you do.
sweet thanks
how long do slash commands take to sync
An hour or less
You set it up correctly?
Yes. Bot has to be online.
ye thats why, ill let it sync
@client.event
async def on_message(msg : discord.Message):
if msg.author.id == client.user.id:
return
if msg.content == 'owner':
await msg.channel.send('@umbral night')
await client.process_commands(msg)
so at the moment, whenever i say 'owner' it pings me
how could i make it so that when someone says 'the owner' or just includes the word 'owner' in their sentence, it'll also work?
im not sure how to do that
Switch them
wdym
6.10.2. Membership test operations
The operators in and not in test for membership. x in s evaluates to True if x is a member of s, and False otherwise. x not in s returns the negation of x in s. All built-in sequences and set types support this as well as dictionary, for which in tests whether the dictionary has a given key. For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y is equivalent to any(x is e or x == e for e in y).
For the string and bytes types, x in y is True if and only if x is a substring of y. An equivalent test is y.find(x) != -1. Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True.
!e ```py
p = [1, 2 ,3]
if 1 in p:
print("Yes 1 is in list p")
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
Yes 1 is in list p
how do i check if an Asset is of a certain file format
.
Best is to read the asset that returns Bytes and use mimetype.
and how can i get total number of members in all the guilds my bot is in?
mimetype?
chan = await create_channel(name)
await chan.delete()
ah
idk if there's any other ways
im trying to make an avatar cmd and if the member's avatar is animated, it'll format the avatar url to a jpg
and for static avatars it'll format it to be a png (just an example)
sum([guild.member_count for guild in bot.guilds])
!d discord.Asset.is_animated
is_animated()```
[`bool`](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)"): Returns whether the asset is animated.
oo
time = datetime.now()
time = time + timedelta(minutes=30)
in this code i want the (minutes=30) to be user input meaning that the amount of time to be added can be user input
So you mean the kwargs?
excuse me but why is my db locking for such a simple command
i literally did ;setup and it locked the db
all my command does is insert ONE SINGLE value
wouldnt even work
After using it does one of the 2 messages appear?
you arent committing the changes
oh TEA
yes
oh yea ty i was dumb
👍
Autocommit a thing on aiosqlite?
what
You could just have a var for the int and add an arg to the command
I know mysql has autocommit
pg doesn't even have commit it just does it lol
i mean aiosqlite has the commit method which even in examples is used so i doubt it
i see nothing about it in docs
@client.event
async def on_message(msg : discord.Message):
if msg.author.id == client.user.id:
return
if msg.content == 'owner':
await msg.channel.send('@umbral night')
await client.process_commands(msg)
why does this make all my other commands not work?



