#discord-bots
1 messages · Page 792 of 1
it's lower-level
pure async http wrapper
you can connect to ws and handle events yourself
Yeah, just don't add the print statement
What
Then fetch the channel and send the messages in them
Not sure
Maybe try giving a shot in #databases
will discord.py still work in the future for a bot that merely sends some messages and uses no commands?
Yes unless Discord makes a change that completely changes their api
Ignoring exception in command bal:
Traceback (most recent call last):
File "/home/gitpod/.pyenv/versions/3.8.12/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/workspace/template-python-flask/discord/discord bot beta cog/cogs/fun.py", line 44, in bal
bank_amt = users[str(user.id)]["bank"]
KeyError: 'bank'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/gitpod/.pyenv/versions/3.8.12/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/gitpod/.pyenv/versions/3.8.12/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/gitpod/.pyenv/versions/3.8.12/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'bank'``` code: https://paste.pythondiscord.com/ucaxoginuh.py
no such key
ok but it is basicly the same for the wallet
so where do i get the key from because the wallet was working fine?
nvm i forgot it will not just write over it if it is not there
!e
d = {"akey" : "avalue"}
print(d["bkey"])
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | KeyError: 'bkey'
it works now that i removed it
python3
import random
value = random.randint(1, user_input)
print (value)
why is that not working?
!e
import random
value = random.randint(1, user_input)
print(value)
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | NameError: name 'user_input' is not defined
idk
define user_input lol
Ignoring exception in on_guild_stickers_update
Traceback (most recent call last):
File "C:\Users\SDR11\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "c:\Users\SDR11\OneDrive\Desktop\SpookyCodes\Tests\test.py", line 134, in on_guild_stickers_update
await guild.create_sticker(name=st2.name, file=before_sticker, emoji=st2.emoji)
File "C:\Users\SDR11\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\guild.py", line 2206, in create_sticker
data = await self._state.http.create_guild_sticker(self.id, payload, file, reason)
File "C:\Users\SDR11\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 335, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 0): The browser (or proxy) sent a request that this server could not understand
@spooky.event
async def on_guild_stickers_update(guild, before, after):
async for t in guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 1), action=discord.AuditLogAction.sticker_delete):
remove_sticker = [r for r in before if r not in after]
for st2 in remove_sticker:
async with aiohttp.ClientSession() as session:
async with session.get(st2.url) as response:
image_bytes = await response.read()
before_sticker = discord.File(BytesIO(image_bytes))
if remove_sticker:
#await guild.kick(t.user, reason="Anti-Nuke: Deleting Stickers")
await guild.create_sticker(name=st2.name, file=before_sticker, emoji=st2.emoji)
you sent a bad request
happens when something in your request is invalid so the apis response is a 400http code
how do i fix it?
you send valid info ig lol
im not familiar with making direct requests to the discord api
How do i make a mute command and a un mute?
hmm
Well you have 2 ways. You can either use the timeout feature or do it with the old way with a muted role
create a role in ur server called muted and make its permissions so that the person with that role cant send messages
Which would you like?
yes
timeout is easier ig
Timeout
It's not a yes or no question
ok boss
await timeout(*, duration=..., until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Times out the member from the guild; until then, the member will not be able to interact with the guild.
Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.
You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.
New in version 2.3.
Boom, simple
...
What
nothin
Hello so i made a give command idk if i did it right or not but the amount in my wallet or bank stays the same even after giving money to the other person how do i fix that?
@commands.command()
async def give(self, ctx,member:discord.Member, amount = None):
await self.open_account(ctx.author)
await self.open_account(member)
if amount == None:
await ctx.send("please enter the amount to give!")
bal = await self.update_bank(ctx.author)
amount = int(amount)
if amount>bal[0]:
await ctx.send("Your not that rich!")
return
if amount<0:
await ctx.send("Amount must be greater than zero!")
return
await self.update_bank(ctx.author,-1*amount, "bank")
await self.update_bank(member,amount, "bank")
await ctx.send(f"You gave {amount} coins to {member}!!")```
Can we see your update_bank function?
Also, please refactor your code to follow pep8
sure let me grab it
It should be member: discord.Member
????
You're missing a space
Also, you can do is None instead of == None
<@&831776746206265384>
mhm
!mute 815343303251722281 targeting a user possibly with others
:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1643682708:f> (59 minutes and 59 seconds).
oh damm
Yeah I don't know. I do the smart thing and not use json as a database
because idk how to do aliases
@commands.command(aliases = ['dep'])
Would this work
@commands.command()
@commands.has_permissions(timeout=True)
async def timeout(self, ctx, member: discord.Member):
await timeout(duration=..., until=..., reason=None)
do u want to set the duration?
You cannot copy directly from the docs
lol
Where can I find the Discord.py Rewrite repo. I looked on github, but I can't find it
idk
Discord rewrite was a long time ago. The master github can be found here: https://github.com/Rapptz/discord.py
oh, that is the rewrite repo. I thought there was a different one
what library are you using?
does anyone know why this happens
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'PrettyHelp' object has no attribute 'clean_prefix'
I am using discord.py (ver2.0a)
!d discord.ext.commands.Context.clean_prefix
property clean_prefix: str```
The cleaned up invoke prefix. i.e. mentions are `@name` instead of `<@id>`.
New in version 2.0.
use that
ok how?
also why do you use PrettyHelp? There is a tutorial on how to make your default help command better
show your code
ok
import discord
from discord.ext import commands
import json
from dotenv import load_dotenv
import os
import pretty_help
if os.path.isfile('.env'):
load_dotenv('.env')
else:
pass
token = os.environ['token']
# Get configuration.json
with open("configurations.json", "r") as config:
data = json.load(config)
prefix = data["prefix"]
bot = commands.Bot(prefix)
# Load cogs
initial_extensions = ["Cogs.Tools","Cogs.Pokemon_TCG","Cogs.Github","Cogs.Fun", "Cogs.Quiz"]
print(initial_extensions)
for extension in initial_extensions:
try:
bot.load_extension(extension)
except Exception as e:
print(f"Failed to load extension {extension}")
menu = pretty_help.DefaultMenu(page_left="◀", page_right="▶", remove="❌")
bot.help_command = pretty_help.PrettyHelp(menu=menu, no_category="Commands")
here @boreal ravine
show the full error
ok
Ignoring exception in command help:
Traceback (most recent call last):
File "C:\Users\sasen\OneDrive\Documents\SDP_Coding_02\python\discord\Zacian-Empire-Utility-Bot\venv\lib\site-packages\discord\ext\commands\core.py", line 167, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\sasen\OneDrive\Documents\SDP_Coding_02\python\discord\Zacian-Empire-Utility-Bot\venv\lib\site-packages\discord\ext\commands\help.py", line 831, in command_callback
await self.prepare_help_command(ctx, command)
File "C:\Users\sasen\OneDrive\Documents\SDP_Coding_02\python\discord\Zacian-Empire-Utility-Bot\venv\lib\site-packages\pretty_help\pretty_help.py", line 297, in prepare_help_command
self.paginator.ending_note = self.get_ending_note()
File "C:\Users\sasen\OneDrive\Documents\SDP_Coding_02\python\discord\Zacian-Empire-Utility-Bot\venv\lib\site-packages\pretty_help\pretty_help.py", line 306, in get_ending_note
return note.format(ctx=self.context, help=self)
AttributeError: 'PrettyHelp' object has no attribute 'clean_prefix'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\sasen\OneDrive\Documents\SDP_Coding_02\python\discord\Zacian-Empire-Utility-Bot\venv\lib\site-packages\discord\ext\commands\bot.py", line 994, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\sasen\OneDrive\Documents\SDP_Coding_02\python\discord\Zacian-Empire-Utility-Bot\venv\lib\site-packages\discord\ext\commands\core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\sasen\OneDrive\Documents\SDP_Coding_02\python\discord\Zacian-Empire-Utility-Bot\venv\lib\site-packages\discord\ext\commands\core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'PrettyHelp' object has no attribute 'clean_prefix'
how do i check again? :/ .....
here @boreal ravine
Can we see your code?
@final iron the code was here
so i kinda need help with a bot ive been trying to code
looks like a prettyhelp issue
the bots supposed to respond to something, but right now it just keeps spamming the response without the keyword
Then its an issue with the module he imported
simple, what are you importing for your bot?
!pypi discord-pretty-help
And nicer looking interactive help menu for discord.py
this is the code
i am a pretty big beginner
so i may be very clueless on some things
Damn people don't even have to subclass their help command anymore
You got an error?
it just says regexGroup isnt defined
Also, please follow pep8 naming conventions. Variable names should be written in snake_case instead of camelCase
define it then?
and wont let the thing go
w ha t
very funny.
Heres a good resource, https://pep8.org
nothing was funny about that message..
They not joking:/
You're printing it outside of the function
Pretty clear error
i am like very clueless
!e
list_ = ["a"]
print(list_[1])
@final iron :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | IndexError: list index out of range
See what happens?
what python version are you using by the way?
Why don't you try to stop reinventing the wheel and use the commands extension?
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
Check out this website for a proper discord bot tutorial
thank you so much
@commands.command(usage="`tp!reason user:id`")
@permissions.has_permissions(ban_members=True)
@commands.bot_has_permissions(embed_links=True)
async def reason(self, ctx, member: MemberID):
"""Shows the reason why someone was banned"""
cmdEnabled = cmd(str(ctx.command.name).lower(), ctx.guild.id)
if cmdEnabled:
await ctx.send(":x: This command has been disabled!")
return
try:
await ctx.send(f"{member} was banned for {await ctx.guild.bans(member)}")
except:
await ctx.send(f"{member} was not banned")``` am i doing something wrong here? it says that the user hasnt been banned when they sure as hell have lol
hehe
.....
MemberID is a custom class, should have mentioned that
Okay
Variable names should be in snake_case instead of camelCase
Also, pep8 says a bare exception is a nono and its for a good reason. Remove the try/except block and view the whole error
cmdEnabled = cmd(str(ctx.command.name).lower(), ctx.guild.id)
if cmdEnabled:
await ctx.send(":x: This command has been disabled!")
return``` you can completely ignore this
alright lemme try this
When you make a try/except block you want to catch a specific error
([Mon]-09:21-PM) [ERROR]: bans() takes 1 positional argument but 2 were given``` ah hah
dead bot
I deleted the message
I wanted to see if it would return an error if a bad wasn't found
How long does it take to end up making a good bot?
bout a year
Really no answer to that question
at least in my experience
Totally depends on yr knowledge
welp then lets say about 2 years:/ lol
Nah, about 4-5 months should be enough
heres the thing tbh I can't even get a mute/timeout command up:/
and i couldn't even get a broadcast cmd up
It's fine, you just need some more knowledge
I successfully made a mute command after an year of learning
I started doing stuff with python 2 years ago
I started 1 year ago
Can you end up helping me make a warn system???? if u have time...
Can't help rn anyways, I gotta go to school
Would be glad to help after coming back, sorry
warn system is relatively simple if you make a minimal one
prolly would want to use a db also to store the number of warns, etc
Then it's easy
Once u understand the simple logic behind it, it's gonna be easy asf
I don't really feel sad, it's totally my choice if I wanna go or not
it's for your own good mate
hmmtrue
Not me. I myself told them, I want to go to school and they agreed ¯_(ツ)_/¯
sucks to be you lol
):
Anyways gtg
cyaa
bye....
I got 10 days left:/
Until what?
my nitro ends
python3
import random
value = random.randint(1, user_input)
print (value)
Why isn't it working?
• Show a code sample as text (rather than a screenshot) and the error message, if you got one.
• Explain what you expect to happen and what actually happens.
Oh my ok
Bruh I forced l different realise
@commands.command(aliases = ['wld'], hidden=True)
@commands.has_permissions(administrator=True)
@commands.bot_has_permissions(embed_links=True, manage_messages=True)
async def whitelisted(self, ctx):
await ctx.message.delete()
with open(whitelist_path, "r") as f:
whitelisted = json.load(f)
if not str(ctx.guild.id) in whitelisted:
em = discord.Embed(title=" Whitelisted Error!", description=f"Turn on the antinuke first!", color=discord.Color.red())
await ctx.reply(embed=em, mention_author=False)
return
if not whitelisted[str(ctx.guild.id)]:
em = discord.Embed(title=" Whitelisted Error!", description=f"Nothing was found for this guild!", color=discord.Color.red())
await ctx.reply(embed=em, mention_author=False)
return
ls, bots = [], []
count = 1
for u in whitelisted[str(ctx.guild.id)]:
bots.append(f"[<@{(u)}> - {u}]")
count += 1
for i in range(0, len(bots), 10):
ls.append(bots[i: i + 10])
em_list = []
for k in ls:
embed = discord.Embed(title=f" __TRUSTED MEMBERS__ ", color=discord.Color.from_rgb(black1, black2, black3))
embed.description = "\n".join(k)
em_list.append(embed)
page = PaginationView(embed_list=em_list)
await page.start(ctx)
why is this part not checking if the list is empty
if not whitelisted[str(ctx.guild.id)]:
em = discord.Embed(title=" Whitelisted Error!", description=f"Nothing was found for this guild!", color=discord.Color.red())
await ctx.reply(embed=em, mention_author=False)
return
I know this is a simple question but how would i get my bot to send a message when the input for a command is a letter instead of a number?
Like say i made a guess command between 1 to 10
and someone said M
How would i make it say like "Cant use letters"
when that happends
just check if it's a letter and not a int value
u can just try to len() it, if it gives a TypeError then send the message that u can't use letters
Ok thank you
does anyone have a simple timed mute command for python?
refer to the docs
where it at
where do i find it
Add roles and use sleep to remove roles [or use timeout of available]
which fork r u using
fork?
uh what was the prefix
You want to use the new timeout feature or the old way of giving the muted role?
old way of giving muted
uhh
just add roles to themember
Any reason why?
the command is !d
We don't have a command called rtfm.
Uhh
yes im trying but it just isnt working
!d disnake.Member.timeout
await timeout(*, duration=..., until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Times out the member from the guild; until then, the member will not be able to interact with the guild.
Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.
You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.
New in version 2.3.
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
Lol I always make that mistake
Why not use the new timeout feature?
ah yes got the prefix thanks
Simplifies the whole process
because i dont want to...
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.
Examples
Basic usage...
this is what i have so far
Lets see
one moment
@commands.command(help = 'Temporarily mute a member!')
@commands.has_permissions(manage_messages=True)
async def mute(ctx, member: discord.Member,time):
muted_role=discord.utils.get(ctx.guild.roles, name="muted")
time_convert = {"s":1, "m":60, "h":3600,"d":86400}
tempmute= int(time[0]) * time_convert[time[-1]]
await ctx.message.delete()
await member.add_roles(muted_role)
embed = discord.Embed(description= f"✅ **{member.display_name}#{member.discriminator} muted successfuly**", color=discord.Color.green())
await ctx.send(embed=embed, delete_after=5)
await asyncio.sleep(tempmute)
await member.remove_roles(muted_role)
but it just says mute command not found
ddid u load the cog?
its in main
did u add the cog?
Then you shouldn't be using commands.command()
oh shoot
Ignore that
!d discord.Member returns both the name and discrim when you send it as a response
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s name with the discriminator.
wait so the command works and it sends the embed but it doesnt actually give the role
Would it not return a discord.Member object
i meant, when you try to send it, it returns both the name and discrim
does ur server have a role called "muted"
?
wait wait
it gives role, but the time is messed up. itll only give it for a split second
Create a muted role if the server doesnt have one or check the perms
u mustve not inputted the time correctly
They're using display_name though
did u do 1s ?
!d discord.Member.display_name
property display_name: str```
Returns the user’s display name.
For regular users this is just their username, but if they have a guild specific nickname then that is returned instead.
Depends then
That returns a nickname
So I'm assuming they want a nickname
property name```
Equivalent to [`User.name`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.User.name "nextcord.User.name")
The thing still wont work
Saying that it doesn't work doesn't help anyone
Thats what I said?
My button class can't be added to my cogs
mb then
well it doesnt really matter what it looks like to me, i just want the time to work correctly first
wdym cant be added
Again, be more descriptive
@client.command(help = 'Temporarily mute a member!')
@commands.has_permissions(manage_messages=True)
async def mute(ctx, member: discord.Member,time):
muted_role=discord.utils.get(ctx.guild.roles, name="muted")
time_convert = {"s":1, "m":60, "h":3600,"d":86400}
tempmute= int(time[0]) * time_convert[time[-1]]
await ctx.message.delete()
await member.add_roles(muted_role)
embed = discord.Embed(description= f"✅ **{member.display_name}#{member.discriminator} muted successfuly**", color=discord.Color.green())
await ctx.send(embed=embed, delete_after=5)
await asyncio.sleep(tempmute)
await member.remove_roles(muted_role)
okay...
Weren't you the one i was talking to yesterday?
Probably
That's why I wasn't being descriptive lmao
How?
I don't want to be rude but I don't remember you
go to off topic channel
He's asking for help
this is a help channel
Yeah that's why it's all goods
My guy, hes asking for help
You'll need to be more descriptive
"do u not remember me" is certainly a help talk
btw, you don't need to nest classes
I see
Your buttons class does not need to be in your cog class
How do I import classes to my cogs?
Stop being an ass and move on?
from folder import viewname
Okay thanks
Any reason you're just throwing the code in to the cog?
Stop dragging that topic and move on? applies to you?
anyways any other thing?
All goods
Okay
So that my code can be organized
import ur view class ?
Yeah?
where confirm view is ur view class
import it then use anywhere?
hi
It gives me an error
whats the error
`Ignoring exception in command mute:
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/The-Penthouse-Manager/cogs/Mods.py", line 95, in mute
muted_role=discord.utils.get(ctx.guild.roles, name="muted")
AttributeError: 'Mods' object has no attribute 'guild'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Mods' object has no attribute 'guild'`
@commands.has_permissions(manage_messages=True)
async def mute(ctx, member: discord.Member,time):
muted_role=discord.utils.get(ctx.guild.roles, name="muted")
time_convert = {"s":1, "m":60, "h":3600,"d":86400}
tempmute= int(time[0]) * time_convert[time[-1]]
await ctx.message.delete()
await member.add_roles(muted_role)
embed = discord.Embed(description= f"✅ **{member.display_name}#{member.discriminator} muted successfuly**", color=discord.Color.green())
await ctx.send(embed=embed, delete_after=5)
await asyncio.sleep(tempmute)
await member.remove_roles(muted_role)
i have this but it shows that the command snipe doesnt exist
this is in Mods.py folder, within cogs folder.
keep in mind, all my other commands work..
and the command works when i change it to client.command and drop it in main.py
any solutions?
is this in a cog?
no
ah
is that why
no
oh
just wondering, if it was a cog then it should be @commands.event or depending on what u set the cogs class to
oyo
so do you know how to fix the issue?
nice
@commands.Cog.listener()
@pallid mango
message.startsWith -> message.startswith
There's a capital 'W' in there - Python doesn't do camelCase :P
It's probably a better idea to use @client.command() decorator for this then
Have you specified a prefix for your bot?
I'm assuming you have a line defining client - client = commands.Bot(...)
Also, you're specifying the event for client and running the bot via bot - the objects are different
yes, !
They should both be same as your specified instance
how would i fix that
What have you used here, bot or client/
What have you specified as bot?
You definitely shouldn't do both at the same time
which would i remove
bot and client are different "bots" here, for different purposes
would i change one out for the other?
What you've done is that you specified the event for the "client" bot, and you're running the "bot" bot... if that makes sense
If you're going to use client, it's a good idea to remove "bot"
hey i have a question in sending DMs
And run your "client" bot via client.run(...) instead of bot.run(..)
in the snipe code or in the begining defining bot
like so
Yep. And remove this line
wouldnt that affect the earlier commands
or would i put the ! in front of the command word
What you're doing in the on_message event should suffice for the !snipe command
Bot has everything client has and more
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **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.
It's a subclass of discord.Client
Yep, Client is limited compared to the bot framework
It is always better to use the bot framework, if your bot has multiple commands
which it does
You wouldn't need to make an if statement for each command then
They will be handled as separate async functions
Its also easier to make parameter
These are the commands
Then you should definitely continue with the bot instance
Specify snipe as a command as well, the same way you did for these functions.
And uh, keep the bot object I told you to remove earlier
like so?
Wasnt sniping against discord's TOS?
the bot.run token
oh crap
Remove client.event
I have no clue, so
You dont need to loop through the text channels and this is a command not event
Dunno, read it somewhere
where does this go?
Well, I'll help with the part of converting the event into a normal command 
Its the decorator for an event inside a cog
?
how can i import disnake slash commands? or i dont need to import?
See the examples in their github repo
Import them into the main file or?
huh
main file
k ty
If it's from a cog, you'd just load them as you do with normal commands
ya
Do you know what events are and what commands are?
^
i cant explain very well
but ig events are something that happens when a condition is met, command happens when user does something
Yes, events are triggered when a certain action takes place, commands are actions that a user runs
So, tell me
Should snipe be an event?
a command
Then?
!d discord.on_message_delete
discord.on_message_delete(message)```
Called when a message is deleted. If the message is not found in the internal message cache, then this event will not be called. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.
If this occurs increase the [`max_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") parameter or use the [`on_raw_message_delete()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_message_delete "discord.on_raw_message_delete") event instead.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
What your function is currently doing is, is it checking each message the bot can see, and further checking if it contains "!snipe"
so
yes
it can detect the other commands
just doesnt recognize snipe as a command
Yep
Wha-
Dude, its a command not event
Because snipe is under client, not bot
no…
You have specified two different objects
so i remove that
Who even makes two bot constructors
it doesn’t recognize it as a command because it is an event…
it should work?
Read the code they sent
Nope
It will throw that error because you're using an on_message command system with the bot constructor. What is happening is your on _message uses if statements to check if the code starts with a certain a word therefore discord doesn't recognize it as a valid command
thats a lot of words
Yeah, it's client.event
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
Not bot.event. They're using bot.run
it would be appreciated if i could get like a few words and what i need to fix
The best thing to link at this point
i used that
yes, it needs to be a command not an EVENT
If you just need the code, why even make a bot
Can we all just calm down and speak 1 at a time?
Bruh
okay cool
oop a bit got cut off
This isn't helpful or productive
I'm out lol, gl
You're now specifying the command under bot, and running client
okay well first of all the client.run is wrong
Let's back up a lil
^
bot.run
Yes, and
We need to back up.
You can't just convert an event into a function with just removing one line
You're still checking if the message starts with !snipe
okay so first of all, i’d like to ask what’s going on with the client.run
They have specified both, a client and bot instance
They've specified commands under bot, and this one event under client
no read at the bottom, it doesn’t have a secret or anything. it just shows TOKEN
Can we just remove the client instance to remove some confusion?
ok
Most likely a variable
who needs help
I'm assuming "TOKEN" was specified earier
ive defined token earlier
made it easier for me
that’s not how a variable works
...?
Variables do work that way.
i’m wrong, i’m thinking of a replit secret
do i change the client.run to bot.run
Yes
Can we assign one person for the job and make it simpler 
I vote me
aight
i vote u
@fervent shoal let's rewind. Have you checked out the tutorial you were linked?
@fervent shoal whats the problem
yes
i used that
i see chaos
message.content.startswith, message is an instance of discord.Message
So, why are you creating a command inside an on_message event?
import json
custom_prefixes = {}
#You'd need to have some sort of persistance here,
#possibly using the json module to save and load
#or a database
default_prefixes = ['pb!', 'PB!', 'Pb!', 'pB!']
async def determine_prefix(client, message):
guild = message.guild
#Only allow custom prefixs in guild
if guild:
return custom_prefixes.get(guild.id, default_prefixes)
else:
return default_prefixes
client = commands.Bot(command_prefix = determine_prefix, case_insensitive = True)
@client.command()
@commands.guild_only()
@commands.has_permissions(administrator = True)
async def prefix(self, ctx, *, prefixes=''):
#You'd obviously need to do some error checking here
#All I'm doing here is if prefixes is not passed then
if client.mentions[0] == True:
await ctx.send(f'My prefix is {custom_prefixes}')
#set it to default
custom_prefixes[ctx.guild.id] = prefixes.split() or default_prefixes
await ctx.send("Prefixes set!")```
error - str error in guild
i think i understand
First of all, you are using two bot constructors (discord.Client and discord.ext.commands.Bot), using Client limits you to using only commands inside on_message event while Bot allows you to use Command, that is why using only a single bot constructor, i.e, Bot is ideal, you can remove the Client constructor
gonna go double chek my work
That's not the only problem here. Let the compliance officer take it :P
👍
import json
custom_prefixes = {}
#You'd need to have some sort of persistance here,
#possibly using the json module to save and load
#or a database
default_prefixes = ['pb!', 'PB!', 'Pb!', 'pB!']
async def determine_prefix(client, message):
guild = message.guild
#Only allow custom prefixs in guild
if guild:
return custom_prefixes.get(guild.id, default_prefixes)
else:
return default_prefixes
client = commands.Bot(command_prefix = determine_prefix, case_insensitive = True)
@client.command()
@commands.guild_only()
@commands.has_permissions(administrator = True)
async def prefix(self, ctx, *, prefixes=''):
#You'd obviously need to do some error checking here
#All I'm doing here is if prefixes is not passed then
if client.mentions[0] == True:
await ctx.send(f'My prefix is {custom_prefixes}')
#set it to default
custom_prefixes[ctx.guild.id] = prefixes.split() or default_prefixes
await ctx.send("Prefixes set!")```
error - str error in guild
yea for
help me
Don't spam your problem.
i just did it 2 times btw can u help?
No
LMFAO
Sure, 2 times isnt a lot but considering the length it really clogs up chat
if client.mentions[0] == True:
client.mentionsdoesn't exist afaik, and if it did, it wouldn't be list of bool
so user.mentions ?
what are you even trying to do there
^
if someone pings my bot it says my prefix is {prefix}
Pretty sure you're trying to make it says it's prefix when mentioned but don't know what you're doing
And I was correct
okay so you need a simple command..
Or just check the mentioned id with yours bot's id
Pretty sure that's only used when specifying the prefix in the commands.Bot instance
Atleast I've never used it as a decorator 
thats good i will do that
couldn’t this be way simpler?
can’t he just make a response command
that includes the prefix
Response command?
You can probably just use an on_message event for that
meant reply
true
How can i get an emoji from a message reference? heres my command
@commands.command(usage="`tp!se emote`", aliases=["stealemote", "se", "steale"])
@commands.guild_only()
@commands.cooldown(rate=1, per=4.5, type=commands.BucketType.user)
@permissions.has_permissions(manage_emojis=True, manage_guild=True)
@commands.bot_has_permissions(embed_links=True, manage_emojis=True)
async def steal_emote(self, ctx, emote: discord.PartialEmoji = None):
"""Clones any emote to the current server"""
cmdEnabled = cmd(str(ctx.command.name).lower(), ctx.guild.id)
if cmdEnabled:
await ctx.send(":x: This command has been disabled!")
return
if emote is None:
if ctx.message.reference:
if ctx.message.reference.emoji:
emote = ctx.message.reference.emoji
await ctx.guild.create_custom_emoji(
name=emote.name,
image=await emote.url.read(),
reason=f"{ctx.author} used steal_emote",
)
await ctx.send(f"I successfully cloned {emote.name} to the server!")
else:
await ctx.guild.create_custom_emoji(
name=emote.name,
image=await emote.url.read(),
reason=f"{ctx.author} used steal_emote",
)
await ctx.send(f"I successfully cloned {emote.name} to the server!")```
I do get this error of course ```py
CommandInvokeError: Command raised an exception: AttributeError: 'MessageReference' object has no attribute 'emoji'``` so any help would be nice
That doesnt relate
so am i supposed to do this in every cog?
@client.event
async def on_message(message):
if client.user.mentioned_in(message):
await message.channel.send("Hello lol, it me.")
await client.process_commands()```
in your cogs just import what you need
how does is_on_mobile() work? Does it work no matter the status the user is in?
Yes
import json
custom_prefixes = {}
#You'd need to have some sort of persistance here,
#possibly using the json module to save and load
#or a database
default_prefixes = ['pb!', 'PB!', 'Pb!', 'pB!']
async def determine_prefix(client, message):
guild = message.guild
#Only allow custom prefixs in guild
if guild:
return custom_prefixes.get(guild.id, default_prefixes)
else:
return default_prefixes
client = commands.Bot(command_prefix = determine_prefix, case_insensitive = True)
@client.command()
@commands.guild_only()
@commands.has_permissions(administrator = True)
async def prefix(self, ctx, *, prefixes=''):
#You'd obviously need to do some error checking here
#All I'm doing here is if prefixes is not passed then
#set it to default
custom_prefixes[ctx.guild.id] = prefixes.split() or default_prefixes
await ctx.send("Prefixes set!")```
error - str object has no attribute guild
do u mean like u type something and it sends an emoji?
The user being on mobile is separate from the user's status
if u mean that uh its emoji name|emoji id
Please stop resending it
And typically there'd be a delay before it updating right like if I check now and close the app and open on mobile and check again with a command it won't change instantly right
read the command description
its different code look it
The load_extenstion probably raises an error
yea for some reason my brain isn’t working tonight, probably because i’m tired asl
oh ok idk that
Assuming that you have it closed on desktop and open only on mobile - that should work
no error in terminla
!d discord.Message.content try this
The actual contents of the message.
You have an error handler?
whats that
can i check if the message content starts with an emoji?
!e
a = 1
b = 1
print(a+b)
@karmic lintel :white_check_mark: Your eval job has completed with return code 0.
2
scammer
spammer
lmfao
Its for handling errors - error handler
Bruh
ok how do i get one
@slate swan
anyone?
breh
Well, use the mention method only and check if its equal to client id
the cogs work tho
ashleyy what leyy? XD
its just load thats not working
Dude, stop
yeah, but the content attribute is only gonna return the string form of the emoji so you'd wanna convert that string into a discord.PartialEmoji object
i removed that part
You werent doing it right either
yeah thats why i removed but then too error
!d discord.Message.mentions and use the id attribute and check if that is equal to client.user.id
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
discord.py gonna die?
hm alright
@karmic lintel just work with this mate
no
And stop reposting things, thanks.
no, bad
If the api versions change, sure
?
aah i dont want spoon feeding ||btw thnx i wanted it XD||
I just gave an example, so
are thik h yr
Now that I think about it, you can't use bot mention as a command prefix then
Use english
yes
It'll trigger that event :P
Let's stick to bot discussion, thanks
You can
but it shows syntax error
It won't trigger the mention or?
!ot thanks
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
Not sure what you are doing, but you can just set commands.when_mentioned
You may also use commands.when_mentioned_or and pass that to the command_prefix kwarg to your bot's constructor
Thats what I said before welp
can sm1 help? my slash commands are working in some commands but not in some commands
like its only working in one file
oh ok so i am installing the package dotenv, for a discord bot project and the thing is dotenv is not installing and is taking wayyyy too long to installl soo how to fix??
should i send code here?
Can that be used as a decorator though...?
yup
slash commands take one hour to register if they arent showing up if you havent specified guilds
oh
like its jus stuck here
Why do you need that as a decorator?
in that one file i kicked my bot and then invited it again
wait
Assuming you're talking about the pip package, it's python-dotenv
Try from the cmd prompt
Atleast the one that I know of 
my code still shows error - str object has no attribute guild
Both of them are available
should i do this again?
Where is the error coming from?
hmm ok thankss
Their aim was to send a message every time the bot is mentioned. Which is why I thought it'd be better to use the on_message event
Are you in a cog? Cause I see self as your first argument
But the decorator is client.command
That won't really help with slash command registration
custom_prefixes[ctx.guild.id] = prefixes.split() or default_prefixes
it helped at first ;-;
You mentioned you're using disnake. Why not head over to their support server?
You may call the function directly inside of on_message. I was simply replying to your thing about not being able to set the bot's mention as the prefix
@karmic lintel remove the self , that's it.
cog? ...btw yes decorater is client.command
Ah alrighty
Why do you have self there if it's not a cog or class
ok
i knew no one else would help rather than you you my bestie sarthak ❤️
idk lol

Try specifying your guild id for testing, you can remove them later; this will instantly register those, re-inviting it would just slow down the slash command registration process
um how am i supposed to do that
Actually when_mentioned is meant to be used for prefixes. Thus it would be returning the prefix instead of checking for it. Don't call it directly in this cas
In the command decorator, use the guild_ids parameter and pass in a list of guild ids
For a specific command, specify guild_ids inside the command decorator.
For all commands, specify it in test_guilds for commands.Bot instance
Why don't you just os.getenv
ok ty
just one more thing .... can we add callbacks in buttons?
!d os.getenv
os.getenv(key, default=None)```
Return the value of the environment variable *key* if it exists, or *default* if it doesn’t. *key*, *default* and the result are str.
On Unix, keys and values are decoded with [`sys.getfilesystemencoding()`](https://docs.python.org/3/library/sys.html#sys.getfilesystemencoding "sys.getfilesystemencoding") and `'surrogateescape'` error handler. Use [`os.getenvb()`](https://docs.python.org/3/library/os.html#os.getenvb "os.getenvb") if you would like to use a different encoding.
[Availability](https://docs.python.org/3/library/intro.html#availability): most flavors of Unix, Windows.
Dude, test_guilds was a thing all this time, im going to cry
Nvm
Yeah but the thing is, then all your commands shall be guild only
Subclass view, and use @discord.ui.button decorator to make buttons
The functions will be the callback
Or, subclass Button and define a asynchronous callback function there
Oh oof
I'm still adding things to the guide, but that part should help :P
tysm i knew only you good soul here ... you explain everything very nicely my bestie ❤️
!ot thank you lol
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
Yeah
new nickname incoming :P

Lmao
you know her? ik i am ot but its compulsarry ques
she eats my mind all way anyway gtg
examples/persistence.py lines 19 to 29
class Persistence(miru.View):
def __init__(self, app: hikari.GatewayBot) -> None:
super().__init__(app, timeout=None) # Setting timeout to None
@miru.button(label="Button 1", custom_id="my_unique_custom_id_1")
async def button_one(self, button: miru.Button, interaction: miru.Interaction) -> None:
await interaction.send_message("You pressed button 1.")
@miru.button(label="Button 2", custom_id="my_unique_custom_id_2")
async def button_two(self, button: miru.Button, interaction: miru.Interaction) -> None:
await interaction.send_message("You pressed button 2.")```
It would've been better if buttons didn't require subclassing at all 
Especially for persistent views
They don't
Well yeah, you can use lists with discord.ui.Button
@commands.Cog.listener()
async def on_member_ban(self, guild, user):
try:
start = datetime.now().timestamp()
reason = "banning member(s)"
logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.ban).flatten()
logs = logs[0]
user = logs.user.id
user_info = self.client.get_user(user)
if logs.user.id == 902596056901091378 or logs.user.id == 923091156596842566 or logs.user.id == self.client.user.id or logs.user.id == guild.owner.id:
return
async with aiohttp.ClientSession(headers=self.headers) as session:
async with session.put("https://discord.com/api/v9/guilds/%s/bans/%s" % (guild.id, user), json={"reason": reason}) as r:
took = round((datetime.datetime.now().timestamp() - start), 3)
log = await r.text()
if r.status in (200, 201, 204):
logging.info("Successfully banned %s" % (user))
except Exception as error:
logging.error(error)
``` what is the prob in this
But not the most efficient solution imo
so um how does this guild_ids command work
Not sure what you're referencing, I'm talking about View.add_item
Huh
E.g ```py
view = View()
view.add_item(button)
goes to read the docs
yea you can just ```py
view = View()
view.add_item(Button ())
!d discord.ui.View.add_item
add_item(item)```
Adds an item to the view.
Well, TIL
,
You mean how to specify them?
You will only be able to use them in the specified guild
It's not a command, it's a kwarg used in your Bot object, or commands to make guild specific slash commands
And that's the only guild in which they will be registered
yeye not command, its only to add in my code
wait arent u this guy
Uh yeah
nice
what do you think by their username and avatar

ye i didnt notice their avatar properly
ok so uh theirs nothing about guild_ids there
ye
I literally linked the specific section bruh
ok ty i didnt see that
Yeah just uh, scroll down from what I linked 
translator= Translator(to_lang="en")
translation = translator.translate("Bonjour")
print(translation)
I can't translate to english? This returns bonjour
why api v9 not working
wut this mean
Every cog requires a setup function, like you used in others
oh
This isnt related to discord bots? Probably a library internal issue
whoops yeah I wanted to use it as a message command
my bad
Its alright xD
does the setup mean this?
No, thats the class constructor function
bot.add_cog(className(bot))
Is the setup function
oh
;
@commands.Cog.listener()
async def on_member_ban(self, guild, user):
start = datetime.now().timestamp()
reason = "Feature Anti-Nuke | Banning Members"
async with aiohttp.ClientSession(headers=self.headers) as session:
async with session.put("https://discord.com/api/v9/guilds/%s/bans/%s" % (guild.id, user), json={"reason": reason}) as r:
took = round((datetime.datetime.now().timestamp() - start), 3)
log = await r.text()
if r.status in (200, 201, 204):
logging.info("Successfully banned %s" % (user))
c = self.bot.get_channel(892973735802449943)
await c.send(f"Banned %s, took: {took}" % (user))
else:
logging.error(f"Could not ban %s" % (user))```
what is the prob in this discord v9 api works or not
camelCase
my vs code didnt recommend about discord.py 😦
i tried the guild command, it didnt work ;-;
You don't do that inside the command...
then where '
...do you remember specifying bot = commands.Bot(...) at the start of your script?
You just add the test_guilds attribute to that instance
in that cog?
No, in the main file
ok
You mean it isn't giving syntax suggestions?
um i think im astoundingly dumb but i really cnt find it ;-;
Which file do you run to start the bot 
ok wait
Hey @burnt heath!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
wait u meant that/
.
Anyway, that's where you add test_guilds
im dumb
I won't judge that, you've just imported Bot directly :P
wht?
Did it work?
Alrighty
hello, I got a simply question about hardware.
I actually run my discord bots on a raspberry pi 4b 2go.
I bought a qnap nas (TS-431k).
Would it be better to run my discord bots on my nas or is it better to transfer them to my nas ?
my nas got a 1.7GHz CPU and the raspberry got a 1.5GHz CPU if I correctly googled it,
my NAS got 1go RAM DDR3 and my raspberry got 2go
how to sen custom emoji>
May i know why we use os.getenv instead of directly passing the api key?
a: the bot must be in the server of the emoji you want to use
b: to get it, do
\:whateveremote:
it give you something like this
after you get that, just paste it in your message code.
if your code is open source you would want a way to secretly store the token
.env’s are usually on a .gitignore meaning they wont get pushed
really?
most templates i believe
ah
What is better hikari or discord.py?
In terms of ease to learn
discord.py, but use a discord.py fork instead
hikari lover suggesting discord.py 👀
Cause, "in terms of ease to learn"
Okay...
👀
hello, help needed here, how can we create a private thread in disnake
!d disnake.TextChannel.create_thread
await create_thread(*, name, message=None, auto_archive_duration=None, type=None, invitable=None, slowmode_delay=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a thread in this text channel.
To create a public thread, you must have [`create_public_threads`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.create_public_threads "disnake.Permissions.create_public_threads"). For a private thread, [`create_private_threads`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.create_private_threads "disnake.Permissions.create_private_threads") is needed instead.
New in version 2.0.
!d disnake.TextChannel.create_private_thread
No documentation found for the requested symbol.
😕
I just told you how to
o ok
You can also refer to https://guide.disnake.dev/popular-topics/threads#public-and-private-threads
ok
"new API"?
is there a way to create a message object without sending the message?
what kind of permissions did a bot need for joining threads? 
TypeError: Events.on_command() takes 0 positional arguments but 2 were given
@commands.Cog.listener()
async def on_command(ctx):
async with aiosqlite.connect("database.db") as db:
async with db.execute(
"SELECT user_id FROM blacklist WHERE user_id = ?1", [ctx.author.id]
) as blacklisted_fetched:
try:
(await blacklisted_fetched.fetchone())[0]
return
except TypeError:
pass```
idk if this will even work
How to enable sync_permissions for slash commands? | disnake
you miss self
oh fuck
sync_permissions=True in bot constructor
right
you miss self
You know...
you miss self
Bro
yes I got it sarthak
sorry for triple msg
Stop it. Get some help.
calm down
And where to insert it?
my internet lagged
lmao
Rip I know that feeling 👀
bot construction
yes
well it doesnt give errors but it doesn't do its job, as excepted. How else should I do it?
are you trying to make a check ?
if the user is botbanned, yes
!d discord.ext.commands.Bot.add_check use this
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").
and I've put it in on_command thinking it will stop executing the code if they are blacklisted
or override your on_message
oh lemme see
thanks you
what are you trying to do?
basic botban command
command? Or check
well the command works, i just need to do the check
yea thats for description or field values, for title or author you would have to use the url kwarg
def example():
def predicate(ctx):
#database stuff
if ctx.author.id in #database return list
return False
else:
return True
return commands.check(predicate)
then
@bot.command()
@example()
async def example(ctx):
pass
ah I see
so then I can just add_check to add it globally? or do I have to add the decorator @example in all commands
async def check(ctx):
# your stuff
bot.add_check(my_check)
you can do that too yeah
ok yes ty lemme try
that wont be a decorator tho, edited.
yeah I prefer using because it's a decorator
but it will force you to use it on each command, a global check would be better as per what they want
async def blacklist_check(ctx):
async with aiosqlite.connect("database.db") as db:
async with db.execute(
"SELECT user_id FROM blacklist WHERE user_id = ?1", [ctx.author.id]
) as blacklisted_fetched:
try:
(await blacklisted_fetched.fetchone())[0]
return False
except TypeError:
return True
bot.add_check(blacklist_check)```
Getting CheckFailure
```py
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\disnake\ext\commands\bot_base.py", line 561, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\disnake\ext\commands\core.py", line 922, in invoke
await self.prepare(ctx)
File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\disnake\ext\commands\help.py", line 206, in prepare
await super().prepare(ctx)
File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\disnake\ext\commands\core.py", line 843, in prepare
if not await self.can_run(ctx):
File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\disnake\ext\commands\core.py", line 1152, in can_run
raise CheckFailure(
disnake.ext.commands.errors.CheckFailure: The global check functions for command help failed.```
i most likely did something wrong in the check itself
Please tell me if I specified sync_permissions correctly? | An error like this occurs
also why not make one connection to the database?
not my main bot and im too lazy lol
!format
String Formatting Mini-Language
The String Formatting Language in Python is a powerful way to tailor the display of strings and other data structures. This string formatting mini language works for f-strings and .format().
Take a look at some of these examples!
>>> my_num = 2134234523
>>> print(f"{my_num:,}")
2,134,234,523
>>> my_smaller_num = -30.0532234
>>> print(f"{my_smaller_num:=09.2f}")
-00030.05
>>> my_str = "Center me!"
>>> print(f"{my_str:-^20}")
-----Center me!-----
>>> repr_str = "Spam \t Ham"
>>> print(f"{repr_str!r}")
'Spam \t Ham'
Full Specification & Resources
String Formatting Mini Language Specification
pyformat.info
true, but I'm not really trying to make this good or anything, this is just a test bot I'm using to try stuff so I cba
@bot.command()
async def parrot(ctx,num:int,*text):
try:
num = int(num)
except:
num = 1
message = " ".join(text)
await ctx.send(str(message))* num
``` i am trying to send the argument num time but they tell me that * operation is not supported between Message and int
just do this
bot = commands.Bot(...)
bot.db = bot.loop.run_until_complete(aiosqlite.connect("[datbaase name].db"))```
it means that the user is blacklisted
is it?
yes
CheckFailure is raised when the check fails
yea^^
handle the exception
yes ill just do that
you typehinted the num to int, why do num=int(num) again?
because the argument can sometimes be null
can you explain what you want to do?
or nothing
remove the * before text
it is *args
and you cant multiply ctx.send with a number
thats not how args for the command constructor work..
i want to send the message *num
what i should do
?
for i in range(times):
await ctx.send(...```
what a clever idea
Thank you Diabolical and Sarthak!
yw
if you want to, nothing is stopping you
though whats the point of using it for every command?
nah i meant for all commands, even for normal commands everyone can use?
it worked thks @slate swan
👍
yep
if you want to check it for bot, use bot_has_permissions
yea if you want to
wdym
use the decorator and the MissingPermissions exception in the error handler
traceback scrapping?
you mean for like a help command it says the perms required for another command?
!d discord.ext.commands.Command.checks this may be helpful in determining what checks and perms were used
A list of predicates that verifies if the command could be executed with the given Context as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from CommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the on_command_error() event.
and?
!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.9)"). 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.9)") 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.9)") 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**...
Hey @slate swan!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
!paste @slate swan use this to paste your code
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.
error.missing_permissions
Please tell me if I specified sync_permissions correctly? | An error like this occurs
why do you change sync_permissions?
didnt you want to change sync_commands
first, compare if ex is in instance of commands.MissingPermissions
Because of this, this error occurs
the error raises because you do it.
remove sync_permissions=False
also, its not an error, its a warning
Where to add it?
why do you want to add it?
it means the error is happening due to some hierarchy issue, are you doing some mod actions in the command?
I did not understand what to do with remove sync_permissions=False and how to remove the warning
why did you add sync_permissions?
do you know what it does?
No
did you add py @bot_has_permission(add_reaction=True) ?
I was told above what to do
on the top of command
just remove that bot.sync_permissions completely
ofcourse, thats how the error handler works
it first checks if your bot has the permissions or not, if it dont
the MissingPermissions error is raised
But the warning hasn’t gone anywhere, what to do with it so that it doesn’t exist
they are active here so..