#Basic Pycord Help
1 messages · Page 55 of 1
actually I can't write there
the thread closed, that's fine. I just want to seperate my subcommands into seperate files, do you know how to do it with the plugin?
sure, first I've created a cog that's loaded before all other cogs to create a subgroup -> relevant if you want to use contexts
after that you just import pycord.multicog (I've imported it as pycog to have a shorter decorator
and then you prefix your normal slash command with
@pycog.subcommand("name_of_the_SlashCommandGroup")
@commands.slashcommand()
async def command():
pass
if you do not want to use the command contexts, or other SlashCommandGroup features you can also add to the subcommand independent=True then it creates a command group with the given name for you
currently in my subcommand decerator I'm doing subcommandground.command(...), you're saying I should use the pycog.subcommand and then just use the normal commands.slashcommand decerator?
could you show me your current code? the way I write is the only that I know 
what they do is the normal pycord way
ohh, okay I just didn't understand it xD
yeah, using the pycog.subcommand decorator you can split the subcommands across files
This is my subcommand file```py
import pycord.multicog as pycog
from discord.ext import commands
from discord import option
import discord.member
import Confirm
import aiosqlite
class mm1v1(commands.Cog):
@pycog.subcommand("mm")
@commands.slash_command(name="1v1", description="test")
async def command(self, ctx):
pass ```
Then my main cog file that the command belongs to is setup like this,
import discord
from discord.ext import commands
from discord.ext.pages import Paginator, Page
from discord import option
from pycord.multicog import Bot
import aiosqlite
import discord.member
import asyncio
import uuid
class MM(commands.Cog):
def __init__(self,bot):
self.bot = Bot()
mm = discord.SlashCommandGroup("mm", "test")```
The command currently isn't being loaded, what should I do different?
why self.bot = Bot()?
Great question, a tutorial I was watch said to do it that way, I don't know enough to question it.
You are creating a new instance of the Bot object
So I should just get of that line then
you do self.bot = bot
the reason I changed bot to Bot() is because multicog says to use it, it's subclass of discord.bot that supports splitting command groups into multiple cogs.
No, it does not say that
i see my error now
how do I make my choices a list of the channels in the server
choices=discord.ApplicationContext.guild.channels doesnt work
text channels?
mhm
voice channels?
choices required a list of strings and got a limit of 25
oh
so how do I fix it
I know im stupid just tell me so we can get it over with
I wonder which channel do you want
I said yes to text channels
is it working?
Here's the slash options example.
oh I found the problem
how to handle DiscordServerError for task.loop? the task stopped if that exception occurs
Using the decorator @tasks.error
wdym?
@tasks.loop()
async def mytask():
...
@mytask.error
async def myerror():
...
I think a thing like that
tysm
i just need to restart the task? or stop/start
start
Btw is there a reason for that?
when there is an error the decorator willbe trigger and then it will continue to the next itinaration
so you can log the error, to a if insistance ... : pass else stop etc etc
its as u want
Anyone know why I can't access the embeds or content from a webhook message? It's all coming back as None, even though the webhook message contains an embed.
Code:
@Cog.listener()
async def on_message(self, message: discord.Message):
if message.channel.id != ADMIN_CHANNEL_ID or not message.webhook_id:
return
target_channel = await self._get_deal_channel(message.channel)
forwarded_message = await target_channel.send(
content=message.content,
embeds=message.embeds,
files=message.attachments,
)
Does ur bot have message content intents ?
.tag intents
Pycord Docs - Intents
Discord API Docs - Gateway Intents
import discord
from discord.ext import commands
# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True
...
# Get all non-priveliged intents; this excludes presences, members and message_content
intents = discord.Intents.default()
# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True # Required for prefix commands >= 2.0.0b5
# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()
# Apply intents when creating your bot
bot = commands.Bot(prefix="?", intents=intents)
no that should be the cause ty
tysm
Well this is pycord, mate
there is no discord.py place to go to
Discord.py has a support server.
whats the diff
Pycord is a different library.
syntax looks the same
ammmm
From interactions and then the layout is different.
If you use d.py, join their server and ask there.
u have link?
Google is free.
i dont think they have one
Yes they do.
look at github
ty
found it
if my laptop doesnt have wifi/Ethernet, the code can still send messages/webhooks?
probably not
Can you turn on a lamp if you cut the wire?
yes if its with batteries
A lamp with batteries doesn't have a wire to plug it in first off.
yes it is if its rechargeable batteries
Can you charge the batteries if you cut the charging cable?
you got me
no ☹️
Is there a .tag explaining blocking code, apart from .tag rie
as far as i know there's not
That would be nice
.tag blocking
Tag not found.
Like smth that gives an example with time.sleep vs asyncio.sleep and explains a bit the difference
This is a list of Frequently Asked Questions regarding using Pycord and its extension modules. Feel free to suggest a new question or submit one via pull requests. Coroutines: Questions regarding c...
Oh thanks
Does doing get_emoji on an application emoji not return the emoji, im trying to do a check if an emoji im getting from a list is animated or not but it just returns none if I use an application emoji id
the emoji is associated with my bot so i thought it would work
application emojis is not yet in the stable version.
If you need to use emojis from your app, just copy the markdown
Yea i just needed a way to check if they were animated or not since im pulling them from a list, its being used for my userinfo command for badges
https://void.lunascape.gay/kN9Pcv
i came up with the jankiest solution ever though so
Hmm, you can get the app emojis directly from the repository, but I think there may be bugs.
I'm not sure
Yea im not running latest commit rn, just latest stable.
idk discord is weird
does someone has a small script to make the bot talk in voice ?, just to test if it works because none of my experiement works
(preference without anything to install)
Here's the basic voice example.
wait no not that
its good
found my issue
inside my decorator
i was doing
ctx.voice_client = ...
but i cant do that
is there a way for i can do that:
@staticmethod
def valid_music():
async def wrapper(ctx: LumabotContext):
if not ctx.author.voice:
await ctx.respond(ctx.translator.music.error.not_connected)
elif not ctx.voice_client:
ctx.voice_client = await ctx.author.voice.channel.connect(
cls=wavelink.Player
)
return True
elif ctx.author.voice.channel != ctx.voice_client.channel:
await ctx.respond(ctx.translator.music.error.not_same_voice)
else:
return True
return False
return commands.check(wrapper)
I have a question, I removed some commands from my bot, why do they still exist in my discord channel?
it takes some time to sync, restart your discord, and this:
it's the opposite of
.tag slashnoshow
Application Commands Not Showing Up?
- Refresh Discord by restarting or pressing
Ctrl+R(orCommand ⌘ + R) - Uninstall libraries that conflict with the
discordnamespace (e.g.discord.py). - Invite your bot with the
application.commandsscope. - Load cogs before
bot.run()(e.g. not inon_ready). - Do not override
on_connect. - Update to the newest version of
py-cord(see?tag install). - Turn off
User Settings > Accessibility > Chat Input > Use legacy chat input. - Share your code and errors.
ty
When to use get_x() and when to use fetch_x() (where x is just the placeholder of something like user, channel etc)?
I dont get the question
when should I use fetch instead of get
uh
that is pretty rare when you only use fetch
you check for get_x if None and if None you use fetch_x
value = client.get_x()
if value == None:
value = client.fetch_x()
you dont want to do every time a API call to Discord because of rate limits
yeah, plus get retrieves data from the bot's cache, right?
get = tries to find the data at the Bot Cache
fetch = Does a API call to the discord API
alr thanks for the help
How do you retrieve the user who interacted with the select menu?
async def select_callback(self, select, interaction):
await interaction.response.send_message(f"The selection that was made was {select.values[0]}")
I wish to say The selection that was made by {user} was {select.values[0]}
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
thanks
hi, is there a way to somehow get the total number of user installs?
shows in the dev portal
yeah but is there a way to get it using the bot api? i want it for a stats command
not yet in pycord, but it does exist in the API
what's the endpoint for it?
thanks
Is it possible to disable a button on a message that is an ephemeral?
I tried this;
@ui.button(label="Cancel Deletion", custom_id="button-cancel-deletion-ticket", style=discord.ButtonStyle.gray)
async def cancel_button_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
button.disabled = True
await interaction.message.edit(view=self)
await interaction.response.send_message("Deletion cancelled!", ephemeral=True)
(even expanded the entire thing with an error log etc. and whenever I try to edit the latest message it says there was no message, so it raises a discord.NotFound)
So again, is this possible on a message that has view components but is an ephemeral?
(ping me if you respond)
use response.edit_message and send a followup instead of the other way around
thanks ^^
is there an example of making a custom help command that lists the bot's commands? i managed to do it but i feel like it's janky
show it
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
i might be remembering wrong but doesnt the paginator come with navigation by default
i think the button colors weren't what i wanted
im in the middle of rewriting everything
I need some quick advice if you guys don't mind...
- I have a task loop scheduled to run every 30 min that acts as a "message queue processor". It essentially checks a database for queued messages and sends them to a 3rd party API.
- Each message has to be a separate API call, so I use a
forloop to process all the messages. However, I only want to make these calls once every second to avoid overloading the API. - I tried placing
await asyncio.sleep(1)within the loop, which kinda works... But if a user calls a slash command withawait ctx.defer(ephemeral=True)in it while thisforloop is running I get the following error:discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction. I'm assuming this is because the bot is sleeping and not replying to Discord's request?
What would be the "proper" way to go about doing this?
#1130595287078015027 message
As per advaith it is documented and he made it seem it is intended to use. So it this something that could be added to pycord?
I have a view setup to edit the embed of a message when you press a certain button, but it says interaction failed even though everything works fine, is there something I did wrong for it to be like that?
Edit the message but it says the interaction failed?
Did you use defer()?
no, what's that?
In simple terms, you are telling Discord to wait longer for the interaction to respond, sometimes it can take a little longer than 3 seconds for Discord to receive the interaction and discord says failed.
At the start of the function that handles the button
the specific interactioin I assume, so for each callback?
If a view is used for multiple components you can use the interaction_check() event to simplify the process
Or you can put it in each callback if you prefer that
okay, I'll give it a shot, thanks.
Is there a way to, when I get a message, see what other users are in the channel?
I tried message.guild.members but it's only showing my bot in that list which is incorrect.
Do I need the members intent for that?
Ah yep, looks like that was it
that's not correct, pls use all intents
Uh... It is correct in that it works for me?
I don't need all intents
And it seems like bad practice to just... Add all of them in case I need a few of them
yes, it is correct. and no, you shouldn't request intents you don't need
then he can use ctx.guild.members probably message.guild.members is bug
No.
You cannot access guild.members without members intents
e.g. itll only be the bot, or at most, the command user + the bot
Is there any other way to send personal user messages except dm (dm can be closed)
Like send a message if they get banned, so they can see the ban reason
is there a way to make it so that an element of my description for a slash command is pulled from a database?
Tag not found.
.rtfm pending_application_commands
discord.ext.commands.Bot.pending_application_commands
discord.ext.commands.AutoShardedBot.pending_application_commands
discord.Bot.pending_application_commands
discord.AutoShardedBot.pending_application_commands
discord.ext.bridge.Bot.pending_application_commands
discord.ext.bridge.AutoShardedBot.pending_application_commands
You iterate over theese before running your bot and you can set the description and other thigns
I see, I don't know if that would work, because it would have to change while the bot is running
That would be quite complex, how often do you need to change the descriptions?
everytime a event in the queue gets moved up so like every 15-20 minutes or so
I don't need it tbh, but it would be cool
How many servers is the bot in?
it'll only ever be in one
then, in your command you can set guild_ids=[your_quild_id] and use sync_commands after editing your command
I'll take a look into it, thanks
I don't know if I mentioned that it's for a paramter of the applicaiton command not the description of the actual applicaiton command, I don't know if that changes anyhting
it shouldn't
You can try just passing waveform as a kwarg to sending a message but it might not work
You could also open an issue or PR so that is is more visible
Okay! Will do that later
hey guys does defer() just extend the timer or does it count as a response
both, really
I have a command that makes the bot say something via send (I dont want people to know who used it) and it works, but also always ends an ephemeral that says "application did not respond"
yea you still have to respond something to the actual interaction
and dont defer unless you really have to
from what I read it extends by 15 minutes, which is good but if theres one that makes a response happen without a msg that would be best
not possible
like I could always do ctx.respond("message sent successfully", ephemeral=True) but id rther not
you have to
and its better to give the user feedback
if i just sent a command and there was nothing in response i'd assume it failed
which is why discord is forcing a response
but you get the feedback by seeing the bot sent the message
all it does is clutter the channel
well it clutters for you until you dismiss it
its unecessary is all
maybe im nitpicking
guh
a single message..
why did i see that GIF in two seperate servers within 5m now wtf
are you in wunkcord
no
Looking for a method for my bot to get and run commands from other apps. Anyone got any ideas? TIA
Things I have tried (these are all in a commands.Cog context):
self.bot.get_application_command()with both a name and/or ID- Getting the other app's user with
app = self.bot.get_or_fetch_user()then usingapp.get_application_command(), again with both a name and/or ID.
You can't
Hi, I'm trying to add a premium subscription using the API to my testing server.
I have this error : Erreur: 401, {"message": "401: Unauthorized", "code": 0}
import requests
url = f"https://discord.com/api/v10/applications/
964234492078350398/entitlements"
headers = {
"Authorization": " my bot token was here",
"Content-Type": "application/json"
}
server_id = input("Entrez l'ID du serveur : ")
server_id = int(server_id)
data = {
"sku_id": "1282072278582169641",
"guild_id":
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
print("Test entitlement créé avec succès.")
else:
print(f"Erreur: {response.status_code}, {response.text}")
can anyone help ? thanks in advance
Auth should be Bot {TOKEN_HERE}, are you following that structure?
Its way easier if you use client.login with a bot token
you dont need a running bot to use py-cord
BOT, idk if the capital are important
but yeah Unauthorized should be cos because of the missing BOT
capital is important iirc
Thanks I edited this and with the help of some other peoples from Discord Devs server
import requests
url = "https://discord.com/api/v10/applications/964234492078350398/entitlements"
headers = {
"Authorization": "Bot MyBotTokenHere",
"Content-Type": "application/json"
}
server_id = input("Entrez l'ID du serveur : ")
server_id = int(server_id)
data = {
"sku_id": "1282072278582169641", # ID du SKU premium
"guild_id": server_id,
"owner_id": "1282090850804957294", # me
"owner_type": 1 # user
}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
print("Test entitlement créé avec succès.")
else:
print(f"Erreur: {response.status_code}, {response.text}")
Now I have this error : Erreur: 400, {"message": "Unknown Guild", "code": 10004}.
login needs to be awaited
so its Bot and not BOT
yh
thanks for the clarification
error explains itself
np
"unknow guild" but I checked twice that it's my guild ID
Ohh okay
py-cord casts them to ints for better usage
so why not just use py-cord as stated before
- create a
discord.Clientinstance, no need for more - create an async function:
- call
client.login()(needs await) - get or fetch the guild you want to create a test entitlement to
- create test entitlement using
guild.create_test_entitlement(needs await)
- call
- call asyncio.run on async function
if you're using the raw api, you would be better off asking in ddevs
<class 'int'>
discords sends them as strings to avoid overflows in some languages
why user can type another word in the autocomplete and use the command
like autocomplete return 1, 2, 3
but if user type 4 in the option
it can still normally to use the command
because its autocomplete
they can type anything they want into it
you have to check it at your own
ok... Alright thanks
its not like choices
but choices is a hard coded list what you cannot change without a bot restart
autocomplete is exactly that- auto complete
^
Link to startup guide?
I didn't use PyCord in like a year and i used it in bridge mode

thx
Is there any way to update the commands bar in ds client without restart?
no
Any idea why this might be happening? My welcome command at the bottom calls "self._create_channel_selection_view":
callback = lambda i: self._handle_welcome_channel_selection(i, ctx)
print("CALLED3")
embed, view = await self._create_channel_selection_view(ctx, embed, callback)
await ctx.respond(embed=embed, view=view, ephemeral=False)
Here it is defined:
async def _create_channel_selection_view(self, ctx, embed, callback):
print("CALLED5")
select = await self._get_text_channel_select(ctx)
select.callback = callback
view = discord.ui.View()
view.add_item(select)
return embed, view
self._create_channel_selection_view is called, yet after this point, the bot does not respond. and I do not see "called5"
All the code works, but not when it is called with "self."
#1132206148309749830 message
ouii
c'est un bot quoi
viens dm c'est pas le bon endroit pour parler de ça ici
do you have to await task.start() method rn? because it used to work fine back in a year
File "C:\Developments\main.py", line 840, in <module>
blockedtimeout.start()
File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\tasks\__init__.py", line 398, in start
self._task = asyncio.create_task(self._loop(*args, **kwargs))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\asyncio\tasks.py", line 371, in create_task
loop = events.get_running_loop()
^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: no running event loop
sys:1: RuntimeWarning: coroutine 'Loop._loop' was never awaited
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
how do i send 2 embeds at once with a response
kindof like this
await interaction.respond(embed=[embed1, embed2])```
this is the code
@tasks.loop(seconds=2)
async def blockedtimeout():
# some code
loop = asyncio.new_event_loop()
loop.run_until_complete(get_server_info())
blockedtimeout.start()
bot.run(key)
use embeds kwarg
^ just add a s
thx
help
await it
i thought task.start() method does the thing for you?
its not an asynchronous method
oh wait
can you show your code
right here
ah
do you use cogs?
yeah
just put it in a cog then, and not your main file
and then start it from the __init__
no lol
No, leave bot.runcwhere it is
if you use cogs, your main file ideally has nothing bu the bot setup + start, and on_ready, and cog loading
it raises new error rn, it says bot.load_extension is not awaited
do you use discord.py lol
no
its really huge i'll clip some of it
just the cog loading really
(also i recommend just using the pypi package as requirement instead of the github unless you really need all in-dev features)
When, you have a second can you show this entire file
oh pls dont use the master branch as a requirements
already said :)
a bunch of imports here
extensions = ["cogs.maincog", "cogs.utilitiescog", "cogs.devcog"]
async def get_server_info():
cluster = motor.motor_asyncio.AsyncIOMotorClient(db_url, serverSelectionTimeoutMS=5000)
try:
await cluster.server_info()
print(" * Connected to the Database server.")
except Exception:
print("Unable to connect to the server.")
@tasks.loop(seconds=2)
async def blockedtimeout():
# some code
if __name__ == '__main__':
for extension in extensions:
bot.load_extension(extension)
print(f"Loaded {extension[5:].capitalize()} extension")
loop = asyncio.new_event_loop()
loop.run_until_complete(get_server_info())
blockedtimeout.start()
bot.run(key)
requests uh
thats a part of the bot feature
do you use a new runner for it?
requests is built in lol
is it? i dont remember lol this project used to work in about a year ago
i didnt touch anything and it's not working rn
either way first of all please replace the pycord dependency with py-cord==2.6.0 to make sure there isnt any issue with the master branch rn
and of course uninstall and reinstall py-cord accordingly
then we can look further
also you still didnt put this in a cog lol
oh wait, am i supposed to run it in a cog?
but the function is in my main.py file ._.
is that the best practice? to run tasks in cogs
yes (imo)
as i said
my original code worked after i reinstalled py-cord in version 2.6.0 😂
also what are the factors that makes it longer for your bot to ready?
i kinda forgotten all these stuff
Loading members to the cache
I think you can disable this with the chunk_guilds_on_startup=False kwarg to bot
i do have this kwarg
but my bot is not readying
And logging in as a sharded bot but I dont think you can make this faster
wait i guess my bot isn't sharded
How many guilds is it in
it's probably not sharded its only in a few hundred servers i assume
i dont remember coding sharding system for the bot
Yeah sharding is recommended above 1000 guilds required at 2500. Under 1000 not recommended because it will actually slow things down
so there must be another reason that my bot is not readying
can you comment out, and see
loop = asyncio.new_event_loop()
loop.run_until_complete(get_server_info())
i figured out my bot's token has been reset for some reason and the error is only showing up after stopping the deploy
hmm strange
i came back to this project because i received a message from discord saying my bot verification is going to expire in about two months 😂
there's so much i have to revise

