#discord-bots
1 messages · Page 1069 of 1
you cant declare a constant inside an object like that.
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationalError: no such column: arg
????
please go to djs server, thats the correct place to ask the question, as you can see the server name its python.
do u know sql queries?
they want you to learn js before using discord.js, and so do we
so and so
um then learn them. It would be easier for you to do what you want
We don’t help with JavaScript here, as mentioned
Ok. But if the arg is in the str of query , should it throw that error?
No need to insult them
And that doesn’t change the fact that you’re not getting help here
well they are not wrong, you are supposed to learn js b4 using djs just like ur supposed to know python b4 making discord bots
Again, we don’t help with JavaScript
I suggest you stop asking because the answer is no
ask in a js server :p
hi
@commands.Cog.listener()
async def on_message(self, message):
db = sqlite3.connect('afk.db')
cursor = db.cursor()
cursor.execute(f"SELECT user FROM afk WHERE user = {message.author.id}")
result = cursor.fetchone()
if result is not None:
cursor.execute(f"DELETE FROM afk WHERE user = {message.author.id}")
await message.channel.send(f"Welcome Back **{message.author}**, I removed your AFK. You were afk")
db.commit()```
using this instantly removes the data if we use afk cmd
how to fix'
I have a few commands inside a cog, how do I make subcommands? Im using slash commands with discord.py
https://paste.pythondiscord.com/odevekicim guys rate what i coded
first try and it works , i guess the best thing is to try ur best
seems nice, there can be improvements
im so confused tho can u show me where can i add like a welcome message or smth
class welcomesystem:
# should be pascalcase
class WelcomeSystem:
async with aiosqlite.connect("wm.db") as db:
``` instead of making connections each time, you can have a single connection througout the cog or the file using `cog_load` method
```py
async def cog_load(self) -> None:
self.db = await aiosqlite.connect("wm.db")
and simply use self.db to get the database whenever you want to
can u help me fixed that please?
begin with the first part, change the class name's case
i never do that i always keep em lower case
hey guys, how to send message in channel every 5 minutes for example
how to send file AND message with requests module (im using webhook) i dont want other module/library so dont say plz
next instead of making connections multiple times you can use single connection
class MyCog(commands.Cog):
async def cog_load(self):
self.db = await aiosqlite.connect("wm.db")
@commands.command()
async def foo(self, _):
database = self.db
!d requests.post
requests.post(url, data=None, json=None, **kwargs)```
Sends a POST request.
use a task loop ```py
from discord.ext import tasks
@tasks.loop(minutes=5)
async def sending_messages():
send message
...```
guys, pls help me, if i do this in while True with time.sleep in on_ready func, i get this warning every 10 secs
no thats a very bad way of doing it
well i just told everything you need to do
thank u so much, how to start this func and what if want to use random interval every time
i rlly dont get it .. if u could that be greay
sending_messages.start() to start it, for random you would have to make some dynamic stuff
thanks, can u tell me more about "dinamic stuff"?
can u do this with like this as well
bot.con = await aiohttp.ClientSession()
#reqs using
result = await bot.con.get('link')
You should also include a cog_unload method since you aren't using a context manager with the connect
To handle closing the connection gracefully
ofcourse
yeah, True
keeping the connection open would be bad
!d discord.ext.commands.Cog.cog_unload
await cog_unload()```
This function *could be a* [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A special method that is called when the cog gets removed.
Subclasses must replace this if they want special unloading behaviour.
Changed in version 2.0: This method can now be a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.10)").
oh, never knew this existed
@slate swan I have many connections and it confuses me lmao
yeah asking i normally do with databases seeing ur example i got a light bulb moment
just add another await asyncio.sleep(random.choice(int)) inside that task so the timings are random
where to paste this line? in on_ready?
making requests in on_ready is bad, you should use bot.wait_until_ready() for the cache to get loaded first, then start the task
i ve solved it
this is noice, and i've been using aiohttp to read emojis from the url manually all the time https://github.com/Rapptz/discord.py/blob/dc8aef7e6aadaaec81d3e31a64840f60ec8425ee/discord/http.py#L522-L531
discord/http.py lines 522 to 531
async def get_from_cdn(self, url: str) -> bytes:
async with self.__session.get(url) as resp:
if resp.status == 200:
return await resp.read()
elif resp.status == 404:
raise NotFound(resp, 'asset not found')
elif resp.status == 403:
raise Forbidden(resp, 'cannot retrieve asset')
else:
raise HTTPException(resp, 'failed to get asset')```
😔 you can even use bot.http.__session.get() to get it to work, not suggested though.
All this just for some error messages
I need help
dpy moment
yeah i use the connection in many place altho creating a bot.con won't make it faster but looks neater atleast
You should probably not use the internal session
agreed, playing with internals is not a noice idea
Don't they embed your bot's token into the headers?
since that may have ur headers
That's really the only problem
yes
Damn
wot if i do bot.http.__session.get("url", headers={}) 
Also it's not bot.http.__session, if you notice there is two leading underscores. That means it's name mangled. You have to access it via bot.http._HTTPClient__session
oh it was a double underscore and i was trying to ctrl+f http._HTTPClient_session 😔
Yea just editted cause I realised I only put one
Not really sure why discord.py decided to use name mangling, as pep8 says somewhere iirc that name mangling isn't meant for private access. Rather used for subclassing stuff
How can I make an Cooldown for an command only for an server that recently used the command?
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
Example:
@commands.cooldown(1, 30, commands.BucketType.guild)
Can only be used once every 30 seconds and the cooldown applies for the entire guild
Thanks!
no problem
can someone here help me
what do you want to do?
i coded a multi guild welcome system , can i send code and then explain what i want?
await interaction.response.send_message(f'This command is on cooldown. Please wait {error.retry_after:.2f}s')
^
SyntaxError: 'await' outside async function
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 53, in <module>
asyncio.run(main())
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 44, in main
await bot.load_extension('cogs.admin')
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 990, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 915, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.admin' raised an error: SyntaxError: 'await' outside async function (admin.py, line 36)``` ```py
async def error():
def on_command_error(interaction: discord.Interaction, error):
if isinstance(error, commands.CommandOnCooldown):
await interaction.response.send_message(f'This command is on cooldown. Please wait {error.retry_after:.2f}s')
elif isinstance(error, commands.MissingPermissions):
await interaction.response.send_message('You do not have the permissions to use this command.')``` I am trying to create a general error that will work with all my command although I do seem to be having a problem and doing this morning, fix it can someone help me?
You are using await in normal function?
yea
That's the error I guess
how do i fix it
can someone help me code
@bot.event
async def on_command_error....
cant use bot.event i am in a cog and on 2.0
Use listener then
commands.Cog.listener
so ```py
@commands.Cog.listener()
def on_command_error(interaction: discord.Interaction, error):
if isinstance(error, commands.CommandOnCooldown):
await interaction.response.send_message(f'This command is on cooldown. Please wait {error.retry_after:.2f}s')
elif isinstance(error, commands.MissingPermissions):
await interaction.response.send_message('You do not have the permissions to use this command.')```
Yo can u help me code the set and remove welcome message
Cog is part of discord.ext.commands
so that?
declare it as an async function too
how??????
async def on_command_error
um yeah, what exactly do you need help with
ok thx
So u saw my code | correct or incorrect
Does the error handler need to be at the top or the bottom of the file?
as i said, the code was correct, but there can be improvements
I made a multi guild system , u can select the channel / remove the channel for ur welcome system . Now I need to code a message to the so set message welcome to server {member.mention} in discord or smth like that and msg del
Something like that if it makes sense
doesn matter
Ur own message
use a database
Interesting because it doesn't seem to be working
…..
I am using it and I coded half
https://paste.pythondiscord.com/fagegemavu code if interested
now i need to continue
What you want it's a bit confusing tbh...
ok lemme explain one sec
i have wm_set (chooses welcome channel) wm_del (removes the channel) now i want to code a msg_set (welcome message) msg_del (remove welcome message)
does this make more sense?
in simple words -> you want to display custom greeting messages
so for msg_set eg = {prefix}msg_set welcome {member.mention} to server
correct!
Lmao
good luck with it
well i need help xd
Any idea of what's wrong?
are they slash commands?
Yes
then you need a seperate error handler
What would that be?
anyways if someone can help me just ping me that would be great!
how could i check if someone has a role in a specific guild
from discord import Interaction
from discord.app_commands import AppCommandError
bot = commands.Bot(...)
tree = bot.tree
@tree.error
async def on_app_command_error(interaction: Interaction, exc: AppCommandError):
...```
@sly hamlet
make a custom check?
is there a way i can disable a button after a certain period of time, like a timeout.. i searched thru the docs, couldnt find a timeout function for buttons..
what are you using
subclassing the View class or not?
wdym
def my_custom_check():
def predicate(ctx):
# a function that takes ctx as it's only arg, that returns a truethy or falsey value, or raises an exception
return commands.check(predicate)
The predicate can be a coroutine, the indentaion might be a bit weird since im on phone
I get tree is not defined
write the logic inside predicate and use the check as a deco above the command
well i want the cmd to work in any server but check to see if someone has a specific role in a specific server
Actually wait
wait, you can use an inbuilt method for that
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
Scroll up I guess
and use the role id and not the name
guild = ctx.guild
booster_role = discord.utils.get(guild.roles, name = 'Server Booster・₊˚‧')
if booster_role in ctx.author.roles:```
i have this rn
ok
What do you need help with? The welcome system?
What about it
So as I mentioned .. one sec
@commands.has_role(role_id)
@bot.command()
async def foo(): ...```
I'm here for another 10, maybe 15 min then I gotta sleep
i have wm_set (chooses welcome channel) wm_del (removes the channel) now i want to code a msg_set (welcome message) msg_del (remove welcome message)
Okay?
But idk how lmao it confuses me the more I code into the system
I need help making it I guess
Do you have a db set up?
Yes
how are you making slash commads then? which lib?
What's ur db structure
the reason im not helping you anymore is you wont ever listen to my advice
i tried before didnt work
Damn
idk why
BTW they say their error is tree not defined, not commands.Bot has no attribute tree idk if they telling wrong
Connect to the db once on startup and store it in a botvar
Damn I had a stroke reading that xd
wait yeah, tree is an attribute of the Bot object
no errors?
I just need help editing my code
brb
i fixed it but have this problum py Traceback (most recent call last): File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\tree.py", line 933, in wrapper await self.call(interaction) File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\tree.py", line 1097, in call await self.on_error(interaction, e) File "C:\Users\culan\OneDrive\Desktop\3.0.0 echo\echo.py", line 57, in on_app_command_error if isinstance(error, commands.CommandOnCooldown): NameError: name 'error' is not defined
Rip my SQL skills
Code
It’s not that bad I guess
@tree.error
async def on_app_command_error(interaction: Interaction, exc: AppCommandError):
if isinstance(exc, commands.CommandOnCooldown):
await interaction.response.send_message(f'This command is on cooldown. Please wait {error.retry_after:.2f}s')
elif isinstance(exc, commands.MissingPermissions):
await interaction.response.send_message('You do not have the permissions to use this command.')```
My SQL skills are
dude
Use exc not error
E.g = msg_set hello welcome {member.mention} then msg_del
ok thx
fml, I hate helping here now
And yea, learn some basic Python
Lmao sometimes I love dpy server for this
Okay?
it only works in the guild the role is in, otherwise it says role (id) is required for the command
Damn u don’t get the point alright it’s fine
Ah wait I get it
I literally strain to keep passive
use the name instead
So when the msg_set command is ran u want the bot to set the welcome msg
ok
Life is not all about 2.0 tho
It’s multi guilded but ye
I got a stroke reading that
Then msg_del deletes it
Have a different record/row for each guild
wasnt even targetting you... lol
Well I showed my code
And set the field as welcome_msg
So when using the error handler I don't get anything back. But I also don't get an error inside of my side on my panel
@maiden fable
On mobile rn, can't really understand code that well on mobile and dont wanna strain my eyes at 12 midnight lmao
Oh, hm
Bro, why u overcomplicating this wtf
Idk
still dont understand your point, sorry
U just need to make sure no one is inputting any eval or smth then u can easily do it
Just use the UPDATE statement to update the text msg
im trying to check if someone has a role in a specific guild
and i want the cmd to work from any guild
Umm
Ngl welcome message system is one of the easiest one to make
Makes no sense but thanks for that I’ll just code something
Nvm I'mma just go
oooooooof, I see now, just fetch the member object from that guild and use the roles property on it
Non multi guild
That’s correct
3 lines of code
multi guild is also easy
U just need basic DB knowledge
Thoughts?
then its a piece of cake
uhh
Why fetch tho
yes
discord.py 2.0a
mine is literally implemented within 15-20 lines with proper return types
bot = nextcord.Client()
bot_guild = bot.get_guild(GUILD ID)
whitelisted_role = bot_guild.get_role(WHITELIST ROLE ID)
waitlist_role = bot_guild.get_role(WAITLIST ROLE ID)
why is it not working? isnt that how its supposed to be??
the bot IS in the guild whos id I entered
the id IS correct
use discord.utils.get
bot_guild is None
ye but h O W
is there a get_role in bot obj?
class ViewCls(View):
def __init__(self):
super().__init__(timeout=seconds)```
the code is right above the screenshot
Either guild id is wrong, or it's not cached
guild id is right, and its cached
How do you know it is cached?
i have this, but i thought this was only for menus, thanks
hunter....sorry
why wouldnt it be
How can I send a dm with ctx
You called the get_* function just after initializing the bot..?
dm whom?
the ctx.author
ahh yes I am dumb I forgot the main FOKEN part of the entire code
of a command
the on_ready function
How do you decide whether to scrap all your code and start again or try to clean up very old code
ctx.author.send
thanks
make a backup, try clearing it up
if its too tedious just revert
if the code is just too badly written, consider re-writing
I think im gonna have to, it was the first bot i made
Anything on this?
no wait
saved everything in pickle files and have some obtuse code and it's all using message content 
Fetch same thing*
2.5k lines of code to rewrite, here we goooo 😤
Gl
thats why you never count the number of lines
anyways, best of luck
I have also started procrastinating my bot rewrite for some reason again 
my case was way worse, I re-wrote my bot for the third time and i never pushed it to github, and my laptop just....died, now im writing it for the 4th time
U haven't enabled Auto Save?
me who saves code after writing like every 4-5 lines
Lmao my code is saved on every key press
I press K, the code is saved. I press Enter, the code is saved
died as in all of its hard disk and memory got corrupted
And for some reason I still press Ctrl S every 2 min
Rip
after every 4 lines i press ctrl+s about 4 times just to double check it has saved 
me addicted to pressing ctrl s so much that i do that for no reason everywhere
Same
I do that on every line
Even when it's already saved and formatted automatically
Can anybody help me on this please?
lol
code
@tree.error
async def on_app_command_error(interaction: Interaction, exc: AppCommandError):
if isinstance(exc, commands.CommandOnCooldown):
await interaction.response.send_message(f'This command is on cooldown. Please wait {error.retry_after:.2f}s')
elif isinstance(exc, commands.MissingPermissions):
await interaction.response.send_message('You do not have the permissions to use this command.')```
commands.command()
async def set_msg(self, ctx):
async with aiosqlite("wm.db") as db:
cursor = await db.cursor()
await cursor.execute("SELECT * FROM wm WHERE guild_id = ?", (ctx.guild.id,))
data = await cursor.fetchone()
if data is None:
await cursor.execute("INSERT INTO wm(guild_id, channel_id) VALUES(?,?)", (ctx.guild.id, ctx.channel.id,))
await db.commit()
await ctx.send("Welcome Message has been set")
return
if data is not None:
await cursor.execute("SELECT channel_id FROM wm WHERE guild_id = ?", (ctx.guild.id,))
await cursor.fetchone()
result = data[0]
await ctx.send(f"WelcomeMessage is already set", delete_after = 10 )
return``` can someone tell me if this would work'
i'd change if data is not None: to else: and remove both return statements for clarity but otherwise i see nothing obviously broken
ohhh
well i need help because , i coded wm_set (set welcome channel) wm_del (remove welcome channel ) now i need help doing the welcome message and removing it
result = (await cursor.fetchone())[0]
?
right now you're fetching the cursor but not defining the data you're fetching as anything
idk what you're asking me to help with
do u see my code?
yes
now i wanna code 2 more commands , msg_set (set a welcome message ) msg_del (delete the message)
use the error classes from app_commands not commands
so you're asking me to code two functions for you? we don't do that here
anyway better stop procrastinating and get back to this rewrite 
no .....
Isn't that what I'm doing?
if isinstance(exc, commands...)
^ please read your code
done https://paste.pythondiscord.com/fetofeguxe now someone help me fix my msg_del and msg_add
so i need if isinstance(exc, app_commands.CommandOnCooldown):
hello
fix? you're storing the guild id along with the channel id instesd of the text
lmao
Well then help me lol
I coded the 2 commands now time to fix it 😂
too bad i suck at sql
Damm
What is a category channel?
I really don't understand what the docs are trying to tell me.
!d discord.CategoryChannel
ok thx
class discord.CategoryChannel```
Represents a Discord channel category.
These are useful to group channels to logical compartments.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the category’s hash.
str(x) Returns the category’s name.
like this server has categories like -> information, news, etc. see the channels list
then what is catagory for?
?
!d discord.Guild.categories
property categories```
A list of categories that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
oh
i just read it
my bad
yeah, I thought its like diffrent things but the same idk
Anyways can someone help me
@slate swan
Do you also know if there is a difference between these two methods?
nextcord.Guild.create_category()
nextcord.Guild.create_category_channel()
await create_category(name, *, overwrites=..., reason=None, position=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Same as [`create_text_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") except makes a [`CategoryChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.CategoryChannel "discord.CategoryChannel") instead.
Note
The `category` parameter is not supported in this function since categories cannot have categories.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
!d discord.Guild.create_category_channel
await create_category_channel(name, *, overwrites=..., reason=None, position=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Same as [`create_text_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") except makes a [`CategoryChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.CategoryChannel "discord.CategoryChannel") instead.
Note
The `category` parameter is not supported in this function since categories cannot have categories.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
yeah aliases
Can someone help me
Does anyone know if this is going to work?
if nextcord.CategoryChannel.name("Trolls") in nextcord.Guild.categories:
...
with what
give it a go
it wont
since categorychannel is the baseclass for an object that holds data
https://paste.pythondiscord.com/fetofeguxe set_msg and del_msg
what about it
how do i disable a button in one page of help menu, and then enable it in the rest?
eg: home button which redirects to home page should not be in the home, it should be disabled.. whereas in other cogs, it should be enabled so tht users can go to that page
ok but how else am I going to make it work?
if there is a channel with this name then do this and if not then create this channel and do this
I cant use a whole channel object since the channel doesn't exist in the scenario.
So I only use the name
get the guild categories first, extract the names out of it use the name property and then iterate through the list to check if the name matches else create it, discord.utils.find could be an alternative to this
I have found this in the official Docs.
What is lambda for?
member = nextcord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
think of it as a one liner function
what is it doing, and is it necessary?
yeh
if anyone know, pls reply
you might want to use the interaction_check event inside the class
!d discord.ui.View.interaction_check
await interaction_check(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.
This is useful to override if, for example, you want to ensure that the interaction author is a given user.
The default implementation of this returns `True`.
Note
If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.on_error "discord.ui.View.on_error") is called.
I dont really know about buttons but maybe try some if statements like if its home page then show only these buttons
idk tho
check the embed, get the view's children, and disable the required button using the disabled property
does anyone know how i can convert a google firebase code into being able to be stored in .env
Hey! Quick question, how do I make subcommands for slashcommands? Using discord.py
or commands groups, are they the same thing?
doesn't have anything to do with this channel though
#❓|how-to-get-help
oh sorry
@commands.command(name='logoff')
@disnake.ext.commands.is_owner()
async def logoff(self, inter):
await inter.send('ATTENTION: Bot is Logging off')
await self.bot.close()
print('Bot Logged Off')
await exit()
@logoff.error()
does anyone know how i can settup the logoff error for if the commanding user is not the owner
no idea how to use that lib
on_command_error event, and comparing the error's class with NotOwner
the error class is NotOwner right, please correct me if im wrong
hey guys, i have this code, in func sending_messages i send message in channel. its work but sometimes i have strange warnings and errors and this bot stop sending messages, but program continue working. why it could be?
i have not messed with errors handlers for a while. do you have an example for a basic error handler
https://gist.github.com/EvieePy/7822af90858ef65012ea500bcecf1612 this is a very decent one
Simple Error Handling for ext.commands - discord.py - error_handler.py
i use disnake. should i just replace any "discord" with disnake?
yessir
yes it is, tho you can modify it and use normally
making your own code is a better choice
ok
what is a cog?
you can read that in the docs
Looking to hire someone for a current project, dm me if interested
do you have a link?
depends
Can you dm me
!rule 9
@potent spearthanks, I'll read that 🙂
how do you think that command will work?
nah, how will you call the command
act like you're invoking the command
how would you? you can't obviously mention banned users
Ignoring exception in command 'real':
Traceback (most recent call last):
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 639, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
File "C:\Users\culan\Desktop\3.0.0 echo\cogs\nsfw.py", line 92, in real
embed.set_image(url = realResponse['url'])
KeyError: 'url'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\tree.py", line 1090, in call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 665, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 658, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'real' raised an exception: KeyError: 'url'``` what am i doin worng
What is realResponse?
@commands.cooldown(1, 5, commands.BucketType.user)
@app_commands.command(name='',
description="")
async def (self, interaction: discord.Interaction):
response = requests.get("api linl=k")
realResponse = response.json()
embed = discord.Embed(
title = "",
color = 0x0000FF
)
embed.set_image(url = realResponse['url'])
await interaction.response.send_message(embed = embed)
else:
embed=discord.Embed(title="Error", description=".", color=0xff3333)
await interaction.response.send_message(embed=embed)``` what i get back from api `{"image":"pic link"}`
a dict without an url key
why is nextcord.Guild.categories returning
<property object at 0x0000029156D2D6C0>
instead of a list of categories?
thare u go
How do you use it in code
As @potent spear already said there's no "url" key in the returned dict, but there's "image"
@bot.command()
async def categories(ctx)
categories = nexcord.Guild.categories
print(categories)
wdym?
I already told you to learn OOP first
I mean you don't copy text straight from docs
ik 😔
You just made a reference to a method of a class
Print out realResponse, maybe you got an error and got something back that you weren't expecting
which method?
Idk if I can call properties methods but in fact they use methods
if you've said you get back {"image": "..."} why are you using "url" not "image"?
"Decorated methods that don't require calling" might be a weird definition but probably valid
so this embed.set_image(url = realResponse['image'])
guys
i coded a set welcome channel + remove command , i also need help fixing my set welcome message and delete command , https://paste.pythondiscord.com/fetofeguxe can someone assist me
Uhm...
how do I get the catergory object then?
there is no get_category etc
!e
class Stuff:
def __init__(self, smth):
self.something = smth
@property
def some_stuff(self):
return self.something * 420
print(Stuff.some_stuff) # no object instantiated, we are accessing method of a class
print(Stuff(69).some_stuff) # object instantiated and we can access its property```
@vale wing :white_check_mark: Your eval job has completed with return code 0.
001 | <property object at 0x7fb0f3f2bbf0>
002 | 28980
Single category is gettable with get_channel
so can someone help me.
get_channel
SniperGlitcherz wsg can u help me
Now why the &$§/ is it called CHANNEL and not CATERGORY
I have been looking for A WHOLE HOUR AND THOUGH CAHNNEL IS ACTUALLY CHANNEL
!d discord.CategoryChannel no idea honestly
class discord.CategoryChannel```
Represents a Discord channel category.
These are useful to group channels to logical compartments.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the category’s hash.
str(x) Returns the category’s name.
just ask 1 question at a time, just sending your whole code and saying "something doesn't do what it should" is just not done
example
Probably discord API considers categories the channels as well
hey, I made a command which I expect to do X when I do !shit remove
but actually, it does Y
can anyone tell me why? <command codeblock>
!d discord.CategoryChannel
class discord.CategoryChannel```
Represents a Discord channel category.
These are useful to group channels to logical compartments.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the category’s hash.
str(x) Returns the category’s name.
Yes
yes
hey i coded a msg_set for my welcome message ```py
@commands.command()
async def set_msg(self, ctx):
async with aiosqlite("wm.db") as db:
cursor = await db.cursor()
await cursor.execute("SELECT * FROM wm WHERE guild_id = ?", (ctx.guild.id,))
data = await cursor.fetchone()
if data is None:
await cursor.execute("INSERT INTO wm(guild_id, channel_id) VALUES(?,?)", (ctx.guild.id, ctx.channel.id,))
await db.commit()
await ctx.send("Welcome Message has been set")
return
if data is not None:
await cursor.execute("SELECT channel_id FROM wm WHERE guild_id = ?", (ctx.guild.id,))
await cursor.fetchone()
result = data[0]
await ctx.send(f"WelcomeMessage is already set", delete_after = 10 )
return``` doesnt seem to work , can someone help me fix it
doesn't seem to work
F
try again
bruh
How can I add a reaction with default discord emoji?
@wet crystal yeah see GUILD_CATEGORY type https://discord.com/developers/docs/resources/channel#channel-object-channel-types
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
@commands.command()
async def set_msg(self, ctx):
async with aiosqlite("wm.db") as db:
cursor = await db.cursor()
await cursor.execute("SELECT * FROM wm WHERE guild_id = ?", (ctx.guild.id,))
data = await cursor.fetchone()
if data is None:
await cursor.execute("INSERT INTO wm(guild_id, channel_id) VALUES(?,?)", (ctx.guild.id, ctx.channel.id,))
await db.commit()
await ctx.send("Welcome Message has been set")
return
if data is not None:
await cursor.execute("SELECT channel_id FROM wm WHERE guild_id = ?", (ctx.guild.id,))
await cursor.fetchone()
result = data[0]
await ctx.send(f"WelcomeMessage is already set", delete_after = 10 )
return``` hey i coded a set welcome message command if u look at it it doesnt seem to look right in my opinion , as of now there arent any errors
u cant make it better then that
basically what i did
Use async wrapper for async app
Simple sqlite will cause issues
is copied the code from wm_set (set welcome channel) and changed some stuff
so now i need to uknow make it into what it should be
lol
Personally I hate aiosqlite but we all gotta use it if we want to keep using sqlite
this is odd and my brain cant comprehend that
I use postgres cuz asyncpg is much more convenient
https://paste.pythondiscord.com/fetofeguxe if someone can help me that would be great (last 2 commands)
@warped mirage do you have a global error handler (on_command_error)?
no
And you get no errors?
..... one sec
File "C:\Users\Dom\Desktop\beta test\cogs\welcomesystem.py", line 68, in set_msg
async with aiosqlite("wm.db") as db:
TypeError: 'module' object is not callable
self.client.get_channel() with no arguments would definitely cause errors (it's in the listener so can't be caught by on_command_error anyway)
now we're talking
wait
Worth putting in that you should have one global aiosqlite.connect()
preferably a botvar
async with aiosqlite("wm.db")
Wrapped into bot subclass
is possible to add a timer in a cog?
that does what exactly?
What kind of a timer
depends on what you mean by timer
3 persons helping you gg
umh
just a cooldown/timer, and when we trigger a command it could reset it
but in a cog
and not in a command
Yeah just decorate the command
is it an on_message event?
Well commands are in a cog I kinda don't get what you mean
no it's just a timer lol
mmh i don't know how to explain
Show your code
if you could show an example of what you want to do, we can help you
Sure go ahead
File "C:\Users\Dom\Desktop\beta test\cogs\welcomesystem.py", line 21, in on_member_join
channel_id = await cursor.fetchone
TypeError: object method can't be used in 'await' expression
@potent spear
wait
I want to use paramiko (python library) to connect to my raspberry pi, via a discord bot. And i have to etablish a SSH connection with paramiko. But i want only one user to be able to control my raspberry pi. So i want to etablish a cooldown/timer, so if nobody use a command that uses paramiko, then it stop the connection. But if someone use a command, it reset the timer and the SSH connection continue
When you get an error just try to understand the error itself and if you didn't, look at the line of traceback that is written by you and find what's wrong
Nice idea of sshing with discord bot lol
final = self.client.get_channel()
TypeError: Client.get_channel() missing 1 required positional argument: 'id'
next error
error says it all
it id
btw this system is meant to be multi guild
If timer won't be long-term you could use a dictionary with user IDs as keys and datetime objects as values
so what do i do
oh so i could just change the datetime
nice idea
thx
@potent spear
but do you think my little project is possible?
If this is what you wanted yw
then you should do it by name, not id
Yeah that's an interesting idea just make sure to secure your SSH and isolate the environment if it's gonna get used by other people
so channel_name?
yeah don't worry it wont be public ahah
and all categorys?
!d discord.Guild.categories 😉
property categories```
A list of categories that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
Make sure not to copypaste the thing
But to understand the OOP principle
I dont have time rn to learn OOP its hurting my brain
come on, isnt there a workaround
You have a discord.Guild object and that's your ctx.guild and that object has categories attribute
There's spoonfeeding and it's a thing I prefer to avoid
How does that work?
basically the way you just told me and I really do like it indeed
Allegory bro
I wish I was smart enough to know what Allegory is
@potent spear bro i did say my code is incorrect , the first 2 commands and last 2 almost look the same and have the same function i think , can u check my code?
https://paste.pythondiscord.com/zoludutake someone help me and check my code with the 4 commands
when i did del_msg it removed my system
@wet crystal did you figure this out
you are, but thats alright there is way more and bigger stuff confusing me here so thats just a small part
Nice
you're a good teller fr
Thx
https://paste.pythondiscord.com/zoludutake someone please
ctx.author.name doesn't work?
Omg i had the wrong thing XD
you still need to ask better questions
just saying "something doesn't work" isn't helping us
we want to know what you did, what you expected to happen, and what actually happened
Lol ok
I CODED 2 commands , wm_set sets welcome channel and wm_del removes the channel then i coded another 2 commands set_msg (SETS THE WELCOME MESSAGE) del_msg ( DELETES THE WELCOME MESSAGE ) when i do set_msg it says its already set , when i do del_msg it turns of the system
thats the best detail i can say
you only explained the first
i said what i did , what its meant to do
WM_SET(set the channel) wm_del (remove the channel) set_msg(set welcome message) del_msg (delete the welcome message)
there u go
I don't care about those command names
just start with 1 command at a time
tell me 1 command first
bruh
I just don't have the time to look at it all at once
if data is None:
return
else:
if data is not None:
await cursor.execute("SELECT channel_id FROM wm WHERE guild_id = ?", (member.guild.id,))
channel_id = await cursor.fetchone()
that logic lmao
which command is this
Very sus double condition and no error message on data fetching fail 😩
lmao
imagine not making helper functions
How can I make a function, when I verify with this way, the bot to add me a role?
on_member_update
this event will be called when the user is verified (the member.pending will be True after verification )
there was a property named pending or is_pending iirc, hm
So before verify, will be False
big brain
I know 🙂
#bot-commands
umm i accadentally switched branches in git and my changes are gone is there a way to recover them? i lost 1 hr of coding my bot
what ide is that
I want to make circle image manipulation of member with pillow, but i want the pic to be circular , is there any way to do this?
will some one help me make a bot ?
import discord
from http import client
import random
TOKEN = 'bot discord token here'
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
client.run(TOKEN)
i started but not working
pycharm community
didnt you save your code before switching the branch>
client.run should be outside on_ready
wdym
so now when you go back to your normal branch it isnt at the state you left?
Unindent your last line, the client.run(...). Also don't use format, use f strings
It looks like you're following a youtube tutorial, so before you go down that rabbit hole, just don't
client.run is inside on_ready function, but it should be on global level
dont do that ?
Also remove from http import client due to namespace conflict
Yes, don't follow youtube tutorials
I only point that out because your code looks suspiciously familiar
oke im beginner in python i started some weeks ago
In that case, maybe you should get a better grasp of Python first?
That's only going to help you understand concepts easier
im watching much videos
Yeah those are usually subpar and not really that good
but can u accept my friend request i want ask u something ?
!resources these are some good resources to get started
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Ask here, my DMs are closed
i dont like its like 🤮 for me
idk how to say it
cuz its some people that will laugh
No?
Nobody's laughing, it's all fair questions here
certainly not
oh ok cuz in polish community everyone doing this
This isn’t the polish community?
Doing what?
laugh
Go ahead and ask, we're more than willing to help and we don't judge
How can I learn discord.py the best?
There are no stupid questions, as it were
Documentation and python basics really help
no
If you ask me, learning python is the best way to learn discord.py, because once you understand Python pretty well, you start connecting the dots and seeing how exactly discord.py works, which makes it much easier for you to work with it
Knowing the concepts of how something works is probably the best way to work with it
oke but when im watching videos and trying to do something how i can remember the code i learned ?
Practice.
@slate swan if i send you a zip of the directory including the .git could you see if the files are still there?
If you're watching videos, it's inherently not going to your brain. For some people it does, for some it doesn't. Maybe you're the kind of person for who it doesn't
like making projects ?
In which case, you should probably start looking for other resources
We call this "tutorial hell"
then how i can do it ?
You don't learn and retain anything by just watching someone else code something, then copying it down
^^ yeah understanding the code is much better
Same way you don't get better at, say, football just by watching professional athletes play it on TV
then some camps or website for pratice ?
!resources books are a very good learning medium
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
I find that things actually go to my head with books & hands on practice
im polish the most big problem for me
Your nationality doesn't matter when you're learning
W3schools and codecademy have pretty beginner friendly tuts
I would recommend against W3schools
i can english but if i read in english i get nothing in head
Whatever you do, don't go there
or could anyone do this for me
Oh?
Ah, language barrier, that's always difficult
I'm not 100% sure but the resources link I sent you earlier, there are tens of resources and one of them may support polish as the language
some how i learned html and css
Yeah, most people do early on
The main reason would just be blatant misinformation
Ah
Other reasons include lacking syntax/documentation, subpar examples, pretty bad explanations, list goes on
Not to mention they did SEO like hell
w3schools can be in polish too ?
Don't know, but again don't use it
i completely lost my errorhandler file when i caccadentally changed branches
oh ok
what do you recommend for learning python
websites ect ?
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
only this ?
There are a bunch if you click on that link
😢 why did I accadentally change branch
I don't know, honestly, one can never really learn a language
Every day you learn something new
img = Image.open("welcome.png")
asset = member.avatar_url_as(size=128)
data = BytesIO(await asset.read())
pfp = Image.open(data)
pfp = pfp.resize((177,177))
img.paste(pfp, (120, 122))
img.save("welcome2.png")
await channel.send(file=discord.File("welcome2.png"))``` How can I make this image circular?
Sorry
Not a problem
how i can make the tutorials to polish ?
Not all of them support polish, you'll have to look around a bit to see if they do support it
but like click on a book and see if it support polish ?
Maybe. Some books do print in multiple languages
I remember doing that for a club 6th or 7th grade year, I thought it was pretty stupid
so its bad ?
Maybe. My opinion was that it's bad
Looks useful, though I'm not the right person to ask since I've never used these resources
I'm a more hands on person like I mentioned, and I learn by doing rather than reading or watching
then what u use ?
None, I try my best to make projects and learn from them
wdym
different people learn differently ¯_(ツ)_/¯
but i dont know how it will be best for me to learn python
like i want to learn it but if i ask people they tell me differently
You need to figure that out yourself, since only you know yourself
tips ? pls
Not really, what sort of tips are you looking for?
learning python
Well, only one I can really give you is that your mindset is probably the most important thing when it comes to learning
yyy
like
You can try using an extension
Which converts all english to polish
wdym
A chrome extension which converts english to polish
name
Don’t have one off the top of my head
im starting getting no ide now how i will learn python
😭
Learning "enough" Python isn't super difficult, it just takes some patience and willingness. You can start by learning the basic concepts first (variables, built-in data types, syntax, functions, etc) and attempt different stuff as you progress. What worked for me (this might not work for you) is read a lot of source code; I started out by trying to make discord bots, and it was very unintuitive for me as I knew very little Python. So I read the library's source code and googled stuff up as I went along. Programming languages are literally meant to be human readable, just take time and go slowly and thoughtfully.
Pretty sure google translate can translate entire sites for you
?
Lol read the website
It says up there "Read the basics"
Look through those links
learn
Don't worry, it is made as simple as possible for people to understand
it's actually less than you'd think
I don't actually understand what you're trying to learn tho
Like all of Python or something?
Because you only really need to know what you're using
If that makes sense
timtoy
wheres your cat pfp😾
tools multitool mby som checker ect
its more
something for discord with python
only i know discord,tools,multitool
@commands.Cog.listener()
async def on_message(self, message):
db = sqlite3.connect('afk.db')
cursor = db.cursor()
cursor.execute(f"SELECT user FROM afk WHERE user = {message.author.id}")
result = cursor.fetchone()
if result is not None:
cursor.execute(f"DELETE FROM afk WHERE user = {message.author.id}")
await message.channel.send(f"Welcome Back **{message.author}**, I removed your AFK. You were afk")
db.commit() ```
This instantly removes my data how to fix it
!with
The with keyword triggers a context manager. Context managers automatically set up and take down data connections, or any other kind of object that implements the magic methods __enter__ and __exit__.
with open("test.txt", "r") as file:
do_things(file)
The above code automatically closes file when the with block exits, so you never have to manually do a file.close(). Most connection types, including file readers and database connections, support this.
For more information, read the official docs, watch Corey Schafer's context manager video, or see PEP 343.
why does ctx.guild.members only show me 1 member and thats the bot himslelf?
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
I have had this on since the beginning
yeah i forgot the intents=intents in the commands.bot
thanks
do i need to create another app in dev portal if i want a test version of my bot?
i like the way u censor stuff

:D
i remember always using with_static_format("png") because of apple not supporting webp
is this still a thing?
yes, Asset object has that method
!d discord.Asset.with_static_format
with_static_format(format, /)```
Returns a new asset with the specified static format.
This only changes the format if the underlying asset is not animated. Otherwise, the asset is not changed.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
yep
no i mean the issue itself
do i still have to do it?
i even made this ugly shortcut
disnake.Asset.compat = property(
lambda self: self.with_static_format("png")
)
for i in range(1, 4):
that is if you actually use i
if u just want to iterate 3 times use for _ in range(3):
alright thanks
can my bot access these assets from dev portal?
How can I send a message to the channel if someone tried to invoke a command but didn't enter necessary arguments?
fixed already? or do you still want the answer?
mind you: always add an else statement in error handlers
if not: the error will raise (silently without output) and you won't even notice, since you never handled it
👍
also, I finally understood the instances etc from OOP
Great! So I don’t want to see any discord.Guild.categories etc anymore in your code
yep haha, I just found out about the utils
What are bad arguments?
Is it a Bad Argument when only when its empty or is it also one if It is nonsense
You can read up on that in the docs
For empty there exists one more error
MissingArguement
thanks
is it possible to make a dismiss button like Clyde has when dm'ing a blocked person or someone who doesn't accept dm's
You only can when sending a message from an interaction and making it ephemeral
is there a list of possible bot errors for disnake
Well the docs are supposed to tell you of possible exceptions for each function so
Bot errors are gonna depend on what the bot is doing
well lol im trying to work on my error handler
Guys what's use of cogs.listener
Me not able to understand it from documentation
To handle events within a cog
Yes but it would be within a cog
It's the cog equivalent of @bot.listen(). A listener is fundamentally different from an event because events override the internal code, and you can also only have one event listener for one event at a time, unlike listeners which can have *as many listeners as you want, all of which will get triggered for the event they are listening for *
Guys can anyone help me fix this error
it's await bot.add_cog(...) if you're using 2.0
Ok
def setup(bot):
await bot.add_cog(invite(bot))
It's giving me error
if you're using await inside a function, the function should be async
Hmmm async def?
precisely
@fading marlin ```py
bot.get_channel
With what we have to replace bot in cogs
self.bot ??
self.bot.get_channel?
yes
import discord
from discord.ext import commands
import requests
import json
def get_quote():
response = requests.get("https://zenquotes.io/api/random")
json_data = json.loads(response.text)
quote = json_data[0]['q'] + " -" + json_data[0]['a']
return(quote)
class quote(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def quote(self, ctx):
quote = get_quote()
Embed = discord.Embed(title="Quote", description=quote,color=discord.Color.green())
await ctx.send(embed=Embed)
async def setup(bot):
await bot.add_cog(quote(bot))
Guys me again and again getting indentation error but my indentation is correct
its @bot.event but with cogs
import discord
from discord.ext import commands
import requests
import json
def get_quote():
response = requests.get("https://zenquotes.io/api/random")
json_data = json.loads(response.text)
quote = json_data[0]["q"] + " -" + json_data[0]["a"]
return quote
class Quote(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.command()
async def quote(self, ctx: commands.Context):
quote = get_quote()
embed = discord.Embed(title="Quote", description=quote, color=discord.Color.green())
await ctx.send(embed=embed)
async def setup(bot: commands.Bot):
await bot.add_cog(Quote(bot))
seems fine to me
!p
pep_number
How to paste code?
See here once
Used client.remove_command(“help”)
And then created my own help command
But it is unresponsive
Wait I’ll send code
Add three of these: ` before and after the code
@client.command()
async def Help(ctx):
await ctx.send(embed=hE)
button2 = Button(label = "Utility Commands", style = discord.ButtonStyle.blurple, emoji = ":utility:"),
Button(label = "Fun Commands", style = discord.ButtonStyle.blurple, emoji = ":bug4:"),
Button(label = "Moderation Commands", style = discord.ButtonStyle.blurple, emoji= ":mod:"),
Button(label = "Dank Commands", style = discord.ButtonStyle.blurple, emoji = ":dh_pepe_juce:")
async def button_callback4(interaction):
if interaction.button.label == "Utility Commands":
await interaction.response.send_message(embed=UC)
if interaction.button.label == "Fun Commands":
await interaction.response.send_message("Currently There Are No Fun Commands")
if interaction.button.label == "Moderation Commands":
await interaction.response.send_message(embed=b)
if interaction.button.label == "Dank Commands":
await interaction.response.send_message(embed=d)
button.callback = button_callback4
view = View()
view.add_item(button2)
await ctx.send(embed=hE, view=view)
No errors in terminal
shouldnt use requests and you can just use the json method so you wont need to convert the payload to a string and then load it
Guys i want to make a discord bot that it plays the songs that we uploaded to the bot before , and we can make playlists of those songs, is that possible ?
yeah i know
just fixed his indentation
any help?
!d discord.ButtonStyle.blurple
It exists
hm ok
Any help ?
Is it possible to edit already sent embeds?
If you have the message object containing the embed, yes
Did you do capital H help or lowercase h help?
like when i say .play playlist-1 it plays the songs i uploaded in playlist one
Right, any error handlers?
Because the first line await ctx.send(embed=hE) should be throwing an error, unless you have a globally defined hE variable
nope
You're sure? No on_command_error or on_error anywhere at all?
i have globally defined variable `hE
ah okay
and the embed won't send?
Try printing something:
@client.command()
async def Help(ctx):
print("help")
...
i had ctx.send(embed=hE at end
when i used it at top of command
the embed is sent but no buttons
I also believe you're doing the whole button thing wrong
https://paste.pythondiscord.com/sepahiyipu
Guys i am getting indentation error but my indentation is correct
Pls once see code and help me if possible
Your indentation is messed up quite a bit
For one it doesn't seem like they're 4 spaced
If it was correct it wouldn't be giving you the error, would it?
Maybe replit error
@commands.command()
async def quote(self, ctx):
quote = get_quote()
Embed = discord.Embed(title="Quote", description=quote,color=discord.Color.green())
await ctx.send(embed=Embed)
Looks like that part isn't indented properly
The first 2 lines have to be on the same indent level
But i replit it's indented
Again, if it was indented properly you wouldn't be getting the error
Can you send a screenshot of how it looks on replit?
And where exactly is the error saying the problem is?
Line 17
Full traceback please
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 200, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Jaisman's PC\Desktop\ACLib\bot.py", line 367, in Help
await ctx.send(embed=hE, view=Help12)
File "C:\Python310\lib\site-packages\discord\ext\commands\context.py", line 700, in send
return await super().send(
File "C:\Python310\lib\site-packages\discord\abc.py", line 1521, in send
with handle_message_parameters(
File "C:\Python310\lib\site-packages\discord\http.py", line 183, in handle_message_parameters
payload['components'] = view.to_components()
TypeError: View.to_components() missing 1 required positional argument: 'self'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1329, in invoke
await ctx.command.invoke(ctx)
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 995, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 209, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: View.to_components() missing 1 required positional argument: 'self'
my buttons are in a class
@sick birch
hmm odd
class Help12(View):
def __init__(self):
super().__init__(timeout=None)
@Button(label = "Utility Commands", style = discord.ButtonStyle.blurple, emoji = ":utility:")
async def counter(interaction: Interaction, button: Button):
await interaction.response.send_message(embed=UC),
@Button(label = "Fun Commands", style = discord.ButtonStyle.blurple, emoji = ":bug4:")
async def counter2(interaction: Interaction, button: Button):
await interaction.response.send_message("There are no fun commands."),
@Button(label = "Moderation Commands", style = discord.ButtonStyle.blurple, emoji= ":mod:")
async def counter3(interaction: Interaction, button: Button):
await interaction.response.send_message(embed=b),
@Button(label = "Dank Commands", style = discord.ButtonStyle.blurple, emoji = ":dh_pepe_juce:")
async def counter4(interaction: Interaction, button: Button):
await interaction.response.send_message(embed=d)
Maybe i should edit code outside of replit and paste?
Your handlers need to be un-indented
Probably a good idea
Technically most are cross platform
Except maybe emacs which doesn't want to play nice with windows
class Help12(View):
File "c:\Users\Jaisman's PC\Desktop\ACLib\bot.py", line 348, in Help12
async def counter(interaction: Interaction, button: Button):
TypeError: 'Button' object is not callable
error ^
- They should be un-indented, under the class, not the constructor
- it should be
discord.ui.button, lowercase b
and if its a class, shouldnt the first parameter be self?
that too
!d disnake.ButtonStyle
class disnake.ButtonStyle```
Represents the style of the button component.
New in version 2.0.
Done it worked
#bot-commands
hey after you learn all about python OOP do you have enough knowledge to code a discord bot?
Depends of what do you mean "learn all about python OOP"
Cus someone think that if they know that it is Object Oriented Programming and it's about objects they know everything
how do i make a sleep without the bot not responding to a message
Uhm, then yes I think, also you need to know how to readthedocs
no, asynchronous programming, scopes, types, conversion, inbuilt methods and functions are must to know
if I use the sleep and someone else ran a command. the bot won't respond until the sleep is finish
await asyncio.sleep(time)
use asyncio's sleep not time
import asyncio also
where could one go to learn that? or is that on the website?
thks
thks
do i need to import things. just like i did in sleep?
ok thks
import asyncio #inbuilt
await asyncio.sleep(seconds)```
await?
await*
xD
me searching what is better to store prefixes: json or database
JSON according to me but people prefer db
Ngl the only reason I love JSON is cz it's easy to edit and highly readable
MEE6: json
Depends on if you already have a db set up and how many prefixes you're planning to store
use a json-based database...
Yes DB is set up, about 300 prefixes, but if thre will be more than 100 servers idk
waht?
json-based database such as mongodb
oh
or pocket or deta
Nah i prefer MySQL
if you already have one set up then I don't see why you would have a JSON seperately for prefixes
Also it'll be easy to use it in dashboard
me2, but i saw people that did this because "why not"
Yeah
await asyncio.sleep(1)
facts
lots of limitations tho
@regal pulsar its u........
hmm?
ur the one who join my server and left
ok ig 🤷♂️
What I prefer to do- Store the json content in memory on startup, then close the file (or use a context manager). Then, make a task to save the updated data (from memory) to the JSON every x minutes. This way, u won't really encounter any data corruption issues acc to me
How can I replace spaces with a percent symbol?
that could work
