#Basic Pycord Help (Quick Questions Only)
1 messages · Page 21 of 1
make it like a normal slash command
oof
if a group has any subcommands then the group can't be used as a command
hello. i get a error, but i do not know why. I'll appreciate if anyone tell me how to fix it!
code:
uhm
well first off, what's the full error
Ignoring exception in on_interaction
Traceback (most recent call last):
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\commands\core.py", line 127, in wrapped
ret = await coro(arg)
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\commands\core.py", line 1201, in _invoke
await command.invoke(ctx)
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\commands\core.py", line 356, in invoke
await self.prepare(ctx)
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\commands\core.py", line 278, in prepare
if not await self.can_run(ctx):
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\commands\core.py", line 373, in can_run
local_check = cog._get_overridden_method(cog.cog_check)
AttributeError: '_MissingSentinel' object has no attribute '_get_overridden_method'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\bot.py", line 1009, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\commands\core.py", line 359, in invoke
await injected(ctx)
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\commands\core.py", line 135, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: '_MissingSentinel' object has no attribute '_get_overridden_method'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\bot.py", line 1058, in on_interaction
await self.process_application_commands(interaction)
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\bot.py", line 756, in process_application_commands
await self.invoke_application_command(ctx)
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\bot.py", line 1013, in invoke_application_command
await ctx.command.dispatch_error(ctx, exc)
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\commands\core.py", line 401, in dispatch_error
local = cog.__class__._get_overridden_method(cog.cog_command_error)
AttributeError: type object '_MissingSentinel' has no attribute '_get_overridden_method'
Ignoring exception in command casoinfo hire:
Traceback (most recent call last):
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\commands\core.py", line 127, in wrapped
ret = await coro(arg)
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\commands\core.py", line 1201, in _invoke
await command.invoke(ctx)
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\commands\core.py", line 356, in invoke
await self.prepare(ctx)
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\commands\core.py", line 278, in prepare
if not await self.can_run(ctx):
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\commands\core.py", line 373, in can_run
local_check = cog._get_overridden_method(cog.cog_check)
AttributeError: '_MissingSentinel' object has no attribute '_get_overridden_method'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\bot.py", line 1009, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\commands\core.py", line 359, in invoke
await injected(ctx)
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\commands\core.py", line 135, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: '_MissingSentinel' object has no attribute '_get_overridden_method'
pycord version?
2.1.1
holy I got the same error just rn
lmao
upgrade to 2.1.3
im trying to run a slashgroup outside a cog
if that still doesn't work, then downgrade to 2.0.1
Already, will do it later, i have to sleep
True, it's ==
@verbal gulch worked for you?
I didn't it yet, i don't have access to my pc right now
alr i will try running here
Alr
worked for me
on py-cord 2.0.1
@cyan quail thanks for the advice
allgood
Oh nice, ty
@cyan quail now im having issue with on_timeout in the views after changing the version
ah i guess self.message wasn't fully implemented back then
hm
how are you sending the view initially?
you could change it to view.interaction = await ctx.respond(...), then in the timeout do self.interaction.edit_original_message instead
ok I will check it out
working! tysm
all good
apparently an error is raised for default avatars when I use member.avatar.url with the error NoneType has no attribute 'url'
how would i get the default avatar url ?
display_avatar.url
is there a way to execute a function certain times in a day?
like i want to execute a function in every hour of the day, is that possible?
automatically ofc
tasks
thanks
No tag install-replit found.
?tag replit
Read this to find out how you can install Pycord in replit - https://namantech.me/pycord/installation/#replit
if you have a replit.nix after showing hidden files then don’t do the above but instead use the one below
?tag replit-install
Follow instructions from: #998272089343668364 message
?tag message-content
As of Pycord Beta 5, Discord API v10 requires message content intent to receive message content. This affects the traditional commands. Not enabling this intent will result in the messages' content, embeds, and components being empty.
You will need to enable the intent on the developer portal, as well as in your code:
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(intents=intents)
Docs: https://docs.pycord.dev/en/master/api.html#discord.Intents.message_content
has it ever worked?
No but it works with my other projects
.
are we referring to message-based commands or application commands?
Message based commands
are there any errors?
clearly not lulw
No
did you override the on_message event?
could you show your code
No.. it's something personal 👀
ok so why ask for help
btw
Tnx for help
Yeah yeah ...
yw
Is there a more efficient way to update a value for all the users in the database at the same time instead of using for loops?
e.g: I want to set the pickaxe value as 30 for all the users at once
instead of doing:
for id in users['data']:
users['data'][id]['pickaxes'] = 30
Hey so I'm making a bot to host event that will have to give up to 300 member certain role, does pycord automaticly have anti rate limit or do I have to implement myself
Cuz rn testing it takes a while so I'm assuming it does but I don't want anything wrong to go at event
What db
then probably not lol
Then for loop should be able to upload your json pretty easily
thx for the advice
Mongo DB got a rate limit?
Oh?
Never have ran into ratelimits on self host. I doubt they exist maybe for cloud hosting when they host but I would assume they are fairly high
the cloud one has the rate limit
Is there a message submission box that can appear under a message or am I imagining things? I thought I saw it was a feature somewhere but I might be confusing it for select menus
yeah they don't exist
How to send message like
?tag timestamp
No tag timestamp found.
?tags timestamp
Timestamps
?tag Timestamps
To make a timestamp you need a unix timestamp. Then, put your time and date into the converter and copy the "Unix Timestamp" (https://www.unixtimestamp.com/) Then to use the timestamp, follow this syntax: <t:COPIED_TIMESTAMP_HERE:FORMAT>
Where it says FORMAT, you can put a few different things:
R: Relative, says "two weeks ago", or "in 5 years"
D: Date, says "July 4, 2021"
T: Time, "11:28:27 AM"
F: Full, "Monday, July 4, 2021 11:28:27 AM"
Example: (note: 1000190514 is Unix time for 11 September 2001)
<t:1000190514:R> -> says 20 years ago
<t:1000190514:D> -> says 11 September 2001
<t:1000190514:T> -> says 12:11:54
<t:1000190514:F> -> says Tuesday, 11 September 2001 12:11
Epoch and unix timestamp converter for developers. Date and time function syntax reference for various programming languages.
@hybrid raft
thx
can anyone help me with this? when i try to run it, comes back with NameError: name 'bot' is not defined
from discord.ext import commands
import discord
from utils.utils import *
from utils.data import Data
class Admin(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.data = Data()
@commands.Cog.listener()
async def on_ready(self):
# bot startup tasks
await logEvent("Bot has finished rebooting.", self.bot)
activity = discord.Game(name=f"Crush Them All! | r.help")
await self.bot.change_presence(activity=activity)
@bot.slash_command(guild_ids=[749087266491727933])
async def purge(self, ctx, num_messages: int):
# purge n messages from current channel
if await isMod(ctx):
channel = ctx.message.channel
def check(msg):
return not msg.pinned
try:
await ctx.message.delete()
await channel.purge(limit=num_messages, check=check, before=None)
except:
pass
await logUsage(f"Purged {num_messages} messages in #{ctx.message.channel.name}, requested by @{ctx.author.name}.", self.bot) ```
On which line? I didn't notice anything wrong so far.
Anyways, you can color the code on Discord by adding " py" at the beginning.
do you want me to copy the whole error message?
Yes, at least the part saying the line.
File "C:\Users\aonap\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\cog.py", line 731, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "C:\Users\aonap\Downloads\raider-bot-main (1)\raider-bot-main\cogs\admin.py", line 8, in <module>
class Admin(commands.Cog):
File "C:\Users\aonap\Downloads\raider-bot-main (1)\raider-bot-main\cogs\admin.py", line 26, in Admin
@bot.slash_command(guild_ids=[749087266491727933])
NameError: name 'bot' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\aonap\Downloads\raider-bot-main (1)\raider-bot-main\bot.py", line 25, in <module>
loadCogs()
File "C:\Users\aonap\Downloads\raider-bot-main (1)\raider-bot-main\bot.py", line 21, in loadCogs
bot.load_extension(f"cogs.{name}")
File "C:\Users\aonap\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\cog.py", line 867, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\aonap\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\cog.py", line 734, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.admin' raised an error: NameError: name 'bot' is not defined```
Do you have other cogs? Do they work?
i do, let me see
Maybe there is a mistake at the end of the cog. Did you add the setup() method?
You need to add this after the cog class, outside of it.
def setup(client):
client.add_cog(Admin(client))
Use "client" or "bot" depending on how you declared it in your main file.
Actually, maybe you already have it, otherwise you wouldn't get this error.
Anyways, make sure everything is fine for the cog.
this bot has been working for over a year, just trying to change from r. prefix to slash commands
class Admin(commands.Cog):
def setup(bot):
bot.add_cog(Admin(bot))```
this is what you meant, correct?
if so, i still get the same message when i run it
No, it has to be outside (same intendation as the first line) at the end of the file.
ok ty, sorry i usually do this w a friend and she knows a lot more than i do w this
yea it is at the end
was already there, didnt see it
I've found the error. The decorator you are using is wrong.
You need @discord.slash_command, not @bot.slash_command.
thanks! now i guess i have to change my commands to all lowercase
now there is a new problem, it loaded the cog but then said 'NoneType' object has no attribute 'send'
Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\aonap\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "C:\Users\aonap\Downloads\raider-bot-main (1)\raider-bot-main\cogs\admin.py", line 20, in on_ready
await logEvent("Bot has finished rebooting.", self.bot)
File "C:\Users\aonap\Downloads\raider-bot-main (1)\raider-bot-main\utils\utils.py", line 129, in logEvent
await channel.send(embed=embed)
AttributeError: 'NoneType' object has no attribute 'send'```
ill figure it out no worries, probably just because im using a test version of the bot
json is not a db
Ik that, I use json files to store my data
hey guys how do i connect to a secure lavalink connection with wss and not ws with wavelink, i have tried putting https parameter to true but i am still unable to connect to my lavalink with wss connection
how can i make it so context menu commands are made only for bot's profile and not for any other member ?
so like, they will only appear if the user right click on the bot and won't appear on other right clicking other users
anyone know how to make this work? trying to edit the commands' embed from a button clickpy i = 0 async def left_callback(interaction): i -= 1 if i < 0: i = len(pages) - 1 await message.edit(embed=pages[i]) left.callback = left_callback async def right_callback(interaction): i += 1 if i > len(pages) - 1: i = 0 await message.edit(embed=pages[i]) right.callback = right_callback
You probably need to use interaction.response.edit_message() instead.
didnt fix it
here ill send more
@discord.slash_command(guild_ids=[749087266491727933])
async def help(self, ctx):
# help command
await logUsage(f"Help command requested by @{ctx.author.name}.", self.bot)
left = Button(label="<<Previous", style=discord.ButtonStyle.primary)
right = Button(label="Next>>", style=discord.ButtonStyle.primary)
view = View()
view.add_item(left)
view.add_item(right)
pages = [self.makeGeneralHelpEmbed(), self.makeRecruitHelpEmbed(), self.makeModHelpEmbed()]
interaction = await ctx.respond(embed = pages[0], view=view, ephemeral = True)
message = await interaction.original_message()
i = 0
async def left_callback(interaction):
i -= 1
if i < 0:
i = len(pages) - 1
await interaction.response.edit_message(embed=pages[i])
left.callback = left_callback
async def right_callback(interaction):
i += 1
if i > len(pages) - 1:
i = 0
await interaction.response.edit_message(embed=pages[i])
right.callback = right_callback```
error message UnboundLocalError: local variable 'i' referenced before assignment
Make sure the indentation is correct.
Check the guide for help about buttons.
Link: https://guide.pycord.dev/interactions/ui-components/buttons
Learn all about implementing buttons in your Discord Bot using Pycord.
and u shouldnt
ik that too, rn im learning how to implement mongo db

even mongodb isn't that great, use sqlite instead; you can save everything in a dict format (ie, like json) there too if you so wish and it is much more simple to use
Why mongo isn't great lmao. It's just another db type
i dont think thats my issue, has something to do with the i = 0 then saying i -= 1 later, not sure how to reword it to make it work
cope however you want my friend. mongodb is not a db that anyone with a sense of scale would use and it is not very practical for data with relations. and on top of that, it is easier to corrupt data. there is literally no reason to choose it over mysql or sqlite. don't even get me started on the performance...
if interaction.author == x:
#do stuff
else:
#not correct person
is there any way to fill in the command promt generated by input() from outer scope?
i got it, thanks 
Kk
Also I think it would be interaction.user or .member
Not author
Wdym
external code is using input() or simething similar to get something from the user, but I wanna work around it since my application isn't using the console
Here's the basic voice example.
External code as in what? Like you made or found something that you want to use in your bot but it requires an input()
not for my bot, but yeah, a package I'm using
So you want to get an input from a bot to use in the console?
I don’t think you can do that
I could be wrong, you’d have to edit the library or something
to be more specific, I am using boto3 and am trying to insert the MFA token needed to edit resources from an outer scope
How do you get the ID of a slash command? I want to use it to display the command as </command:123> but cannot find anywhere how to get the ID or how to mention the command.
Sorry, is this in relation to pycord? I would say try asking in the python discord server or waiting for someone smarter than me to answer here
I just don’t really understand what your entirely trying to do
yeah I also asked there, the chance of actually getting an answer is just a lot higher when asking at multiple places
on the UI or by the api? if it's from the api it's command.mention, and on the UI you need to right click the command name after selecting it
How can i connect bot to voice channel
channel.connect()
https://docs.pycord.dev/en/master/api.html#discord.VoiceChannel.connect
Here's the basic voice example.
How did you write /command like that? 
Was wondering the same
Never seen that before
</command:ID>
You can only get a command ID from pc I’m pretty sure
</you can actually:9274> </put anything there:193847> </with random ids:92479>
</test:187>
Thank you! Don't know how I missed the command.mention in the docs lol
</hi:234243>
</words:123>
That's cool! I'll use it for my bot, in the messages where I mention commands. 
How can I get the ID automatically? I don't understand what "from the API" means. 
by the api meaning by the library
are you getting the id of the current command being ran? or other commands
I can't find command.mention in the docs. Sometimes I need it for the same, sometimes for another.
https://docs.pycord.dev/en/master/api.html#discord.SlashCommand.mention potentially broken for subcommands though
for the current command, it'd be ctx.command.mention
for other commands, you can either iterate through bot.walk_application_commands() to get all command objects, or use bot.get_application_command to get a specific command by name
Thank you! I'll try using the name then.
For other commands, I can only get ApplicationCommand objects, that don't have the mention attribute. 
? it'll return SlashCommand, not ApplicationCommand
ApplicationCommand is a generic type that SlashCommand inherits from
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'mention'
How can I edit a channel's name ?
Yes, I wrote "group_name command_name" to find the channel. Not possible? 
well it is but subcommands are a bit different
I already saw that and added
await discord.TextChannel.edit(1015850484545892352, name= f'{len(client.guilds)} Servers')
but it isn't working, it gives the error
AttributeError: 'int' object has no attribute '_edit'
not discord.TextChannel, you get the channel object with client.get_channel
I was wondering if I was doing something wrong. For subcommands it returns something like </command subcommand:None>. I guess it doesn't work then?
it's broken at the moment, but you can modify it slightly to create the mention itself
basically you need </group_name subcommand_name:group_id>
because subcommands don't have IDs which was overlooked when adding mention
So I should get a mention of the group, then get the ID from that mention and insert it in place of None?
is there some kind of "on_click_button"?
Now,
await client.get_channel(discord.ChannelType.text, 1015850484545892352, name= f'{len(client.guilds)} Servers')
TypeError: Client.get_channel() got an unexpected keyword argument 'name'```
it'd just be easier to form it yourself entirely py group_name = "..." command_name = "..." # just for example group = bot.get_application_command(group_name, type=discord.SlashCommandGroup) mention = f"</{group_name} {command_name}:{group.id}>"
or something along those lines
i think you've misunderstood get_channel and edit
get_channel only takes the channel id, i.e. client.get_channel(id)
then you use .edit on that object
Alright, ty, it works now
allgood
is there some kind of "on_click_button"?
there's on_interaction but it's recommended you don't use this, instead you should use button callbacks

Here's the button roles example.
maybe there should be a simpler button example... oh well
Here's the confirm example.
should be the easiest
wow that's such a descriptive name
wanna make a pr to fix it?
hmmmmmmmm
i wonder if dropdown should also be renamed since it's never referred to as such in the docs
that sounds like a fair pr
i guess the example itself uses Dropdown for the class names but hmm
Yep, that works. It's interesting, there isn't an id attribute in https://docs.pycord.dev/en/master/api.html#slashcommandgroup but it works anyway. Unless it's a different kind of group...
@commands.on_interaction()
async def on_interaction(self, interaction):
print(1)
how to do it correctly in cogs?
the correct decorator is @commands.Cog.listener()
why do you need an event for it?
thanks
also discord.Cog.listener
oh true
is there a way to make this work without global variable?
fwiw pagination is a built in feature but uhhh
add a variable to the view itself
like view.page = 0
How can I mak my bot see if the dm of someone is closed
then refer to view.page instead of i
ill try that out
try send an empty message and see what kind of error is caught
if it errors with discord.Forbidden, their DMs are off
Thank you very much! I made this function based on what you shared and it's working for both cases.
def get_command_mention(command_name: str, group_name: str = None):
if group_name is not None:
group = self.client.get_application_command(group_name, type = discord.SlashCommandGroup)
command_mention = f"</{group_name} {command_name}:{group.id}>"
else:
command = self.client.get_application_command(command_name, type = discord.SlashCommand)
command_mention = command.mention
return command_mention
but if it's discord.HTTPException, their DMs are on
what about can_send
that's an internal function that checks the message content itself
ic
seems like its working tyvm @cyan quail
all good
@cyan quail why can't we make a PR with something like this to fix the command mention not working for ground?
i keep meaning to but i keep forgetting lol
i think it was discussed in #discussion over how it should be implemented
between qualified_id to return the root id or for some other logic
I saw.
maybe i'll give it a go now but groups are supposedly part broken on 2.1.3 so not sure if i can even test
apparently it is fixed
there was a fix on 2.1.3, but some threads popped up suggesting it was still broken in some scenarios
#discussion message
Is there a way to avoid this?
when you do slash, click on the bot icon and select the command
You know how in slash commands, we can restrict guild_ids to a certain guild, can we manipulate the guild_ids so that if I use a command it'll add in a guild ID and get registered or do I need to do something like cogs (it's just that with cogs, I don't rlly get them so I choose to not implement them)
any one knows how to use the $set properly in MongoDB? smh im doing it wrong but I dont understand how
Bro im freaking blind, messed up putting a comma there
it should be like this: {"name" : "Bot"}
Is there any way to get a webhook link through the bot?
I was thinking more about something for users. Anyways, it didn't take more than 10 seconds so it's not a real problem.
I would like my bot to send a message when a schedule event is over, can I detect that with on_scheduled_event_update?
get a channel with bot.get_channel then use channel.send
I presume no one knows if this is possible without cogs? If cogs allow that to happen
pretty sure guild_ids only works before the bot connects
don't think it can be modified while the bot is online
If you don't want to use cogs, I think your only alternative is to save the updated guild_ids in a file and then force the bot to restart itself.
After restarting it, if you implement it correctly, the command will be loaded again by using the new guild_ids from the file, rather than the default one.
cogs solve that problem?
the guild_ids
By using cogs, you can restart the cog instead of restarting the whole bot. I don't think you gain anything else from it.
I see, I'll see what I can do, probably will see some yt vids since they're pretty helpful. thank you though!
You need this in your main file:
# Load all cogs.
for file in os.listdir("./cogs"):
if file.endswith(".py"):
client.load_extension(f"cogs.{file[:-3]}")
And then you write your cog like this:
import discord
from discord.ext import commands
class Artwork(commands.Cog):
def __init__(
self,
client: commands.Bot
):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
print("Artwork module loaded.")
@discord.slash_command(
name = "artwork",
description = "Get a random artwork. Cooldown: 1 minute, per server."
)
@commands.cooldown(1, 60, commands.BucketType.guild)
async def random_artwork(
self,
context: discord.ApplicationContext
):
# What you want to do.
def setup(client):
client.add_cog(Artwork(client))
As always, you can use "bot" instead of "client".
my_pages = [
Page(embeds=[discord.Embed(description='first page')]),
Page(embeds=[discord.Embed(description='second page')])]
how do i set a thumbnail for these embeds?
like where do i even type embed.set_footer()?
just define the embeds beforehand
will I be able to pass in other args in the __init__() instead of only self, client?
i guess you can change .set_footer() etc. on the end but make sure it doesn't become unreadable
oh I didn't see that lmao maybe I'll see
Any idea why new_event = await bot.Guild.create_scheduled_event( don't do anything (no error message, no event created)?
let's say you print on the line after, does that run?
No it doesn't
sounds like a ratelimit but let's see
can you implement logging real quick https://docs.pycord.dev/en/stable/logging.html
then try to use it
Thanks will look into it
I get a discord.client:Dispatching event application_command_error without much more details
what's your full command code?
...and i didn't see this before, but why bot.Guild?
yeah idk why you did bot.Guild
it's just Guild
thanks, I'll try this
🤦♂️ it worked
Thanks a lot for your patience ...
ok
Is there a way I can have a method invoked before interaction with the bot
An intearction being a slash command or button clicked, etc
on_interaction event
what am I doing wrong?
TypeError: Loop.__init__() missing 7 required positional arguments: 'coro', 'seconds', 'hours', 'minutes', 'count', 'reconnect', and 'loop'
lowercase loop
Hey I'm wondering why I'm getting this error
https://discord.com/channels/881207955029110855/1016235836427210802
And no one has responded to my thread for 2 weeks
Probably because no one knows. Try using Google as there's a 99% chance you find an answer.
Google does not have an answer
(Looking at the comments, and looks like the thread died)
Hey there, I was trying to use buttons in my bot but then I got this error
Heres my code:
key =
TOKEN =
bot = discord.Bot(debug_guilds= )
class ReportGuide(discord.ui.View):
@discord.ui.button(label="Next Section",style=discord.ButtonStyle.primary,emoji="▶️")
async def button_callback(self, button, interaction):
await interaction.response.send_message('')
@bot.slash_command(description='')
async def academy(ctx, ign: discord.Option(str)):
uuid = rq.get(f"https://api.mojang.com/user/profile/agent/minecraft/name/{ign}").json()
weight = rq.get(f"https://hypixel-api.senither.com/v1/profiles/{uuid['id']}/we?key={key}").json()
if round(weight['data']['weight']) >= 700:
embed = discord.Embed(title="",description="",color=discord.Color.blue())
embed.add_field(name="",inline=False)
embed.add_field(name="",value="",inline=False)
embed.set_footer(text='')
await ctx.respond(embed=embed, view=ReportGuide)
bot.run(TOKEN)
you didn't initialize the view ()
hey
im super confused on one thing
basically im trying to make select menu role selector, but im super confused how i would make this a persistent view
i know how to make persistent views just am confused about this situation
Works the same as any other view
Here's the persistent example.
How do you change the author name on a message the bot is sending
@bot.event
async def on_interaction(interaction):
print(type(interaction))
This works, and it prints when I use a slash command, but it stops there.
The command itself does not respond
does pycord has automatic handling for spliting embeds in case the max char limit exceeds?
@discord.slash_command()
@commands.cooldown(5, 30, commands.BucketType.user)
async def givetreat(self, ctx, member: discord.Member):
# gives a cookie to a user
try:
cookieData = self.data.getCookies()
if not str(member.id) in cookieData:
cookieData[str(member.id)] = 1
else:
cookieData[str(member.id)] += 1
self.data.updateCookies(cookieData)
cookie = await self.data.getCookiePicture()
embed = discord.Embed(
description=f"{ctx.author.mention} gave a treat to {member.mention}!" \
f"\n{member.mention} now has {cookieData[str(member.id)]} treats. " \
f"Check your treat count with `r.treatstats`."
)
embed.set_image(url=cookie["link"])
generalData = self.data.getGeneral()
embed.set_footer(text=generalData["footer"], icon_url=self.bot.user.avatar.url)
await ctx.send(embed=embed)
await logUsage(f"@{ctx.author.name} gave a treat to @{member.name}.", self.bot)
except Exception as e:
await handleException(e, self.bot)
@discord.Bot.event
async def on_application_command_error(self, ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.respond(error)
else:
raise error```
getting missing positional arg coro
I don't think so. I recommend using something like textwrap- it's really simple.
Example:
import textwrap
list_of_contents = textwrap.wrap(yourmsgcontent, 4000, break_long_words=False, replace_whitespace=False)```
I think you're looking for webhooks
when you are overriding on_interaction you need to await bot.process_application_commands(interaction)
Thanks
Also is there a reason why when I click a button its not getting picked up in on_interaction
@bot.check
async def on_interaction(interaction: Interaction) -> bool:
print('here')
return True
@bot.slash_command(name="test_command", guild_ids=[constants.TESTING_SERVER_ID])
async def test_command(ctx):
async def callback_func(interaction: Interaction): await interaction.response.defer()
view = discord.ui.View()
but = discord.ui.Button(label="test")
but.callback = callback_func
view.add_item(but)
await ctx.respond(view=view, content="start")
i fixed it
thanks though! just had to change @blank.event to commands.cog.listener()
cool
this has 100% been answered somewhere, but how do i go about making the message sent from a slash command private?
as the author is the only one who can view it
~~I can't get to make the voice registration work. I get this error when using the stop command.
raise MP3SinkError("ffmpeg was not found.") from None
discord.sinks.errors.MP3SinkError: ffmpeg was not found.
I'm using the code that's in the example linked in the guide, but adapted to be in a cog.~~
Problem solved! 
Hey guys! How do I make a command require the user to have administrator permissions?
put something like this @discord.default_permissions(administrator=True,) right above the function definition
or wait it might be @commands.has_permissions(administrator=True)
Do I apply it like this?
yeah, id recommend testing it though lol
yeah, you are going about perms incorrectly
also my internet is too bad to post the errors
guys can you join my thread when i create it'
Try @discord.ext.commands.has_permissions(administrator=True) instead.
@has_permissions() below @bot.commands
I am in the process of making a discord bot using discord.py and asyncio. The bot has commands like kick and ban which obviously should not be available to normal users.
I want to make a simple sy...
You can do that way if you import the rest.
This is the pycord server not discord.py
aware
Permissions are pre 2.0, so they work the same way because Pycord is basically a fork of Discord.py.
but pycord was made to match very simular
i transfered from d.py to pycord personally smooth transition
Same, I only had to fix the part about Slash Commands because they are new and I was using a third library for them.
yeah, i ran a bot with 100+ servers so i was forced to change to slash
happy it works atleast. and now i get to play with buttons and pages
Could be a very simple answer, but i'm not grasping it at the moment,
Why am I getting this
AttributeError: 'SlashCommandGroup' object has no attribute '_callback'. Did you mean: 'callback'?
discord/commands/core.py lines 240 to 247
@property
def callback(
self,
) -> Union[
Callable[Concatenate[CogT, ApplicationContext, P], Coro[T]],
Callable[Concatenate[ApplicationContext, P], Coro[T]],
]:
return self._callback```
whats the context?
Traceback (most recent call last):
File "/home/ken/PycharmProjects/ticket_man/venv/lib/python3.10/site-packages/discord/cog.py", line 731, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/home/ken/PycharmProjects/ticket_man/ticket_man/bot/cogs/tickets.py", line 16, in <module>
class Tickets(Cog, command_attrs=dict(hidden=True)):
File "/home/ken/PycharmProjects/ticket_man/venv/lib/python3.10/site-packages/discord/cog.py", line 238, in __new__
new_cls.__cog_commands__ = tuple(c._update_copy(cmd_attrs) for c in new_cls.__cog_commands__) # type: ignore
File "/home/ken/PycharmProjects/ticket_man/venv/lib/python3.10/site-packages/discord/cog.py", line 238, in <genexpr>
new_cls.__cog_commands__ = tuple(c._update_copy(cmd_attrs) for c in new_cls.__cog_commands__) # type: ignore
File "/home/ken/PycharmProjects/ticket_man/venv/lib/python3.10/site-packages/discord/commands/core.py", line 1259, in _update_copy
copy = self.__class__(self.callback, **kw)
File "/home/ken/PycharmProjects/ticket_man/venv/lib/python3.10/site-packages/discord/commands/core.py", line 247, in callback
return self._callback
AttributeError: 'SlashCommandGroup' object has no attribute '_callback'. Did you mean: 'callback'?
Same, but I wasn't forced to switch. I already had Buttons and I made pages by myself. Now they also work in Threads and I'm exploring new features, like voice recording. The switch was also meant to be a learning experience, so I get to practice fixing code.
Could someone explain to me why my scheduled event supposed to start now (datetime.datetime.now()) are set to start one hour later when created in discord?
Here's an extract from the debug log: DEBUG:discord.gateway:For Shard ID None: WebSocket Event: {'t': 'GUILD_SCHEDULED_EVENT_DELETE', 's': 8, 'op': 0, 'd': {'status': 1, 'sku_ids': [], 'scheduled_start_time': '2022-09-16T12:41:19.616000+00:00', 'scheduled_end_time': '2022-09-16T13:00:00+00:00', 'privacy_level': 2, 'name': 'Test', 'image': None, 'id': '1020298336852520990', 'guild_id': '697837117643948082', 'entity_type': 3, 'entity_metadata': {'location': 'competition'}, 'entity_id': None, 'description': 'This is a test', 'creator_id': '1019326256677929051', 'channel_id': None}}
anyine could check #general ? 💀
how come discord says 265kb is the maximum role icon size, but when i try uploading something thats 285kb it still goes through? is it doing some compression/conversion in the back?
hows that related to pycord?
ah youre right sorry
it surprised me so i wasnt thinking
Or actually use the support channels
hm good idea
can someone help me?
@option(
"role",
description="Enter your role id",
min_value=1,
max_value=99,
# Passing the default value makes an argument optional.
# You also can create optional arguments using:
# age: Option(int, "Enter your age") = 18
)
@option(
"logschannel",
description="Enter your logs channel id",
min_value=1,
max_value=99,
# Passing the default value makes an argument optional.
# You also can create optional arguments using:
# age: Option(int, "Enter your age") = 18
)
async def setup(
ctx: discord.ApplicationContext,
status: str,
logschannel: int,
role: int,
):```
ctx: discord.ApplicationContext,
status: str,
logschannel: int,
role: int,
):```
I'm pretty sure 1019983696... is higher than 99
But taking an int won't work either way. Take a string and then convert it.
im not sure how many people care about the answer but apparently you can get 2MB max, so 2097152 bytes, despite the apparent role icon limit 
Am I doing something wrong?
10 seconds have passed but it dont print it...
seems like tasks is not looping every 10 secs
did you start the task
Can I lock a button/menu only to the owner?
no, you'd have to check inside the callback
alright!
That’s why I like aiocron vs ext.tasks. I can just define it once (although in __init__; for some reason aiocron decorators won’t work in cogs)
someone have the documentation on hand for how this is done?
oh
rip, cool feature tho
how would i add a description to the options provided (if possible)
like "nardoragon" - by xyz
would i have to do something different in the options area?
it's not possible https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-choice-structure
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
It's possible using OptionChoice
You just have to process it differently
Documentation on this?
Thank you
Name is what shows on the ui, while value is a hidden value
So let's say you do choices = [OptionChoice(name=, value=), ...], you'd access product.value and then name can be whatever you want
command to install discord buttons?
Here's the confirm example.
normal buttons
cuz i have error: ModuleNotFoundError: No module named 'discord.ext.buttons'
Cause Buttons are part of discord.ui
yea i fixed it but now the error is: ModuleNotFoundError: No module named 'utils.json_loader'
Then no such module exists lol
oh shit, thats so sick. thank you very much! this is exactly what i wanted :D
thanks again
If I can ask - Referring to the above example, could one change the Choices text later, or would that require a re-registration? Like I know autocomplete can build and return, but are static Choices re-fetched each time?
you'd have to restart the bot
(maybe reloading the command would work? can't confirm)
So just be aware of that, @naive steppe. You may want to turn that into an autocomplete if you intend on making the list dynamic over time
What do you mean by this? @gleaming falcon
You can’t change choices after the bot starts. So if you wanted to add another “rank”/“store id” (your naming convention is a little confusing), you’d have to re-register the command.
In contrast, if you maintained a list externally and used an autocomplete to reference it, you should be able to make changes to the list
If you’re certain you won’t need to adjust anything over time, then of course my suggestion is useless.
Oh shit
Here's the slash autocomplete example.
Like have the list check a github repo each time its ran? And grabs any new ones
Nvm just looked at the .py
I would do it on a task to keep internally rather than on demand, but yes.
Ok thats sick
Yeah, hard code is yucky and i have not actually touched this method
Super useful
Thank you
Also threading is like in C# right? Where you can assign a task or function to a thread and still run the command without waiting for the result of said func
I may need to touch up on threads ;-;
yeah
Does the function that is creating an embed have to be asynced and awaited to it work? Cuz im not getting anything when I print the embed object
Embed is an object. So if u print it out, u won't get the actual results. There probably should be a to_dict method somewhere, which possibly u could print it out that way
yeah ik, but when we print a embed we should get a response like embed object or something right?
thats the thing, when I print I dont get anything
its just blank
it should irc
Does restarting the bot reset every command's id?
nope
all commands will have the same ID assuming you didn't change their names or something
what if anything else is changed like description or parameters
i don't THINK that resets them but i can't confirm, hold on
if i have a command that i want to have a "shared cooldown" how would i go abouts it? for example someone runs /poop and i want there to be 30s inbetween the next person who uses it?
use the cooldown decorator https://docs.pycord.dev/en/master/ext/commands/api.html#discord.ext.commands.cooldown
just checked, changing description and parameters is completely safe
but the moment the name is changed, the ID and its previously overridden permissions are lost forever (even if you use the same name again)
Is there a way to make collections dont delete the info in the query after being readed?
PyMongo question ☝️
You can get them automatically, if you want, although it's not really needed. I do it that way because I have too many commands to mention.
Mongo doesn't delete the info?
what im trying to say is when I go thru its elements once, I cant go twice:
Why are you running two for loops when you can just run one and do the checks inside
its just for example, on the logic im trying to do is a for loop inside another for loop
Well, that doesn't look like a for loop in a for loop
for coin in findCurrencies outer loop
for image in findImages: inner loop
if image['_id'] == symbol:
link = f"{image[symbol]}"
Works for me anyways
it almost runs like twice
hmmm idk
Try wrapping it in a try except?
One message removed from a suspended account.
One message removed from a suspended account.
the way i declare findCurrencies and findImages is:
findCurrencies = currencyCollection.find({})
findImages = imageCollection.find({})
you gotta get the message first, discord.Message.reference.message_id will return the ID of the message the user replied to
Get it or fetch it, whatever it is. And tada you get a cool new message object
the thing is when the outer loop loops once, the inner loop acts like findImages is empty
Can you actually share your whole code
yeah lemme copy it
?tag paste
Heads up @fleet tusk!
We've deleted your bot's (TRADER#5603) token because you've accidentially shared it.
Please regenerate it at https://discord.com/developers/applications/1019988662093611019/bot to be safe
findCurrencies = currencyCollection.find({})
findImages = imageCollection.find({})
for coin in findCurrencies:
currency = coin['currency']
id = coin['_id']
embed = Embed(
title=f"example",
color=embedColor
)
link = "https://imgur.com/IjZ67ok.jpg"
for image in findImages:
if image['_id'] == symbol:
link = f"{image[symbol]}"
basically the for loop
Whole code I said
forgot the variable declaration
?tag paste
Please, help:
I want to write a bot for ds, please help.
I am using the pycord library.
I run the code:
import discord
class MyClient(discord.Client):
async def on_ready(self):
print(f'Logged on as {self.user}!')
async def on_message(self, message):
print(f'Message from {message.author}: {message.content}')
client = MyClient()
client.run('token')
And it gives me an error:
Traceback (most recent call last):
File "C:\Users\Latmi\Desktop\ds bot\bot.py", line 3, in <module>
class MyClient(discord.Client):
AttributeError: module 'discord' has no attribute 'Client'
the thing of for loops is in the imageList method
How can i fix it?
Show your pip freeze
Would you mind using the paste tool. I'm on mobile
oh sur
done, i just need to paste there right?
And share the link
You have discord 2.0.0
Should i download newer version?
I deleted it but it didn't help
Nothing looks wrong chief. I'd try using a try/except
Restart your editor
Uninstall py-cord and install it again
I will try do some funny stuff like saving the first for loop in a temp object
thanks for help
Oh, you right, thank a lot
read the error
Oh, sorry
One message removed from a suspended account.
message.mentions
for n in nateamids:
await player.remove_roles(ctx.guild.get_role(n))
is there a better way of doing this? my goal was to if the member had a role in a list, get rid of that one in specific but the method i have now is removing all of them (32 roles) which is taking about 1 minute
If role in user.roles?
oops sorry, if a member had one of the roles in the list
a role i wouldn't know beforehand
as the name implies, remove_roles lets you remove multiple roles at once
so instead you should make a list of roles and then expand it inside py roles = [ctx.guild.get_role(n) for n in natemids] await player.remove_roles(*roles)
it won't error or anything if the user doesn't have one of the roles either; it'll simply remove all possible roles from the list
oh ok, thank you!
im passing the list through a param
itnvmm im huge brain fart
Is there an attribute that lists the tags of a forum thread? I don't think there's one listed here: https://docs.pycord.dev/en/master/api.html?highlight=thread#discord.Thread

amazing, thanks for the reply 😄
how can i fetch every param
i need a list
for a for loop
like for param in idk_what_to_put
Could someone direct me to example code on how this is done?
Also, i have a button that calls a slash command, how do i go about feeding that slash variables while its made with "view=MyView()"
Do you mean the pages?
Pages?
Yes, the buttons to edit the embed.
Sorry if i dont understand, i was stuck on 1.7.3 because of d.py
I have no idea about any of the new features
Ok, ill look into the documentation
Ty for giving me the name
I'm not sure if you can do it that way by using Pages. I use a custom code for doing that.
Yeah, im currently using an array to store the params i need.
Only problem is if the command is called while someone is using it then it wipes the param list
Breaking the follow up
Do you really need to store it? Just read the custom_id of the button being pressed.
I think that by storing it you are only making it harder to implement.
Im currently not on pc, but ill try and explain what im trying to do
When i get on my pc
Say 20 mins, brb
For my help menu, I do it this way without using the Pages feature because I wrote the code before it was a thing.
- The slash command calls the method that creates the embed, without any page selected.
- The embed gets created, defaulting on the first page.
- The buttons are added right below the embed, by using a View.
- When clicked, the buttons call the same method that creates the embed, but this time with a page selected based on the
custom_idand an array that has the button names to use as a reference.
oh so its sorta like recursion
you are calling the same slash command just parsing a different set embed/array
(i hard coded the channel and what not for testing purposes
To change page, you have to edit the message instead of sending a new one.
You have to rely on interaction.response.edit_message() in your View.
ohh, that makes sense
and how would i got about passing context? if at all possible
Do you need context if you have interaction?
so i can interaction.author.id?
To see who clicked, you can use interaction.user.
You are welcome. Well done!
im really liking the new way discords doing buttons and such
feels a lot more creative
Now you can make the button of the active page be disabled.
You can enable them all and then disable the current one.
self.enable_all_items()
button.disabled = True
ok thanks, one last question before i stop bugging you
how do i make / set the default screen (this one)
since in order to call the slash i need to provide ctx, key, and product
how did you go about setting up the home one? since i think how im doing it is causing problems
(updated image)
From the slash command, I call craft_embed() without telling which page, defaulting to the first one.
From the buttons, I call craft_embed(page) instead.
I recommend creating a method to craft the embed, so you can call it twice as I did.
Did you import the embed as a EmbedBuilder?
i use maxembeds to create them, tho a method would cut it down
This is how I did it. It depends where you put the View in the code.
async def craft_embed(
self,
page: str = None
):
pages = ["Utility", "Draft", "Creative"]
if page is None:
page = pages[0]
ok im basically there
i have all 3 buttons working now its just, when called it doesn't produce an initial embed
You have to check if you are calling the function when needed.
How is the code for your slash command now?
works :D
tho i basically hard coded basic view in, which feels slimy. ill work on it tomorrow
Basic View should be disabled here because it's the current page, right?
oh yeah i forgot to implement the disable button
Just make a function to create the embed, so you don't repeat code.
My pleasure! I like to help and to solve problems. 
1 last thing
i have the disable in the def button, but the button doesnt get disabled?
To make it start with 1 button disabled, you have to disable it when creating the View.
To disable the button when clicked, you have to handle it on interaction.
If that's the callback you call when the button is clicked, yes.
You can make a function to call for every button callback.
A button gets clicked, the function gets called, check which button, change page.
ok i found my problem
in await interaction.response.edit_message()
i wasnt calling view again
so it wouldnt change
all i had to do was add view=self
sweet, well im going to call it at that, its 230am and ive had my fun :)
yesterday it worked with my slash command but now im getting an error: ImportError: cannot import name 'Option' from 'discord' idk what to do, I installed many shit but, yea nthing worked
yeah this shit happened to me
i deleted both discord.py and pycord, then re-installed pycord and restarted my ide
shit worked for me after
If you have multiple discord libraries
this error will come
can you show the pip list?
like discord.py, py-cord all together
I've a question can we use buttons and Select menus in ephemeral messages ??
try it and yes you can
how do i use bridge commands in a cog?
but if I uninstall discord.py then there comes another error
no wait
I uninstalled discord.py and there comes the same error
aiofiles==0.6.0
aiohttp==3.8.1
aiomysql==0.0.21
aiosignal==1.2.0
aiosqlite==0.17.0
altgraph==0.17
appdirs==1.4.4
asgiref==3.5.2
async==0.6.2
async-timeout==4.0.2
attrs==20.3.0
backports.entry-points-selectable==1.1.0
blinker==1.4
bottle==0.12.19
bottle-websocket==0.2.9
buttons==0.1.9
certifi==2020.12.5
cffi==1.14.5
chardet==4.0.0
charset-normalizer==2.1.1
click==7.1.2
clipboard==0.0.4
colorama==0.4.4
config==0.5.0.post0
dearpygui==0.8.64
discord-py-slash-command==4.2.1
distlib==0.3.3
django-model-utils==4.2.0
dnspython==2.1.0
docutils==0.17.1
Eel==0.12.4
filelock==3.3.0
frozenlist==1.3.1
future==0.18.2
gevent==21.1.2
gevent-websocket==0.10.1
gitdb==4.0.7
GitPython==3.1.18
greenlet==1.1.0
h11==0.12.0
h2==4.0.0
hpack==4.0.0
Hypercorn==0.11.2
hyperframe==6.0.1
idna==2.10
itsdangerous==2.0.1
Jinja2==3.0.1
kivy-deps.angle==0.3.0
kivy-deps.glew==0.3.0
kivy-deps.gstreamer==0.3.2
kivy-deps.sdl2==0.3.1
Kivy-examples==2.0.0
Kivy-Garden==0.1.4
MarkupSafe==2.0.1
MouseInfo==0.1.3
multidict==5.1.0
option==2.1.0
pefile==2021.5.24
Pillow==8.3.2
platformdirs==2.4.0
priority==1.3.0
py-cord==2.1.3
PyAutoGUI==0.9.53
pycparser==2.20
PyGetWindow==0.0.9
Pygments==2.9.0
pyinstaller==4.4
pyinstaller-hooks-contrib==2021.2
PyMsgBox==1.0.9
PyMySQL==0.9.3
PyNaCl==1.4.0
pyperclip==1.8.2
pypiwin32==223
PyRect==0.1.4
PyScreeze==0.1.27
PyTweening==1.0.3
pytz==2021.1
pywin32==301
pywin32-ctypes==0.2.0
Quart==0.14.1
requests==2.25.1
six==1.15.0
smmap==4.0.0
sqlparse==0.4.2
termcolor==1.1.0
toml==0.10.2
typing-extensions==3.7.4.3
tzdata==2022.2
uritools==3.0.2
urllib3==1.26.4
virtualenv==20.8.1
Werkzeug==2.0.1
whichcraft==0.6.1
wsproto==1.0.0
yarl==1.6.3
zope.event==4.5.0
zope.interface==5.4.0
ok
but now its not working, it shows a long error and says its ready but the slash command dont show up
no yesterday it worked but i can send you it
remove discord-py-slash-command==4.2.1
@bridge.bridge_command(description="....")
How can I use multiple button in one view... when I am making a View Class to make it persistent.....
like pages?
Im not sure if it works with a list like
view=[button1, button2]
kindaa
class GreenButton(View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(.......)
async def callback(self, button: discord.ui.button, interaction: discord.Interaction):
........
@discord.ui.button(.......)
async def callback(self, button: discord.ui.button, interaction: discord.Interaction):
........```
but it only shows the last button
Oh, just send the class?
yes
it only shows the last button not the first one
Rename 2nd to second_callback
mine
np
i guess i need some coffee 
how do I ignore messages from bots?
like, i dont want my bot saving other bots id in the data base
thanks
i get this error right here Exception has occurred: NameError
name 'intents' is not defined
File "C:\Users\doree\OneDrive\Documents\topg\main.py", line 8, in <module>
bot = discord.Bot(intents=intents)
this is the code
import os
import discord
import random
from discord import Intents
from discord.ext import commands
from discord.commands import Option
bot = discord.Bot(intents=intents)
token= ""
@Bot.slash_commands(description="echo a message")
async def echo(ctx, echo: Option(str, "Enter the message you want this bot to say!")):
await ctx.respond(echo)
@Bot.slash_commands(description="nuke a user")
async def nuke(ctx, user: Option(discord.User, "Enter the user you want to nuke!")):
responses = [f"nuking {user}!", "congrats you started world war 3", "looks like the commander didnt sign off your lucky! :,)", f"sorry, but {user} is part of nato", "gay midget porn"]
await ctx.respond(random.choice(responses))
@Bot.slash_commands(description="rob a user")
async def rob(ctx, user: Option(discord.User, "Enter the user you want to rob!")):
responses = [f"Robbing {user}!", "gun ran out of ammo your dead!", "looks like your dumb you tried to rob a cop😂 :,)", f"Sorry, but {user} is a old lady", "penis in my mouth"]
await ctx.respond(random.choice(responses))
class MyModal(discord.ui.Modal):
def init(self, args, **kwargs) -> None:
super().init(args, **kwargs)
self.add_item(discord.ui.InputText(label="type issue here", style=discord.InputTextStyle.long))
async def callback(self, interaction: discord.Interaction):
embed = discord.Embed(title="issue")
embed.add_field(name="Descrbe the issue", value=self.children[0].value)
await interaction.response.send_message(embeds=[embed])
@Bot.slash_commands(description="report an issue in the server")
async def issue(ctx: discord.ApplicationContext):
"""Report An Issue In The Server."""
modal = MyModal(title="Report A problem")
await ctx.send_modal(modal)
@Bot.event
async def on_ready():
print(f'Logged in')
bot.run(token)
Error is self explanatory, you never defined intents
@wooden zenith Please stop cross-posting.
still
but how do i define intents
choose either your thread or this thread
.
ok then please use /close in your other thread
Do you even know python
i never said I was going to help but i may
oh thanks
Because you're passing a non defined intents variable
You don't forget basics in 3-4 weeks.
i do
i only been coding for 6 weeks maybe
Just define intents above your bot instance
it's @bot.slash_command not @bot.slash_commands
no problem
Hello, anyone could help?
i have something like this:
c = await guild.create_text_channel(f"ticket-{ctx.author.name}")
and i want to do this:
await interaction.response.send_message(f"Successfully created a ticket. Check at {CHANNEL_MENTION?}", ephemeral=True)
(ping please)
c is your channel
And that is a channel object...
How it doesn't work
Can't help you then
c.mention
do people forget mention is an attribute not even sure if I'm mentioning its correct type whether an attribute or not
Can you say me please, why doesn't it work?
await message.author.edit(username="O")
Error:
TypeError: Member.edit() got an unexpected keyword argument 'username'
I saw documentation and in it written so
you can only edit a discord.Member's nick, not their username https://docs.pycord.dev/en/master/api.html#discord.Member.edit
Another question:
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
discord_id: str = message.author.id
await message.channel.send('Hello!')
await message.author.edit(nick="O")
I do all, but have error with permission, but my bot have admin permission
Traceback (most recent call last):
File "C:\Users\Latmi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Latmi\Desktop\ds bot\bot.py", line 26, in on_message
await message.author.edit(nick="O")
File "C:\Users\Latmi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\member.py", line 808, in edit
data = await http.edit_member(guild_id, self.id, reason=reason, **payload)
File "C:\Users\Latmi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 353, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
the bot's role should be above the author's top role
hierarchy moment
and the author cannot own the server
You want to say, that i should to give server to bot?
no, I'm simply saying that the bot cannot give a role to someone ranked higher than them
Really
bots can give a role ranked lower than the bot's highest role to a member having a role higher than the bot's highest role right?
no. if the user has any role higher than the bot, it will not work.
nvm I'm stupid
Humans can do it to other humans. just checked
why not bots then
sorry I meant to say that the role cannot be higher than the bot
Is there any way to check if a person is an admin or not without using roles?
Thanks
is there a limit of subcommands u can have
25
you can have 100 top-level, 25 subcommands and each of those can also have 25 commands each
ah ok ty
Image treatment for science
Hello guys !
I am a french biologist who is currently doing searches on ‘’the blob’’ a wacky cell endowed with intelligence. I you never have heard about it I really advice to have a look. I am studying the way it grows. For than I have some images (as you can see in the first one). I would like to transform all the non-yellow pixels (those that are not those of the blob) into black. Thus I will recover images with a mask of the shape of the blob.
If I lost you with my explanations. The expected result corresponds to the second photo. I first tried with Pillow by analyzing the r g b of the images but the result is not good. The result have to be as accurate as possible for the searches.
As I have already said, I am a biologist and not really an IT expert. Any help would be greatly appreciated and would in some way help scientific progress.
what image
those ones
ignore the message dyno sends. So because this is a server for creating discord bots, there probably aren't that many experts that use Pillow here. you can try in the Python discord server in the following message.
?tag python
its is very difficult to help you if you don't understand python first.
As it stands, you do not or cannot show that you understand the basic fundamentals of Python. Please continue to learn Python first, as pycord is a Python framework and as such requires that you have a confident grasp on these fundamentals . For now, pause your current project and when you have learned enough Python you can then pick it back up and continue where you left off (if at all possible).** You cannot drive a truck if you do not know how to drive at all.**
cool free resources are
w3school
freecodecamp.org
there are also a lot of python programming tutorials out there a youtube search will give a lot awesome content. If you need help with python there is a python server for that where they will be more that happy to help you with these thing, you can also ask for python help in #881309540639997952.
python server: https://discord.gg/python
https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#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 # Required for prefix commands!
...
# 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)
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Diff. Issue now :/
if i want to use slash command following error comes up: discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
?tag 403
No tag 403 found.
?tag forbidden
You get a 403 Forbidden (error code: 50001): Missing Access as error?
You might've added your bot in the past without the applications.commands scope.
What to do?
Old way: Re-add the bot with the applications.commands scope.
New way: Since 11/07/2022 discord automatically includes the applications.commands scope in OAuth. You just need to re-add the bot with the bot scope. See [#discord-api-updates@996103073111998544](#discord-api-updates message) for more infos.
basically re-invite your bot.
^
and it dont worked
Is there a way to sync the time I start a task with irl time?
for example I want to execute the task only when is 17pm and 18pm of the day
https://docs.pycord.dev/en/master/ext/tasks/#discord.ext.tasks.loop
instead of seconds or minutes etc, you should use time which is a list of datetime.time objects
Help please. I need a function that will generate a random number that will later be assigned to ticket. When creating a request, this id is generated.
import random
Does anybody know why my slash command is not registering arguments?
This is my method signature:
@levels.command(name="xp")
@option("xp", description="Amount of XP to give", min_value=1)
@option("user", description="The user to give XP to", default=None)
async def add_xp(self, ctx, xp: int, user: discord.Member = None):
try commenting out the command, running it, uncommenting and running it
To reregister it?
yes
I did so but the issue persists. This was happening before, but if I try to run the command with no arguments, it gives me this cryptic error:
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\bot.py", line 1009, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Python310\lib\site-packages\discord\commands\core.py", line 359, in invoke
await injected(ctx)
File "C:\Python310\lib\site-packages\discord\commands\core.py", line 135, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: '_MissingSentinel' object has no attribute '_get_overridden_method'
Not sure if that's helpful. I couldn't find any references to my code in the stack trace.
update
I tried to use that before, lemme just get the error brb
Okay, thanks
I'm on the latest version but the issue is still happening.
I think I've found the problem but it's not a Pycord issue, thanks for your help.
figured out that it was not the tasks, smh the logs that I got in the bot host were:
3Ignoring exception in on_application_command_error
#Traceback (most recent call last):
\ File "/usr/local/lib/python3.10/site-packages/discord/client.py", line 382, in _run_event
await coro(*args, **kwargs)
a File "/home/user_347498475031756802/cogs/Events.py", line 126, in on_application_command_error
3 await ctx.respond(embed=embed, ephemeral=True)
c File "/usr/local/lib/python3.10/site-packages/discord/commands/context.py", line 258, in respond
Z return await self.interaction.response.send_message(*args, **kwargs) # self.response
d File "/usr/local/lib/python3.10/site-packages/discord/interactions.py", line 712, in send_message
! await self._locked_response(
h File "/usr/local/lib/python3.10/site-packages/discord/interactions.py", line 959, in _locked_response
await coro
a File "/usr/local/lib/python3.10/site-packages/discord/webhook/async_.py", line 211, in request
# raise NotFound(response, data)
Pdiscord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
what is this error for btw
well
send in the code for tasks
yes
lemme check the task.loop args
there
your code there is fine, the error is unrelated
i made a command where i ahve multiple buttons when i do it i see all the buttons but when other people do it there is a button missing any idea on how to fix it?
What if you do it multiple times?
Quick Question. I made some minor updates to my bot, trying to increase its efficiency. I run two tokens, a production token which is hosted on the server and a test token which I use for development.
The most recent update works fine locally, but when I deployed it to the server, I am getting slash commands missing, although the bot is online.
I have the sever logs here: https://pastebin.pl/view/8490cd10
But, I am struggling to figure out where the error is.
Pastebin.pl is a website where you can store code/text online for a set period of time and share to anybody on earth
I am using the most recent version of pycord.
The error is : discord.errors.NotFound: 404 Not Found (error code: 0): 404: Not Found, but I am not getting much when I google it
what's the command for downloading py-cord and getting the lastest features?
python3 -m pip install -U py-cord --pre
gets me this files
(its lacking discord.commands)
py-cord==2.1.3
python3 -m pip install py-cord==2.1.3
or from git: python3 -m pip install git+https://github.com/Pycord-Development/pycord
if u want the latest dev version, install it from git
how do i go about making "cancel" delete the interaction?
to add as well, I hold the values entered in the initial /verify
only problem is if someone else calls the command before they lock it'll lock there value
i was thinking about writing a text doc that contains id and key temporarily and is deleted after any option is picked, but is there a better / more effective way to do this?
one way to approach it is to save the values to a database (eg to a SQLite or PostgreSQL db) instead of writing it to a text doc or a JSON file
it's always not a good idea to use a text doc or JSON files to store data
another way is to use redis, and to save a key-value pair as interaction.user.id:hold when u want to hold it before locking it (done when the cmd is executed). and then to cancel it, check the key-value pairs on redis to make sure if the current user's id is in there, and just delete that key-value pair. to lock it, what i would do is to update the key-value pair with the value being something like locked, and write it to a database from there
Hey guys! How do I make a bot have an "Idle"-type status instead of Online?
https://docs.pycord.dev/en/stable/api.html?highlight=discord bot#discord.Bot.change_presence
example:
await client.change_presence(status=discord.Status.idle)
Didn't work
?tag idw
Saying it doesn't work or asking what's wrong with this code? is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
should be this:
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, status=discord.Status.idle)
yeah but I want it to have the status
Listening to my clients.
as well as the idle type
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="Listening to my clients"), status=discord.Status.idle)
Thanks! Worked perfectly!
Well except for the Listening to my clients. bit
you have to get rid of "listening to"
the Listening status activity type does that for you
ah ok
Is there a way to remove the file preview
is there a way to make interactions like these pass on boot of the bot?
like i run the bot and make say a role menu
then the bot goes down for some unseen reason
is there a way to code it to re-instate that message without re-creating it
You can make the button persistent, so that it works even after restarting the bot.
oooo
Learn all about implementing Select Menus or Dropdowns in your Discord Bot with Pycord.
bless your soul
🙏
ok how do i delete the message / interaction on clicking "cancel"
how would that delete it?
the clear items was a temp, i want to delete the message as a whole
Try interaction.message.delete().
tried both, do i maybe have to feed the message id?
No. Code?
i just have no clue how to delete the interaction, cant set content or embed to none, cant call delete_message, ect
If I remember correctly, you cannot use it for ephemeral messages.
You should either make the message not ephemeral or get rid of the button to delete it.
fair
im still thinking of how to pass the key / product to the class myview
since storing it as temp data and deleting it on call only works for 1 button press, then it breaks the rest
and i dont want to store key values as its against my privacy policy
is there a way to call something after the message is 'canceled'
You can add it to the __init__() and then pass as a parameter.
For example, here I do that with client because I need it for a function.
class HelpView(discord.ui.View):
def __init__(self, client):
self.client = client
super().__init__(timeout = None)
SAVIOUR
🙏
how can i ask for extra info after the slash command is made
like if the slash command is done by a moderator and they have the ability to delete keys, ect
but they have to input a key that gives them auth
i was thinking having 3 buttons disabled (disable key, delete key, unlink key) untill the moderator key is provided
is there some kind of textbox with submit field?
You can ask them to use another Slash Command to insert the data or use a Modal to receive it as input.
how can i get user discord language?
whats your play method / command?
Hello there, help please with bot.
I try to add modal, but nothik work, help please. I realy dont't know what i should do:
https://paste.helpch.at/rogarujiye.scss
Error:
await item.callback(interaction)
File "C:\Users\Latmi\Desktop\ds bot\bot.py", line 46, in button_callback
await interaction.response.send_modal(modal)
File "C:\Users\Latmi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 939, in send_modal
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
no its a prefix command like "!play"
you can only have one response
Code: ``` f2 = open("temp/tempembed.json", "r")
s = json.loads(f2.read())
embed = discord.Embed().from_dict(s)
try:
data = {
"content": messages["message_content"],
"username": messages["message_author_name"],
"avatar_url": messages["message_author_avatar"],
"embed": embed
}
send = requests.post(webhookurl, data=data)```
Error: 'Embed' object is not iterable
JSON: {"footer": {"text": "Use `!help [command]` for more info on a command."}, "color": 4689870, "type": "rich", "description": "testing"}
Anyone has an idea?
?tag WinError 3
No tag WinError found.
?tag WinError3
No tag WinError3 found.
?
my code dont find the cogs folder
did you change the name or its not anymore in the same folder?
its in the same folder and the name of the folder is: "cogs"
if __name__ == "__main__":
for file in os.listdir("./cogs"):
if file.endswith(".py"):
extension = file[:-3]
try:
bot.load_extension(f"cogs.{extension}")
print(f"Aktiviert: '{extension}'")
except Exception as e:
exception = f"{type(e).__name__}: {e}"
print(f"Fehler: {extension}\n{exception}")
yes
Traceback (most recent call last):
File "c:\Users\Hardy\Desktop\botss\utility\main.py", line 114, in <module>
for file in os.listdir("./cogs"):
FileNotFoundError: [WinError 3] Das System kann den angegebenen Pfad nicht finden: './cogs'
Das System kann den angegebenen Pfad nicht finden = System cant find the path
help needed how to change variable literal
Help please. I want to send message in special chancel. I try to use this:
async def callback(self, interaction: Interaction):
chanel1: channel = 1021084385543471145
await chanel1.send_message(embed=embed)
But have error, what i should do?
not: chanel1: channel = 1021084385543471145
guild = bot.get_guild(GUILD_ID)
channel = guild.get_channel(1021084385543471145)
await channel.send(embed=embed)
to get a channel you can use utils.get() or get_channel()
What?
Yes?
Can help with this?
Traceback (most recent call last):
File "C:\Users\bogdan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1009, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\bogdan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 359, in invoke
await injected(ctx)
File "C:\Users\bogdan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 135, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: '_MissingSentinel' object has no attribute '_get_overridden_method'
Update to 2.1.3
shop = discord.SlashCommandGroup("shop", "wtf")
@shop.command()
async def test(ctx):
print(ctx)
bot.add_application_command(shop)
try using bot.create_group
Traceback (most recent call last):
File "C:\Users\bogdan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "C:\Users\bogdan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1055, in on_connect
await self.sync_commands()
File "C:\Users\bogdan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 642, in sync_commands
registered_commands = await self.register_commands(
File "C:\Users\bogdan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 541, in register_commands
registered = await register("bulk", data, _log=False)
File "C:\Users\bogdan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 359, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 1: Application command names must be unique```
Oh. My fault. But:
File "C:\Users\bogdan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1009, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\bogdan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 359, in invoke
await injected(ctx)
File "C:\Users\bogdan\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 135, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: '_MissingSentinel' object has no attribute '_get_overridden_method```
shop = bot.create_group("testing")
@shop.command()
async def test(ctx):
print(ctx)
try uninstalling py-cord completely and re-installing py-cord
Again error
I delete dir: cache(in pip) and used command: pip uninstall py-cord
I've had a couple of situations where a command doesn't produce an output on the user's side, but the command was still successful. Despite it working correctly, the end user is told "the interaction has failed"
But I don't have anything beyond the error at all
sorry, i was asking a new question unrelated to your issue.
Oh sorry
Try use this:
@some.decorator
async def some_func(ctx):
await ctx.response.defer()
#and your code```
i actually just found that too, thank you
can someone correct me if this isn't best practice?
About?
Hm. This problem has not yet been solved
is there any reason why the mention ends up like this?
the users are not cached by your/their discord client
do you mind explaining that for me real quick?
your discord client wouldn't cache every user in the world because that would take forever.
so instead it only caches accordingly
and if the user isn't cached, that happens
ok that makes sense, is there any way i could cache that 1 user in the command?
it's not you, as the bot, who caches, it's your user
basically the only way to cache them on your own client would be to somehow see that user naturally
such as seeing one of their messages or viewing their profile
would be able to view the channel be enough?
probably
alright, i'll try to mess around with the options, thank you both!
Is a background loop (task.loop) that runs every 5 seconds to check if any giveaway has ended better than using coros/tasks to schedule ending of each giveaway
Is there a way to check who's in a voice channel, if any?
a background loop would be good, but i'd personally sacrifice the time accuracy by checking every 30 seconds or even a minute
though if you're on a small scale then 5 seconds would probably be fine, as long as you're certain it won't overlap with itself
check channel.members
Is there documentation on activities?
what activities
Like the games.
Is there a way to pass the variable of the person who clicked on the button from on_message to the MyModel class? https://paste.helpch.at/rogarujiye.scss
Exception has occurred: AttributeError
type object 'Interaction' has no attribute 'edit_original_message'
File "C:\Users\doree\OneDrive\Documents\topg\main.py", line 10, in <module>
from discord.commands import Option
how do i fix this error i been using my bot for 2 days now all of a sudden this pops up
i havent added a single thing
or delete a single thing
remove discord.py from dependencies
so do i j uninstall it
then reinstall
idk what that means
uninstall discord and discord.py from pip
and then uninstall py-cord then reinstall py-cord
Interaction has a user attribute.
thanks, i already got it
Random question. Why don't you use the commands features to create your commands? Instead of using the on_message event which is the old way of doing it and VERY uncomfortable
If you know the next end time, you could use something like aiocron to schedule the event for the exact time, then after processing, re-schedule for the next end time, etc
How would it overlap itself?
What's aiocron
theoretically if it takes longer than 5 seconds to run all the logic then the loop will run again before ending, but ultimately you know the speed of your code so if that isn't a worry then feel free to disregard it
I think 5 seconds is enough. Will test though
https://github.com/gawel/aiocron Allows you to set actual crontabs instead of relative tasks
When I start the bot I don't get the list of slash commands, even when I have the server id specified
oh. well whats a crontab?
how to dm a member
i mean my bot banned a user now bot need to notify the user he is banned
Bot is not able to send messages to him 😅
Where in the documentation do I look to get the user_id (not message ID) from a message?
Thank you! Do you have any tips on how to find things like this in the documentation? I tried searching for user ID but this never turned up :S
i found there is author attribute to message then followed it
Thanks so much! 🙏
Alright, so I have this modal:py class get_ad(discord.ui.Modal): def __init__(self): super().__init__( discord.ui.InputText(style = discord.InputTextStyle.long, label = "Enter your Advertisement", placeholder = "Maxium of 250 characters, 5 lines.", max_length = 250), title = "Advertisement", timeout = None) async def callback(self, interaction: discord.Interaction): await interaction.response.pong() and when open it using ```py
modal = get_ad()
await ctx.send_modal(modal)
hello how do i get interaction author? (store in variable as user ofc)


I FORGOT
it worked