also how big of a difference is pycord and discordpy rn?
Discord API support they are essentially identical but implementation is quite different
yes, i migrated to pycord when slash commands are enforced
yea many did, since the dpy guy basically rage quit when slash commands were announced lol
what about the new function method names, and features?
well for one, dpy doesnt use like @bot.command, but uses a weird (overcomplicated) tree system for commands
dont ask me, i dont know much more either, just that pycord is considerably easier
the worst part is they decided to come back
Everything new is named slightly different. Very little overlap.
you might get some functions to work but it would work differently and create a lot of hidden bugs
but core library basics like idfk guild.channels and guild.get_channel, you name it, are overall really similar if not 90% the same
because it was just taken from dpy and never (needed to) change
it took me 2 weeks to migrate from discordpy to pycord and rewrite everything in slash command, im not spending another 2 weeks to migrate back again
yea as long as bob is keeping up with the updates
ah you missed the bob situation lol
what was it?
Well bob does not do alot of the development anymore but other people are
oh yeah i can tell
a relatively big update was ready but bob was gone for quite some time which meant the pypi package couldn't be updated
i used to play clashofcode with him
but i think control of that was transferred to someone else? but i dont remember exactly
well updates come out when ready now so 
man it'll be a pain if i have to migrate back to discordpy some day
you wont
IF pycord ever was to stop development, there'd just be another fork, and business as usual
im planning to rewrite the whole bot during december because after a year i look back at my code and it's ugly af
ikr
Yeah, I dont see py-cord dying at any point.
smh 20k lines of code of gibberish
no lol
my main.py is the only clean file i have
although it still has around 1k lines of code
oh yeah my cogs are pretty clean too
bruh mine has like 28
i put all the loop functions and bot events in main.py
yea you should really consider splitting it up
i tried but when i do that everything breaks
i implemented a dynamic cooldown for my bot
e.g. this is how i structured my bot
especially the helper classes cut down on a lot
and utils in general ofc
idk if you know but that is built into pycord kind of
wdym
dynamic cooldowns
The following section outlines the API of Pycord’s prefixed command extension module. Bots: Bot: Attributes activity, allowed_mentions, application_flags, application_id, cached_messages, case_inse...
wait what was the feature of this again?
well
dynamic cooldowns lol
because i remember i implemented this back in 2021 or 2022 because its not flexible enough to achieve what i wanted
i mean you can do a ton with it
yeah right, it says a command can only have one cooldown
what i wanted is, check for a condition, if true the cooldown will be longer, otherwise it will be shorter
i dont think dynamic cooldown provides this feature, and that's probably the reason i rewrote the whole thing
thast exactly what dynamic cooldowns do
check the dummy function
yea thats exactly what dynamic cooldowns let you do lol
i am 100% sure back in the days they dont provide this feature
so i had to implement it myself
It was even at 2018?
look at the docs, its well described
it says it takes discord.Message as a parameter but i have literally no idea how it works
i probably just forgotten everything it's been at least a year since i last touched bot development
message.author and you have all you need
yeah but it doesn't allow me to enter two different cooldown duration right?
because this is how i used the cooldown
referring to the custom cooldown i implemented above, it will give the user a 900s cooldown if they are not a donator, and 600s cooldown for a donator
is this possible with the built-in dynamic cooldown?
yes.
huh.
theres no way
i mean it takes a discord.Message as a parameter how is it possible
yeah i joined before v.20 came out
i still have the v2.0 tester role
i just realised how terrible is my code
12 database read write in the on_application_comand event, and a bunch of if else statement checks
wtf
yeah i have a database that traces what's the last time the user used a command, and the command they used etc
also check if they are userbotting like using the same command again and again, and check if they are banned/temporary blocked from using the bot
also checks if the bot is currently under maintenance, or if there's new updates that should inform the user for the first time they use a command
damn
there's going to be a bunch of work for the revamp
Since when ?
hi guys! my button stops working after 5-10 minutes (no error)
code:
class FormButton(View):
@discord.ui.button(label = 'Send request', style = discord.ButtonStyle.green, custom_id="fmbt")
async def button_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
modal = RoleModal(title = 'Request')
await interaction.response.send_modal(modal)
print(123)
Here's the persistent example.
you nneed this
what exactly do i need?
mainly this in the on ready, and making your view have no timeout
discord.AutoModAction
discord.AutoModAction.metadata
discord.AutoModAction.type
discord.AutoModActionExecutionEvent
discord.AutoModActionExecutionEvent.action
discord.AutoModActionExecutionEvent.alert_system_message
discord.AutoModActionExecutionEvent.alert_system_message_id
discord.AutoModActionExecutionEvent.channel
discord.AutoModActionExecutionEvent.channel_id
discord.AutoModActionExecutionEvent.content
discord.AutoModActionExecutionEvent.data
discord.AutoModActionExecutionEvent.guild
discord.AutoModActionExecutionEvent.guild_id
discord.AutoModActionExecutionEvent.matched_content
discord.AutoModActionExecutionEvent.matched_keyword
Is there a way for a bot to add, remove, enable & disable automod rules? Can't seem to find much anywhere...
create and delete yes
enable and disable, not sure
Any chance you can point me toward some docs regarding creating/deleting? I've had a look on https://docs.pycord.dev/en/stable/api/models.html#automod but it doesn't seem to help much lol
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
you're so close
creating rules is a method of Guild
Awesome, thanks :D
I'm currently testing changes for a bot on a test server and although I've limited all commands from that bot to be executed within one channel (in the server integrations) on the test server I can still see and successfully execute the commands in other channels as well (restarted the bot and reloaded discord already)
Is that a thing because I'm also the owner of the test server?
I'm on version 2.3
Is that a thing because I'm also the owner of the test server?
yes
ah ok
thanks!
Hey guys, what i got wrong here? trying to run some blocking code this way but i get an error
I fixed this, just added None as first arg. Although deferring a modal doesn't send the message "Bot is working..."?
if you want the "thinking" message, set invisible=False
in the defer?
yes
alright tomorrow i'll try ty
worked ty
can i'm attach variable to member?
can you explain in a full sentence
sad
ok
I am trying to make User Installed App but it doest seem to be working, am i doing something wrong?
bot logs in but doesnt show cmd , I tried reloading discord for cache, it didnt work
i think i found it
it would be default_command_integration_types and not default_integration_types
discord.Bot
discord.Bot.activity
discord.Bot.add_application_command
discord.Bot.add_check
discord.Bot.add_cog
discord.Bot.add_listener
discord.Bot.add_view
discord.Bot.after_invoke
discord.Bot.allowed_mentions
discord.Bot.application_command
discord.Bot.application_flags
discord.Bot.application_id
discord.Bot.application_info
discord.Bot.auto_sync_commands
discord.Bot.before_identify_hook
thnx
hey guys, I THINK i've been looking at this too long, but i'm getting a NoneType error telling me serverrole doesn't have the members attribute, yet in debug every part of the right side of the assignment resolves?
profession: discord.Option(str, choices=['Alchemy', 'Blacksmithing', 'Enchanting', 'Engineering', 'Inscription', 'Jewelcrafting', 'Leatherworking','Tailoring'])
,):
if profession == 'Alchemy':
serverrole= discord.utils.get(ctx.guild.roles, name=profession)
discord.utils.get(ctx.guild.roles, name=profession) return None
i'm forcing the user to select a prof though?
print serverrole
by fetching it
oh my god. I never saved it in my test server. If this works i'm headbutting a wall.
I am officially an idiot. Thank you for rubber ducking
okay next question (SORRY) - using the same block of code, it now executes fine but with multiple users added to the role only returns the first into the serverrole variable
show the code
profession: discord.Option(str, choices=['Alchemy', 'Blacksmithing', 'Enchanting', 'Engineering', 'Inscription', 'Jewelcrafting', 'Leatherworking','Tailoring'])
,):
if profession == 'Alchemy':
serverrole= discord.utils.get(ctx.guild.roles, name=profession)
if serverrole.members:
members_list = "\n".join(str(member.mention) for member in serverrole.members)
await ctx.respond(f"The users in the {profession} role are: \n{members_list}", ephemeral=True)
else:
await ctx.respond(f"No members in the {profession} role", ephemeral=True) ```
When Alchemy is selected, only one user is returned
yet it has two users
that's the output
Can you show the bot intents
in the codebase? or in the discord dev panel
the bot
did you also added it to the bot?
I mean at bot = discord.Bot
can you show thez print of serverrole.members
so you dont have any role intents
for me it need member intents
[<Member id=202471364454514689 name='.igglepiggle' global_name='IgglePiggle' bot=False nick=None guild=<Guild id=1276103481287249990 name='MyBotFarm' shard_id=0 chunked=False member_count=5>>] is the print
only returns one member
try with adding member intents
if i'm understanding the skeleton I used from the pycord documentation, that's correct
intents.member_intents = True?
(very VERY new to python)
aah okay my mistake thank you
That has fixed it. Thank you very much. I'll read up on member intents now so I understand why.
Hi, I have an issue with my premium button
button = Button(
style=discord.ButtonStyle.premium,
sku_id= 1282125623967354920
)
It says : discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
I checked and 1282125623967354920 is my sku ID. Anyone knows what I have this error ?
it says the same if I try with str
i didn't realize premium was a button style.. is it new and the docs don't show the addition? https://guide.pycord.dev/interactions/ui-components/buttons#button-styles
Learn all about implementing buttons in your Discord Bot using Pycord.
The API provides some enumerations for certain types of strings to avoid the API from being stringly typed in case the strings change in the future. All enumerations are subclasses of an internal c...
Guide is very outdated.
this style is quite new
the error discord gives you should tell you what's invalid
I double-checked and sent a screenshot of the sku url that I have in the dev portail
Oh yes I forgot
one sc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.sku_id: Invalid SKU
but as I said I double checked
.
guys, how to use __slots__?
Is it possible to have an issue reopened on github once someone has closed it?
yes
How would one do that?
you can only re-open issues that you created or if the issues are in your repository
in this case, this issue is closed for good
oh, so should I just open another one then since there is more info now?
if you believe that should be the case, go ahead
The issue is that the full name is no longer displayed, and only the first letter is shown. Originally, the entire name was supposed to appear, but now it doesn't work anymore. It's unclear where the problem lies; it might be related to the database
class CreateTicketSelect(discord.ui.View):
def __init__(self, guild_id):
super().__init__(timeout=None)
self.guild_id = guild_id
async def generate_select_options(self):
options = await db.get_options(self.guild_id)
return [discord.SelectOption(label=option, value=option) for option in options]
@discord.ui.select(
custom_id="ticket_select",
placeholder="👆 | CLICK ME!",
options=[],
)
async def select_callback(self, select, interaction):
try:
options = await self.generate_select_options()
select.options = options
await interaction.response.edit_message(view=self)
except discord.errors.InteractionResponded:
await interaction.followup.edit_message(message_id=interaction.message.id, view=self)``` ```py
async def get_options(self, guild_id):
options = await self.all("SELECT option_name FROM ticket_options WHERE guild_id = ?", (guild_id,))
return [option[0] for option in options]```
why do you not fill the options when creating the select?
By default, the option is displayed with the full name, but when you set the database, the option is not displayed with the full name. That's the problem!
Return option[0] return the first occcenrure so the first eltter
Just do return option for option in options
Else check ur db to see if there is full name
Did u try to remove the [0]
where, then ?
In ur get_options
I mean in the code u shared this only appeared once
I don't understand what you mean can you for me do?
…
remove the [0]
Then test
but it still doesn't work
go to 2.6
He is using ezcord
from what you shared in the screenshot it looks like it works perfectly fine
For options you should use
yes it works on the print but on the select menu it always shows
?
ya
@ticket.command(description="add a ticket Select Option")
async def add(self, ctx, name: Option(str)): # type: ignore
guild_id = ctx.guild.id
if await db.name_exists(guild_id, name):
await ctx.respond("The option already exists.", ephemeral=True)
return
await db.add_option(guild_id, name)
await ctx.respond("The option was added successfully.", ephemeral=True)
ticket_message_id = await db.get_message(guild_id)
if ticket_message_id:
channel = ctx.guild.get_channel(await db.get_channel(guild_id))
if channel:
try:
message = await channel.fetch_message(ticket_message_id)
view = CreateTicketSelect(guild_id)
await message.edit(view=view)
except discord.NotFound:
print(f"Ticket message not found for guild {guild_id}")```
@fresh sierra
if the value prints correctly, there is no way this only returns the first letter as the option name unless you're doing something else
like what you see in the thing
how is the select menu being created
here
according to ur code after you click on the dropdown it should edit the option right @rare marlin
but my question is how can they click on the dropdown if there is no option ?
yea i still am confused why they initialise the menu with no options selected
is that even possible ?
apparently
well
i cant do what he is doing
Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0.options: Must be between 1 and 25 in length.
@rare marlin can you actually send the dropdown ?
with discord modals is possible to select some users?
modals are text only
as i said
send the dropdown click me
again to see if its work
because i explain to u my thing
u should not be able to send an empty dropdown
what i think u should use it creating option dynamically
HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0.options: Must be between 1 and 25 in length.```
@fresh sierra Can I send you the whole code? @sage tendon
I have now fixed the error but it still only shows the first letter, do you know why? @fresh sierra
.
How can I fix it? Where is the error?
you need to create a dropdown withotu the decorator
to be able to pass the option as the creation dynamically
how?
What's the difference between category.id and category_id ? (Ping me on reply)
oh wait
category_id is to specify where a new channel should belong to
answered my own question
why are they needed Cogs?
So you can split your code into multiple files
ok, but why should I split it?
so you avoid having one huge impractical file with everything in it
They are somewhat of a leftover from prefix commands as you could reload your cogs and the commands would change. I think you can still reload the cogs as long as you do not change the command definition. It gets weird when you want to hot reload a command definition
cogs are all but leftovers
how can I perform each task in turn (sequentially, one after the other). I am using aiosqlite and my database is being blocked due to multiple tasks
my attempt would be to start each task after the one before finished, maybe you could use custom events for that?
your database connector should handle concurrent access
it might block but only for a few milliseconds
You might need to look into connection pools
I'm seeing a weird issue with paginators, where if I have two paginators that were invoked by different commands both active at the same time, I get an index error when trying to page through the first one. If i invoke the same command twice to get 2 of the same paginator though, they both happily work. Am I doing something wrong?
Are you editing a list or dict in your callback that could be shared between paginators
hmm, no. This is the full error:
Traceback (most recent call last):
File "/Users/derek/Code/pzsd-bot/.venv/lib/python3.10/site-packages/discord/ui/view.py", line 426, in _scheduled_task
await item.callback(interaction)
File "/Users/derek/Code/pzsd-bot/.venv/lib/python3.10/site-packages/discord/ext/pages/pagination.py", line 121, in callback
await self.paginator.goto_page(
File "/Users/derek/Code/pzsd-bot/.venv/lib/python3.10/site-packages/discord/ext/pages/pagination.py", line 691, in goto_page
page = self.pages[page_number]
IndexError: list index out of range
Each paginator gets its own new list of pages, even when invoking the same command twice
Strange, you should open a thread with your code
I'm not on PC so I can't test right now tho
Asking again in case I am just dumb:
Is there a way to pre-emptively restrict SlashCommandGroups to specific Roles or at least flags (e.g. kick_members or whatever) so I don't have to manually go into Integrations?
Ah, maybe checks is a good starting point https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_cog_groups.py#L23
I see there's commands.has_role(...)... can I use that to specify a specific Role? Or would there not be enough context to enforce that by the time it registers the commands with Discord?
All checks are performed by the bot. So the bot will still receive the command and throw an error if the check is not met.
Default Permissions and the integrations menu are the only way to hide the command from users
IE you cant restrict a command based on a role or user via your code
Thank you. Although what do you mean by 'Default Permissions' being able to hide commands?
If you set default permissions to admin ONLY admins can see the command at all
More general to what toothy said
If you set default permissions to something the user can only see that command if they have those permissions. If integration settings are set they will override the default permissions
So for example a ban command can have the default permissions of ban_members and that will make it so that when the bot is first added to the guild only people who are allowed to ban can use it until the owner customizes the integration settings to their needs
Ah. Got it. Thank you, that’s helpful
Is there any way to make "single guild" bots more redundant?
Essentially I want to run two instances in different DCs
for what purpose
redundancy..
If network drops in DC1 but works in DC2 then the bot should stay online.
Not quite familiar with sharding, however I believe a guild can only "belong" to one shard.
yes
from my testing there's only ever one response even if the bot runs twice
if you use followup or ctx.respond, you still send something from the second bot instance
i do always use respond
let me retest
nope, one response in chat
cant check the other bot's console rn tho
how to create custom check for slash_command
with open('config.json', 'r') as f:
config = json.load(f)
admin_users = config['admin_users']
def is_admin():
async def predicate(ctx: discord.ApplicationContext):
return str(ctx.author.id) in admin_users
return commands.check(predicate)
@bot.slash_command(name="admin_add", description="Add a Pokémon to the database.", checks=[is_admin().predicate])
@discord.default_permissions(manage_guild=True)
async def admin_add(ctx, image_url: str, pokemon_name: str):
Is this how I supposed to do it?
@bot.slash_command(name="admin_add", description="Add a Pokémon to the database.")
@discord.default_permissions(manage_guild=True)
@is_admin()
async def admin_add(ctx, image_url: str, pokemon_name: str):
this seem more logical to me
but depends on how u want
ok
Ignoring exception in on_application_command_error
Traceback (most recent call last):
File "/home/container/.local/lib/python3.12/site-packages/discord/client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "/home/container/main.py", line 319, in on_application_command_error
raise error
File "/home/container/.local/lib/python3.12/site-packages/discord/bot.py", line 1137, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.12/site-packages/discord/commands/core.py", line 432, in invoke
await self.prepare(ctx)
File "/home/container/.local/lib/python3.12/site-packages/discord/commands/core.py", line 354, in prepare
raise CheckFailure(
discord.errors.CheckFailure: The check functions for the command spawn failed
i am getting this
on both type of check styles
are you returning true or false?
.
thats all i have
{
"admin_users" : [330342042687504395]
}
config.json
i'll be dammed, i was converting userid to string fk
that's why it wasn't matching
this is very bizarre, having two paginators active at once, trying to go to the next page of paginator A will actually affect paginator B instead. I have a thread open with my code, though idk if those get looked as actively as here. In any case, it seems the paginator class is getting confused on which buttons refer to which paginator? Has anyone else experienced something like this?
oh wait a second, do I need to provide a separate list of custom buttons to each paginator? all my paginators are sharing the same list of buttons
that's the only thing i can think of that could cause an issue. guess i'll test providing copies of the list so each is getting new button instances
nope, that didn't fix it. even with completely different instances of paginator buttons, the two paginators are still somehow linked
Answered fisk in the thread
Hey I had py-cord working then i cleaned my project up and repackaged it into a docker file, now its having problems with a slash commands with descriptions? did somthing change?
any errors?
nothing in the console
do you use ctx.send and not respond?
that looks fine for me
my other comands work too, just not this one.
Hard refresh your client.
ctrl + r
I Closed and re-opened discord itself, not the bot. that worked? I'm really confused now.
But thank you
Yes I meant the app.
Just discord things i guess.
How does one get the cog commands to sync/ work with the desktop client? Can get it to work on the web app
Do you mean the commands are not showing up on discord?
If so restart your discord client. Ctrl + r. It is just discord being slow to update them so you have to force it to
Why didn't I think of that, thanks lol
np, a very common issue we have here 
It showed on the list of commands but calling it did nothing lol
Needing a hand with some discord.Option related stuff.
I have a command arg with predefined options via discord.Option with a ton of discord.OptionChoice elements in the choices arg. The choices list is 51 items long, with a max of 25 (this is the issue).
Is there any work-around for it? Thanks :D
you can only use autocomplete
but that doesnt enforce the options, it just suggests them, the user can still enter everything
(and btw you dont need optionchoices unless you want the displayed value to be different from the actual value
Is there a way to only restict to the provided options?
Ouch >.<
why does @discord.default_permissions not check permissions at all? or am i using it wrong here?
everyone is able to execute that command
Can you make sure that permissions in the integration menu are not overriding the default permissions?
im sorry, could you please explain what you mean? i dont quite get it
i thought that works the same as @commands.has_permissions
So default permissions are the permissions that are required unless they are overridden by an admin in the guild.
You can go to Server Settings -> Integrations -> your bot
If these are set they will override the default permissions
Commands permissions is the bot checking if the user has permission
Default permissions is discord checking if the user has permission unless overridden
thank you for your explanation
well i never changed anything there so there shouldnt be any overrides
It does not work with subcommands
just figured, thanks you two!
You can only do it on the original group by passing default_member_permissions with a discord.Permissions object

is that possible to setup a global check in a cog ?
Basic Pycord Help (UPDATE TO 2.6.1!)
quest = bot.create_group(name="quest", description="Manage you regional quests")
```How can i create quest as a solo slash_command as well use as group command?
I currently know how to create a slashgroupcommand and its subcommands and I don't know a way to use that group command as solo slash_command
for example:
`/quest add region:Alaska` : using quest with sub command
`/quest`: using quest as solo slash_command
I wanted to show info about quest of user using just /quest but if i can't find any help, then i'll be forced to shift to /quest info instead
not possible
thanks but no thanks :)
that makes no sense in response to that message
i mean you cleared my query but it didn't helped to achieve the main goal
yeah on it currently
set the view timeout to None, but i keep getting "This interaction failed"
did you also add it to the bot?
interaction can be failed due to errors too
you need to do self.bot.add_view(View())
is it possible to create mutiple choosable options
like a user can select mutiple options from choices?
in a select? yes
no, in slash_command options
then no
ahh guessed it :/
you can kind of simulate that with autocomplete
but the user can then just type whatever they damn well please
i'd just make multiple options
results in "Application Command raised an exception: ValueError: View is not persistent. Items need to have a custom_id set and View must have no timeout"
why don't you make a sperate view class
makes it much cleaner to handle
and yea you didnt set no timeout
was planning to clean it up into a view class once I had select menus figured out
lol
The option list isn't much so one option at a time won't hurt
I initially had a timeout, where I set view = View(timeout=None), but removed that timeout before running into that error
yea add it back
partially worked, the add_view at the bottom is returning TypeError: object NoneType can't be used in 'await' expression
code
here's that whole thing
and show the error too
had an await, but, removed it after getting the error
while it works, the select menus don't pop up
show
this is what happens after running the command
any error?
nope
show where you send the message then
because i dont think you do
since you arent using ctx in that command
i'm hitting enter after the command
you arent responding to the interaction in your code
dont add persistent view in command
thats 1 thing
and show ur whole code of command
they're just missing ctx.respond, thats all
hmm, any way to not make this persistent?
what
replace self.client.add_view with await ctx.respond(view=view)
they'll still need to add the view to the bot tho if they want it to be persistent
which would be much cleaner with a seperate class :>
yeah but that would add it with every command run
i know
worked, but "this interaction failed" is back
yea because you arent adding the view to the bot
first of all make a seperate view class before you do anything else
and then add that to the bot in on_ready
might as well, ty
bump
why?
Didn't update
why?
update
test everything
done
update test everything some big big turns out happening
*bug
Security risk of some sort
and everything goes to shit
you think about it too much
n.n
Ab ins Bett mit euch!
voxy is right
followed this, got it to work: https://guide.pycord.dev/interactions/ui-components/dropdowns/
Learn all about implementing Select Menus or Dropdowns in your Discord Bot with Pycord.
the only thing I'm not sure of is if I can only pass one select menu within the class
From what I read (unconfirmed) it's 5, but can't seem to add another one
I think it's 3 or 4
here's where I'm at, only the first select shows
async def cog_check / async def cog_check
I mean a global check
For I put a check in a cog that does that for every command in the whole bot
This is gonna be a check but not a global check right ?
Im gonna try
But in my memory it was not doing a global check
i don't think its a decorator
just a method
And thanks for clearing that, it was what I was shezrching for
hello, i am trying to create a delete button that deletes a message. i made the custom id channel_id-message_id. in the callback method, i tried messageObj = await commands.MessageConverter().convert(interaction.context, message_id) but it errors with
AttributeError: '_EnumValue_InteractionContextType' object has no attribute 'guild'.
can i actually do this? basically trying to delete reported messages and the view is hidden from the public
The delete button deletes the message it was sent on? Or it deletes another message?
Just pass the message object to your view class through the init
Or pass your channel ID and message ID and then create a PartialMessage
you should not be using the message converter in that way. If anything you should be using my_channel.get_message() and my_channel.fetch_message(). But like dark said for deleting messages you only need a PartialMessage
thank you!
How can I upload emojis to the bot?
Since even I know how to upload emojis to a discord server, but how could I do it for the same bot?
go to the discord developer portal, click on your application, click on emojis and you can upload it from there
Can't it be uploaded with a pycord function?
not yet, but soon
isnt role.position should return the role position and so not the same number for many role ? (each role in the guild has 2 as position after)
(this issue is not there is 2.5 so yeah seems that is a 2.6 issue)
after updating to 2.6.1 role.position only return 1
How can I programmatically end the bot process without any traceback or extra console output?
(sys.exit(0) outputs traceback and bot.close() prints some extra warning messages)
i created this slashGroupCommand and added subcommands to it but I also want to create its prefix version so I went through Bridge Commands but I can't seem to find how to use a slash group as both prefix command group and slash command group
You might have to use bridge group for it
you mean like
quest = bot.bridge_group(name="quest", description="Manage your regional quests")```like this?
Maybe, I never did it with bridge commands
Here's the bridge commands example.
showcased there
and then use it like this
@quest.command(name, description)
async def add(args)```
just 1 more question, i have added options in one of the slash commands, but since in prefix commands users can't see choices, so do i need to add additional custom validation decorator to check if the has entered valid choice?
or pycord has internal validation function to raise error for wrong choice input?
Using choices only choices can be pass in prefix
Using autocomplete everything can be use
suppose there are two choices male & female but the user inputs child using prefix command. So will the command return error or will it not get invoked?
Yes
yes what?
i have add as subcommand under quest group. so to use it in prefix method user must invoke it like this right?
!quest add Alaska
*Alaska for region argument in add subcommand
can u give Me discord.Interaction doc link? @errant trout
Look it up yourself?
https://docs.pycord.dev
Pycord is a modern, easy to use, feature-rich, and async ready API wrapper for Discord. Features: Modern Pythonic API using async/ await syntax, Sane rate limit handling that prevents 429s, Command...
You'll be shocked when you find out there's a search bar.
and hyperlinks to look further
i didn't find that why i asked
plz help me out
thanku so much
is it so hard?
yes
@isAdmin()
async def view(self, ctx):
.....
ctx is a required argument which is missing
class Config(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.functions = Functions()
@commands.group(name="hostrole", description="View host role commands.")
@isAdmin()
async def hostrole(self, ctx):
///....
it is in a cog/class and only started once i updated @isAdmin(), i removed the isadmin check from the command yet it still did it
thats not how you define a slash group
you do
x = SlashCommandGroup(...)
//later
@x.command()
async def...
tho if its prefix ignore what i said and idk how prefix groups work
yes its prefixed
it worked earlier on till i edited isadmin
despite it doing the same thingwith and without it
fake perms
def __init__(self, bot):
self.bot = bot
self.functions = Functions()
@commands.group(name="hostrole", description="View host role commands.")
async def hostrole(self, ctx):
if ctx.invoked_subcommand is None:
subcommands = [f"`{ctx.prefix}{command.qualified_name} {command.signature}`".strip() for command in self.hostrole.commands]
subcommands_list = '\n'.join(subcommands)
embed = discord.Embed(title=f"{ctx.command}".title() + " Commands", description=subcommands_list, colour=0xFFFFFF)
embed.timestamp = discord.utils.utcnow()
if any(command.signature for command in self.hostrole.commands):
embed.add_field(name="Parameters", value="`<required>` `[optional]`", inline=False)
await ctx.send(embed=embed)
@hostrole.command(name="add", description="Add a role to the host roles.")
async def add(self, ctx, *, role: commands.RoleConverter):
fail_check = await self.functions.roleCheck(ctx, role)
if fail_check:
await self.functions.databaseRemove("global", "roleConfigs", "hostRole", "id", ctx.guild.id, role.id)
return
data = await self.functions.databaseAdd("global", "roleConfigs", "hostRole", "id", ctx.guild.id, role.id)
if not data:
embed = discord.Embed(description=f":whitealert: {ctx.author.mention} - {role.mention} is already a host role.", color=0xFFFFFF)
await ctx.reply(embed=embed, mention_author=False)
return
embed = discord.Embed(description=f":success: {ctx.author.mention} - {role.mention} is now a host role.", color=0xFFFFFF)
await ctx.reply(embed=embed, mention_author=False)
thats some other cmds
remove the @isAdmin() still doing it
what
idk how to explain it
but
its pretty much if you have a role you want to be able to access commands but dont want to give it the actual permission, e.g, ban member
.rtfm has_any_role
database for multiple servers but thats not the problem
class Config(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.functions = Functions()
@commands.group(name="hostrole", description="View host role commands.")
async def hostrole(self, ctx):
if ctx.invoked_subcommand is None:
subcommands = [f"`{ctx.prefix}{command.qualified_name} {command.signature}`".strip() for command in self.hostrole.commands]
subcommands_list = '\n'.join(subcommands)
embed = discord.Embed(title=f"{ctx.command}".title() + " Commands", description=subcommands_list, colour=0xFFFFFF)
embed.timestamp = discord.utils.utcnow()
if any(command.signature for command in self.hostrole.commands):
embed.add_field(name="Parameters", value="`<required>` `[optional]`", inline=False)
await ctx.send(embed=embed)
@hostrole.command(name="add", description="Add a role to the host roles.")
async def add(self, ctx, *, role: commands.RoleConverter):
fail_check = await self.functions.roleCheck(ctx, role)
if fail_check:
await self.functions.databaseRemove("global", "roleConfigs", "hostRole", "id", ctx.guild.id, role.id)
return
data = await self.functions.databaseAdd("global", "roleConfigs", "hostRole", "id", ctx.guild.id, role.id)
if not data:
embed = discord.Embed(description=f":whitealert: {ctx.author.mention} - {role.mention} is already a host role.", color=0xFFFFFF)
await ctx.reply(embed=embed, mention_author=False)
return
embed = discord.Embed(description=f":success: {ctx.author.mention} - {role.mention} is now a host role.", color=0xFFFFFF)
await ctx.reply(embed=embed, mention_author=False)
ctx is a required argument that is missing.
It's a prefixed group command btw
can you send the full error/traceback
thats the error printed off
the FULL traceback
is it indented correctly
yep
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.```
there should be more in the terminal
I want to make sure it is referenceing the right thing
yh
<discord.ext.commands.context.Context object at 0x000001DBECC648E0>
Ignoring exception in command hostrole view:
Traceback (most recent call last):
File "C:\Users\ferne\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\bot.py", line 349, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\ferne\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 1550, in invoke
await ctx.invoked_subcommand.invoke(ctx)
File "C:\Users\ferne\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 951, in invoke
await self.prepare(ctx)
File "C:\Users\ferne\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 881, in prepare
await self._parse_arguments(ctx)
File "C:\Users\ferne\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 783, in _parse_arguments
transformed = await self.transform(ctx, param)
File "C:\Users\ferne\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 610, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.
what i've noticed is that it seems to be acting as if self isnt there
like in my bots error log channel it shows:
Command raised an exception: AttributeError: 'Context' object has no attribute 'functions'
which is what im guessing is referring to:
data = await self.functions.databaseFetchResult("global", "roleConfigs", "hostRole", "id", ctx.guild.id)
almost, but wrong
it's passing ctx to self
Which generally implies that the fucntion is not in the class IE not indented correctly or something else above it is not indented corecctly
Restarted and checked
everything indented correctly
can you just screenshot the code in your IDE
can you show yout pip list
