#Basic Pycord Help (Quick Questions Only)
1 messages · Page 62 of 1
yw
How do I fix the problem with the categories not showing up
commands don't have a category attribute
Oh
How do I make categories then
Ok
How can i do a manual webhook post request?
My code:
payload = {
"content" : msg.content,
"username" : author.name,
"avatar_url" : author.display_avatar.url,
"embeds" : [e_json],
"attachments" : a_json,
"thread_name" : f"Art by @{author.name}"
}
async with aiohttp.ClientSession() as session:
async with session.post(HOOK_LINK, json=payload) as r:
print(r.status)
print(await r.text())
r.status returns 400 and await r.text() returns this
{"attachments": ["0"], "embeds": ["0"]}
why not just use the native way?
because there's a current bug where posting files when creating a thread doesn't work
because of a library issue
the thing i want to figure out is how to send embeds and attachments created from the library through the post request
tried using the .to_dict() method but it doesn't seem to work
How do I fix this because I only see 2 argument
Traceback (most recent call last):
File "D:\Code\Python\RealDia\main.py", line 64, in <module>
class Debug(discord.cog):
TypeError: module() takes at most 2 arguments (3 given)
It's discord.Cog
Oh ok
400 means most likely something is wrong with your payload
Yep, and i know it's got to do with attachments and embeds
Does the attachment attribute take a json?
it takes an array of attachment objects
i'll add a bit more of the code
e_json = embed.to_dict()
a_json = [a.to_dict() for a in msg.attachments]
I tried doing this to turn discord.Embed and the attachments into a dict
Why are you doing @bot.command inside of a cog?
For categories in the help command
That is not how you use cogs at all
Here's the slash cog example.
Ignoring exception in command Force Starboard:
Traceback (most recent call last):
File "C:\Users\Stickfab\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 124, in wrapped
ret = await coro(arg)
File "C:\Users\Stickfab\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 1668, in _invoke
await self.callback(self.cog, ctx, target)
File "e:\Documents\GitHub\wooperbot\cogs\artboard.py", line 135, in mc_forcestar
await self._forcestar(ctx, message)
File "e:\Documents\GitHub\wooperbot\cogs\artboard.py", line 110, in _forcestar
await self._artboard_add(message)
File "e:\Documents\GitHub\wooperbot\cogs\artboard.py", line 84, in _artboard_add
await self.board_hook.send(msg.content,
File "C:\Users\Stickfab\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 1745, in send
data = await adapter.execute_webhook(
File "C:\Users\Stickfab\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 344, in execute_webhook
payload["thread_name"] = thread_name
TypeError: 'NoneType' object does not support item assignment
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Stickfab\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\Stickfab\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 375, in invoke
await injected(ctx)
File "C:\Users\Stickfab\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'NoneType' object does not support item assignment
seems to be an issue with pycord since in payload["thread_name"] = thread_name, payload is None
may or may not have relation to this issue https://github.com/Pycord-Development/pycord/issues/1949
Commented about it on the current open issue, hope it gives off a hint https://github.com/Pycord-Development/pycord/issues/1949#issuecomment-1453888964 ¯_(ツ)_/¯
In your opinion, is it better to set optional arguments/properties as 'or' or 'equals'?
name: str | None
name: str = None
Both seem to functionally do the same (on the surface), but curious which way is more 'pythonic'
Well the first one is type hinting, not a default value
neither imo. name: str | None = None seems to follow pep 484 (type hinting) better
If you do def foo(x: str | None) you still need to pass a value to x
Okay, I could be getting spoiled by pydantic
(str | None = None is ugly; how could that be the recommended style)
that's just type hinting x to str or None. It does not set any value to x
Right. So in that case, x: str = None be valid, then?
well that is the one which makes the most sense. None is not str. typehinting as only str would be wrong because it can be None when default
Well the thing is, you said
Both seem to functionally do the same (on the surface), but curious which way is more 'pythonic'
Which is wrong, because they are two completely different things
One is type hinting, the other is setting a default value
True, depending on the context. I was working in pydantic where they do both work similarly, but can see how it would be different in a def
the result is the same for both when dealing with slash command options. but as you said, different when speaking normally
It's not, but there's something to be said for brevity and implication; it may be "wrong" in a rigid sense, but would be obvious and unambiguous to anyone reviewing.
str | None = None seems awfully redundant.
Anyway, the answer to my initial question seems to be "it depends" 😅
ye
typecheckers will complain
mypy would probably too
pycharm hasn't, but yeah I don't run it through black or mypy, etc.
ou
Any way to EDIT a message's file attachment rather than add a new one without having to edit the message twice and utilize file = []?
pass attachments kwarg instead of files
.rtfm message.edit
Didnt get an answer a few days go gonna try again:
Is there any way to hide commands from users on the backend side? (eg if the command doesnt pass checks) I know you can hide via server settings
also a couple more questions that I could figure out by spinning up a testing bot but would be helpful for a quick response here:
-
Does remove_cog() and add_cog() on the same cog pick up changes in code? or will it keep the same code as when the bot started?
-
What happens if two different bots register the same slash command name?
You can't hide commands like that, no.
thought that might be the case, thanks
- Just use https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.reload_extension
- Nothing? What do you mean by that?
is it still broken?
Is what broken?
like if i have two bots on a server that both have a /time command, will it just allow a user to select which bot you want to use the /time command on?
Yes, that is how slash commands have always worked.
You can literally see it by typing /help in here
o7 -
I am using self.load_extension("src.cogs", recursive=True) in order to load the cogs on my bot.
However. It is only loading 1/3 of the cogs that I have. I'm struggling to figure out why.
is it possible to receive an event when an interaction button is clicked?
This section outlines the different types of events listened by Client. There are 4 ways to register an event, the first way is through the use of Client.event(). The second way is through subclass...
only this one I know
do self.load_extensions("src.cogs")
It still only loaded one :/
well your cogs probably have errors in them
I think there might be an issue with the cogs?
Damn.. I have no idea what it is. As the init is the same for the cogs..
And logging for errors does not give anything
try adding ```py
@commands.Cog.listener()
async def on_ready(self):
print ("Ready! Cog X")
Is this in the cogs?
yes
Cool, will give it a go
Try load_extensions
Hmmmm... I can see how the would be different.. I will try
add the self
oh right
x3
my brain
Did it work?
@grizzled sentinel @novel jay
I've made all of the cogs identical. If needed I can add my code somewhere else if it is not a good idea to do so here..
They all contain:
"""
General Slash Cogs
"""
import logging
from discord.ext import commands
logger = logging.getLogger()
logger.setLevel("INFO")
class SlashGeneral(commands.Cog):
"""
General Slash Commands
"""
def __init__(self, bot):
self.bot: commands.Bot = bot
logger.info("Init General Slash Command Cog")
@commands.Cog.listener()
async def on_ready(self):
logger.info("General Cogs: READY")
def setup(bot):
"""
Add cog to bot
"""
bot.add_cog(SlashGeneral(bot))
And only this one is being loaded? It's very odd.. this is how I am doing init in the bot class..
def __init__(self, debug_guilds):
super().__init__(self, debug_guilds=debug_guilds)
self.load_extensions("src.cogs", recursive=True)
logger.info("Cogs added")
Hmm, I am just a little confused because it worked fine before. But stopped.. possibly something to do with the new pycord version.. I am now loading them in main.. but.. same issue
I am very confused
which py-cord version?
2.3.2
I will put it this way. It was working on Feb 7th
update to 2.4.0
That worked
If using slash commands you should not use discord.ext.commands
Use discord.Cog and discord.Bot instead.
only using slash commands
I am only using them yes..
What
You can't add params
Unless you literally edit py-cord's code and don't break anything
Why do you want a channel parameter?
Do you realize you adding 3 lines to your event listener is the same thing than adding the 3 same lines to the event dispatcher right
This is not possible becouse of a discord limitation.
can you do something like prefix command arg command ?
what
They want a slightly modified group commands setup
Where args are accepted before the subcommand
Well since they're using prefix commands that shouldn't be too hard
just validate and parse each argument
Dammit; having brain-damage on interactions again.
I press a button, which does a thing and then edits the interaction message using interaction.response.edit_message. Normally this works fine, but the button is now taking juuuust over the 3-second response time.
I tried using interaction.response.defer(), but now it won't let me edit, saying it was already responded to.
Is there a way of overcoming this?
Hey my button says interaction failed and i dont want to send any response to it, how can i make it not say interaction failed?
defer it and dont send a followup
use interaction.edit_original_response to edit
if that doesnt work use interaction.message.edit
Is it necessary to enable intents on all cog files when it is already enabled in the main file?
What? How would you even enable intents in a cog?
sorry i mean the in the cog file using bot = discord.Bot(intents=discord.Intents.name()), not in the class
Why would you do bot = discord.Bot(intents=discord.Intents.name()) in a cog file?
You don't define a bot instance in your cog files
what about a non-cog file which only includes a command function instead of cog?
Huh?
?
What do you mean a non-cog file? You can't have commands in separate files without using cogs
that's not how it works
You either have them in your main file or in cogs
okay, anyways how can I check if the channel where the command was run is a forum thread or not?
.rtfm Message.thread
how does create_group work in 2.4?
main file or cogs?
cogs
Here's the slash cog groups example.
like that
ohhh thanks let me try it
it worked thanks a lot
discord.ui.Views in cogs not persisting
#Cog
class CogSample(commands.Cog):
@commands.Cog.listener()
async def on_ready(self):
print(f"{__name__} Loaded")
bot.add_view(MyView())
@buy.command(name="setup")
async def setup(self, ctx: discord.ApplicationContext):
embed = discord.Embed(title="", description="",color=discord.Color.blue())
await ctx.send(embed=embed, view=MyView())
await ctx.respond("Created",ephemeral=True, delete_after=0.1)
#View
class MyView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None) # timeout of the view must be set to None
i have something like this set up
Here's the persistent example.
@leaden relic see that
Here's the tic tac toe example.
look a few lines above and below
check if you see any mistakes
if not, send the code here
also which python version are you using?
python version. not py-cord version
cool
i did though i was looking for a way to do it inside a cog, i somehow made it by calling the view in the main file's on ready
would be better if persistence could be done iside the cog's on ready
why not do it in the init?
on_ready is not safe as it can fire multiple times
do all the items have custom id set?
discord.Bot has init ?
Every class has an init function
yeah it works on bot.event on_ready but not inside the cog file
@bot.event
async def on_interaction(interaction):
if interaction.custom_id == "register":
How to filter the interaction from the Button's label text
without it having a custom id
You could check in interaction.data but discord might not send the label. What are you trying to do because I think there might be a better way.
Basically make it respond with an error message saying "This interaction expired" for buttons which people press after months
Ok 👍: that is a valid reason to use on_interaction (most people use it wrong)
The docs dont show what the raw data given in interaction.data is can you post the output of printing that here
<MessageInteractionData custom_id='44edf50c18a781e943424a8ef7de4a80' component_type=<ComponentType.button: 2> values=None>
Yeah
interaction.data prints this
Yeah, I dont think you can get the name of the button unless you load the view (Would not be worth it in your case.) You could disable all the buttons in expired interactions instead.
Ah
Ig instead of that now i'll assign a custom id for each interaction in the future
custom_id will definitely help right
for future, idc about the past button clicks then
The custom ID is just a "username" for the button. I dont think it would further your progress. 2 buttons generally should not have the same ID. I have been meaning to play around with buttons with the same ID for things simple like delete message but Im not sure how it will act.
Oh actually it does work out for me
I need it in such a way to detect separate buttons actually
it's meant to have a different This interaction has expired response in my case
Thanks!
how to make a loop in pycord (for the presence)
Use ext.tasks
Here's the background task example.
oh ty
Does this work with bot instead of client?
discord.ext.tasks it is separate from the bot
Here's the background task asyncio example.
i need a loop for the activity presence
So I would be running a client.. and a bot?
can you just tell me how, or give me a good example? the one from the toolkit didn't rly help me :/
sadly
No, you would not need client
If you put the task in a cog you can access bot.
Ah ok, so the example uses client. But if I put that in bot cog it would work?
I’ll try that.. I need a background task that will update roles every x hours, as well as on command
Yeah, This guide example looks a bit better
from discord.ext import tasks, commands
class MyCog(commands.Cog):
def __init__(self):
self.index = 0
self.printer.start()
def cog_unload(self):
self.printer.cancel()
@tasks.loop(seconds=5)
async def printer(self):
print(self.index)
self.index += 1
with discord.Cog if using slash commands of course
The answer is yes btw. What Ice wolf meant that ext.tasks and bot clients aren't related. Heck you can even use ext.tasks with some other project that doesn't even use discord
Ahh, sorry, thought the “not related” meant they wouldn’t work 😂 thanks
i did try putting it in init of cog but it throws an error
Do you want to show this error? Or should we guess what it is and see if we're right?
ohh wait
Note: i have a bot = discord.Bot() outside the cog class
my first ver of init was
def __init__(self, bot):
self.bot = bot
bot.add_view(MyView())
this raised a RuntimeError: No Running Event Loop
the second one is
def __init__(self):
bot.add_view(MyView())
this one raised a TypeError: __init__() takes 1 positional argument but 2 were given
I don´t understand this part in discord.Webhook example
async with aiohttp.ClientSession() as session:
webhook = Webhook.from_url('url-here', session=session)
because in the description it says "Represents an asynchronous Discord webhook."
If it´s asynchron, why i have to do this with aiohttp again?
Then the description is false or not?
Why would it be false??
I always thought with aiohttp i made an synchron call an asynchron one
Yes?
But the description says it's asynchronous, so I don't need to make the call asynchronous again
or not?
What are you even talking about
The description says it's asynchronous because it is, because it's using aiohttp
no

the description says discord.Webhook is asynchronous.
And aiohttp made it asynchronous again

Yes? You have to use aiohttp if you want to use asynchronous stuff
That's how it works
It's not just going to be magically asynchronous
ok then that's misleading for me, because I thought the discord.webhook is already there
theres a lot of asynchronous functions out there, so yes i thought it going to be magically asynchronous 😄
Even if a function is asynchronous you have to use aiohttp
Otherwise it's useless to have it async in the first place
Hi, stupid question: I've got all the intents:
intents = discord.Intents.all()
client = discord.Client(intents=intents)
enabled but I still can't read message.content outside DMs. Is this something i'm missing?
Did you enable such intents on the dev portal?
what pycord version are you using?
2.4 I think?
I used whatever pip gave me
it is possible i failed to cleanly remove discord.py before switching to pycord
do pip freeze and see if you have discord still in there
or anything that could conflict
Can you show the pip list?
if you're on linux you can do something like pip list | grep discord
^
on windows it's pip list | findstr "discord" I think
any example of "about me" or watching or streaming? i want to make it dynamic with a users counter?
about me is different from bot's activity
ok i am now in a venv so i have nothing
]
example about bot's activity?
ha, what the heck
Uninstall pycord and use py-cord
not sure if there is an example, but what you want is bot.change_presence
is there a difference and if so why is this
.rtfm bot.change_pre
pycord is incorrect, py-cord is correct. It's because the package is named py-cord and not pycord
why do both of these things work up until this exact point then
"pip install pycord" should probably spit out an error rather than installing a bugged version 😅
ok here we are currently
it is a different library. an ffmpeg wrapper
Realistically it shouldn't work, because pycord isn't even a wrapper for the Discord API
Do it x3
there was a time when i was having a hard time setting up venv 😌
that time for me is literally now, i hate venv T_T
At my Pi I dont even use a venv x3
first step: python -m venv venv the second venv here is the name of the virtual environment
second step: ./venv/Scripts/activate this is to activate the venv
every time i interact with venv i feel a vague sense of dread
In production using a venv shouldn't be necessary anyways unless you're hosting multiple things. But during development it's basically a must to avoid a pain with conflicts
i used to not use it too, but too many packages get in the way and forced me to learn it now i like it hahaha
ha lmao powershell accepts forwardslashes
I always use WSL when developing because I don't like Windows CLI
oh no it's still somehow kept the old packages what tf did i do
oh clown moment
i'm using the system python
very unused to dev on windows pls understand
Hence why I recommend WSL ^
`import discord
bot = discord.Bot()
testingservers = [1022218805214183525]
random = bot.random()
@bot.event
async def onready():
print("loaded, Everything functions {bot.user}")
@bot.slash_command(guild_ids = testingservers, name = "start", description = "Check to see")
async def work(ctx):
await ctx.respond == ("Hey, loser. You suck bozo L BOZO L RATIO FAKE BOT")
bot.run('MTA4MTYxMTMxNzgwNDI5MDA0OQ.Gvw5W7.SFEU6KFWZmCkced-M4UpJCUcPIHzRL6GIHunhs')
` Ignore the the "Hey, loser. You suck bozo L BOZO L RATIO FAKE BOT" The bot hosting works. But not the command
how do i check if a user has the active developer badge
you need intents
i think
intents = discord.Intents.all()
intents.members = True```
wiat why are you sending your client secret here?
Nice token
then bot = bot.random(intents=intents)
Pls reset the token
Doesnt matter
await ctx.respond == ("something here") what's with this line?
oh, thats when the command plays
it responds with the text
no i mean what's with the ==
was testing stuff
What?
it's await ctx.respond("something here")
nevermind
dosen't make much of a difference
and it's not bot.random()
it's bot = discord.Bot()
Reset your bot token
prob here
Can you open a thread?
@bot.slash_command. Im pretty sure i enabled the commands in Oauth2
yeah fair enough
@bot.event
async def on_ready():
and what is bot.random? And onready is not a thing
ik
the bot random thing is for something else
And why is your command inside of the onready method?
wait where do i create the thread i can't create it here and #general is the wrong place for it
#969574202413838426
Why does the #github stuff looks so bad at my phone
im new to this stuff, the reason why. Pycord wouldnt install. It got installed yesterday. I used the pycord install command. didnt work
ohhh it changes to #
dark dark mode
If you're new to Python you shouldn't be making a bot in the first place. Read #help-rules
forgot lmao
anyway have a nice day
Discord Mobile, always bringing new visual bugs to enjoy
to be fair developing anything for mobile is a pain
I dont know how it is so I cannot say anything about it
how do i make it so it displays 2 badges? ive tried this:
if user.public_flags.hypesquad_bravery:
e.add_field(name=f"**Badges**", value=f" Hypesquad Bravery", inline=False)
if user.public_flags.active_developer:
e.add_field(name=f"**Badges**", value=f" Active Developer\n Hypesquad Bravery", inline=False)```
Why are you nesting your if statements?
uhh idk i was just trying stuff
Well don't nest them
just have a separate if statement for if user.public_flags.active_developer:?
Yes? Your logic makes no sense right now
i already tried that tho
oh wait
okay i tried it and it didnt show hypesquad badge cuz i dont have one

Hello guys. I have a question related to select menu. When the bot turns off and on, the menu does not work, you have to use the command again, is there any way to fix it so that it works forever
Here's the persistent example.
If I have three buttons like this:
async def button_callback(self, button, interaction):
label: str = "A1"
author = interaction.user
for child in self.children:
if child.view.id != {"A1", "A3"}:
child.disabled = True
if self.buttons_selected < 1:
await interaction.response.edit_message(content=f'{author}, your first choice was {label}! Please select '
f'another option')
self.set_button_one(label)
self.increase_button_selected()
else:
self.set_button_two(label)
self.reset_button_selected()
await interaction.response.edit_message(view=None, content=f'{author}, your first choice was '
f'{self.button_one} and '
f'your second choice was {self.button_two}!')```
I'm trying to disable different ones but this isnt working. Is it not child.view.id to check that?
are you trying to disable a button that is not in the set of {"A1", "A3"}?
I have all the buttons under the same class, I assumed I could disable them by calling their custom_id using the child attribute
id ≠ custom_id.
you are also comparing a string to a set of strings, which will return false
you may be looking for
if child.custom_id not in {"A1", "A3"}:
hmm, I get an unresolved reference error with child.custom_id. Do I need to import that directly from pycord?
ok, got this:
async def second_button_callback(self, button, interaction):
label: str = "A2"
author = interaction.user
for child in self.children:
if child.view.custom_id not in {"A1", "A2"}:
child.disabled = True```
and it doesn't throw any errors in pycharm but when I press the button in discord I get: 'BingoButtons' object has no attribute 'custom_id'
you can always compare the label instead
would that require adding in the eq method to the class?
or am I missing something obvious
uh view doesnt have a custom id
the items do
mmm, so if I have a
class DisableButtons(discord.ui.View)
I wouldn't be able to grab the labels/custom_id from that?
pretty sure no. although the buttons inside can have custom ids
hmm, so is there someplace I should look for information on how to do this? I want to have a 5x5 board of buttons and disable certain ones based on which other button is pressed. Is there a way to check the button label or custom_id to disable is or am I gonna need to try a different method?
Thank you very much for this. Now everything works, but unfortunately not with a modal window, when I add it to item , pycord requires another title argument, but it is not needed at all
🤔
ig you can check the button label. iterate over view.children
uh you cant have a persistent Modal, can you?
ohhhh, yes yes..
thank you bro
lol np
show MyModal code?
await interaction.response.send_modal(MyModal(title="Modal via Button"))```
ok, one moment
class MyModal(discord.ui.Modal):
def __init__(self):
super().__init__(timeout=None)
self.add_item(discord.ui.InputText(label="Как вас зовут?")) # первое поле
self.add_item(
discord.ui.InputText(label="Сколько вам лет?")) # второе поле
self.add_item(
discord.ui.InputText(label="Ваш любимый фильм?")) # третье поле
self.add_item(discord.ui.InputText(label="Ваше хобби?")) # третье поле
self.add_item(
discord.ui.InputText(label="Чем увлекатаесь?",
style=discord.InputTextStyle.long)) # большое поле
# Система логов, вся информация на канале about
async def callback(self, interaction: discord.Interaction):
# Канал на котором будет отправлен лог
channel = discord.utils.get(interaction.guild.channels,
name='┣🍰・about') # НАЗВАНИЕ КАНАЛА ЛОГОВ
await interaction.response.send_message("Успех!", ephemeral=True)
author = interaction.user
await channel.send(f"{author.mention}")
embed = discord.Embed(
title=f"☘️ {author} Решил вам рассказать о себе!",
colour=0x2f3136,
description=f"""
**Имя** — {self.children[0].value},
**Возраст** — {self.children[1].value},
**Любимый фильм** — {self.children[2].value},
**Хобби** — {self.children[3].value},
**Увлечение** — ```{self.children[4].value}```
""",
)
embed.set_footer(text="Спасибо за хорошую информацию!")
await channel.send(embed=embed)
- def __init__(self):
- super().__init__(timeout=None)
+ def __init__(self, title):
+ super().__init__(title, timeout=None)
squid really rocking those diff codeblocks lol
Is the a way to use cogs and bridge
yes?
Nice and what now?
I think I found it
How do I get categories for help commands
so im having a little bit of an issue, wondering if anyone has a quick fix answer.
I'm able to grab the "interaction.user" from a message, but if that user mentions another user i am unsure how to grab that mentioned user's information from the interaction.
I should point out, this is for a third party bot that processes reminders and game data collation for a discord game so the user is not interacting with my bot so I cannot grab it from a ctx command.
.rtfm Message.mentions
this is from a slash command not a regular message
the game has message intents so prefix commands i can capture mentions fine.
it also has slash commands to access the same data, and when using slash there is an option to select a user and view their data instead of your own; i can capture who initiated the command, but not who they mention and message.mentions returns None
How would you grab information about mentioned users if you can't see mentioned users?
ive tried to grab the member data from the embed it sends but for some reason it is not matching the username provided via "get_member_named()" function
so i'm doing a message search through message history to capture the trigger phrase
and if that has mentions i can capture who they mention, or just the message.author
however with slash i can only capture the interaction.user
And if you grab the original_message from the slash command?
it returns information about the command, the channel, the message, guild etc but not any actual message content
trying to get information about the interaction now
ok ive got the interactionMessage.data but theres still only the interaction user's id
ive got roles, name, id, discriminator, avatar, etc
How do I make hidden messages
Where if used only the person that used the command can see if
Can you do that in ctx.send()
no
Ok
its for slash interaction responses only
^
Well my non slash commands work but not the slash commands
?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.
Never mind had to restart the bot
lul
How do I make a command that can mass delete messages
I had no clue where it was in the documentation
why?
you dont know how to use a search field?
purge isn't exactly initutive to everyone.
but if people also would use google they would find examples to it 
so I'm trying to do some cleanup code for if I want to shutdown my bot, and I want it to delete a 'dashboard' message, I'm able to get the code working in a test async function, but doing it in cog_unload is getting me issues, getting 'was never awaited' can anyone tell me what I'm doing wrong here?
def cog_unload():
for guild_id in self.lastmsg:
with asyncio.Runner() as runner:
guild = runner.run(self.bot.fetch_guild(int(guild_id)))
channel = runner.run(guild.fetch_channel(self.lastmsg[guild_id]['channel']))
msg = runner.run(channel.fetch_message(self.lastmsg[guild_id]['msgid']))
jump = msg.jump_url
runner.run(msg.delete())
print(f"Deleted dashboard message {jump}")
did you read the first line?
you're really one of the most unhelpful people on this server
also fetch is a coroutine
you have to await if you use fetch
Override bot.close
It is an async function
Don't do this in cog_unload
ok thanks
was trying to figure out how to make it work by even just getting the main loop off of the bot and trying with that, no dice. But too frustrated to delve deeper heh
any guide for always working buttons (persistent)?
i know we can add custom views to the on_ready function
but how to do it dynamically
like if a user runs a command, it shows them the buttons. i want the buttons to stay working, even on restart.
another question, how to get the message upon which the button is clicked (interaction has happened)
for example i have multiple messages with the same persistent view, how to get the message object upon which button has been clicked.
thanks
are the buttons dynamic based on what the user inputs in the command?
then use a db
to store what the user enters
interaction.message
Yes
Oh damn I'll have to use a db then
not that difficult
use sqlite
and please nojson
?tag nojson
Why not to use json files for data storage
JSON files are commonly used to store data that is read by a program, however, they are unsuitable for storing dynamic data due to a number of reasons.
It is recommended to use a DBMS (Database Management System) as they come with optimized technologies for storing and retrieving information.
Advantages of using a database:
- Database tables can be related, making it easy to separate your information into multiple tables and only fetch what you need
- Databases allow you to use a query/data processing language to make complex data operations easier with less code
- One misplaced character will corrupt an entire file. A database very rarely experiences corruptions due to their automatic handling of data integrity
- Transactions in SQL databases allow you to revert unwanted changes and prevent data corruption in the case of an error
- Databases have support for indexes, allowing retrieval of some data to be extremely fast
- It is very easy to update existing data in a database, as opposed to re-writing a file
- Databases are reliable
Popular database management systems:
- SQLite3
- MongoDB
- PostgreSQL
- MySQL
- MariaDB
- Microsoft Access
Yes yes, i don't use json anyways for db. Always have used postgres
wow tysm 
I have a list of discord role ids, i want to check if a user has any role that has the same id in that list. what is the effecient way to do that?
you could use python function any
but i think ill need the list of ids of that member
along with list comprehension
i cant just do member.author.roles.any([id lsit])
k ill try that
member.author.roles.any([member.guild.get_role(x) for x in mylist])```
uh no
then
any is a python function. it accepts a list of values and returns True if any of the value is true
you use it like this xyz = any([...])
easiest way would be using list comprehension
there is also commands.has_any_role but that is a command check
.rtfm has_any
lol 👍
!rtfm CommandTree
!rtfm app_commands
.rtfm app_commands
.rtfm CommandTree
Target not found, try again and make sure to check your spelling.
what does mentionable_select do?
#883236900171816970 please 
sorry
iirc, a select menu that includes user, roles and channels
string dropdowns have a limit of 25 options
but discord allows other dropdown types too. namely user, role, channel and mentionable (which is previous 3 combined)
you can filter channel select menus if you want to display specific types like text, voice, category etc
Should i use aiosqlite or json to store stuff??
I have a server with over 10,000 members and i need to store alot
sqlite please
?tag json
Why JSON is unsuitable as a data storage medium.
-
JSON, quite simply, is not a database. It's not designed to be a data storage format, rather a way of transmitting data over a network. It's also often used as a way of doing configuration files for programs.
-
There is no redundancy built in to JSON. JSON is just a format, and Python has libraries for it like json and ujson that let you load and dump it, sometimes to files, but that's all it does, write data to a file. There is no sort of DBMS (Database Management System), which means no sort of sophistication in how the data is stored, or built in ways to keep it safe and backed up, there's no built in encryption either - bear in mind in larger applications encryption may be necessary for GDPR/relevant data protection regulations compliance.
-
JSON, unlike relational databases, has no way to store relational data, which is a very commonly needed way of storing data. Relational data, as the name may suggest, is data that relates to other data. For example if you have a table of users and a table of servers, the server table will probably have an owner field, where you'd reference a user from the users table. [This is only relevant for relational data]
-
JSON is primarily a KV (key-value) format, for example
{"a":"b"}where a is the key and b is the value, but what if you want to search not by that key but by a sub-key? Well, instead of being able to quickly usevar[key], which in a Python dictionary has a constant return time (for more info look up hash tables), you now have to iterate through every object in the dictionary and compare to find what you're looking for. Most relational database systems, like MySQL, MariaDB, and PostgreSQL have ways of indexing secondary fields apart from the primary key so that you can easily search by multiple attributes.
For more info and resources about storing persistent data, please check out https://vcokltfre.dev/tips/storage/
?tag nojson
Why not to use json files for data storage
JSON files are commonly used to store data that is read by a program, however, they are unsuitable for storing dynamic data due to a number of reasons.
It is recommended to use a DBMS (Database Management System) as they come with optimized technologies for storing and retrieving information.
Advantages of using a database:
- Database tables can be related, making it easy to separate your information into multiple tables and only fetch what you need
- Databases allow you to use a query/data processing language to make complex data operations easier with less code
- One misplaced character will corrupt an entire file. A database very rarely experiences corruptions due to their automatic handling of data integrity
- Transactions in SQL databases allow you to revert unwanted changes and prevent data corruption in the case of an error
- Databases have support for indexes, allowing retrieval of some data to be extremely fast
- It is very easy to update existing data in a database, as opposed to re-writing a file
- Databases are reliable
Popular database management systems:
- SQLite3
- MongoDB
- PostgreSQL
- MySQL
- MariaDB
- Microsoft Access
Async sqlite makes the code very messy
asqlite is slightly better library because it has connection pools aiosqlite
Split methods, join methods
not a lot 
you dont store lists in sql
exactly
you use separate table with relations
thats the 1st principal of sql
1 column of a row shouldn’t store more than 1 piece of data
I was doing smt like this ",".join(list) and list.split
you create a separate table and use foreign keys
bad choice
Imma have to watch some vids ig
see this
you can do smth like that
?!
help please...
def __init__(self, title):
super().__init__(title, timeout=None)
self.add_item(discord.ui.InputText(label="Как вас зовут?")) # первое поле
self.add_item(
discord.ui.InputText(label="Сколько вам лет?")) # второе поле
self.add_item(
discord.ui.InputText(label="Ваш любимый фильм?")) # третье поле
self.add_item(discord.ui.InputText(label="Ваше хобби?")) # третье поле
self.add_item(
discord.ui.InputText(label="Чем увлекатаесь?",
style=discord.InputTextStyle.long)) # большое поле
# Система логов, вся информация на канале about
async def callback(self, interaction: discord.Interaction):
# Канал на котором будет отправлен лог
channel = discord.utils.get(interaction.guild.channels,
name='┣🍰・about') # НАЗВАНИЕ КАНАЛА ЛОГОВ
await interaction.response.send_message("Успех!", ephemeral=True)
author = interaction.user
await channel.send(f"{author.mention}")
embed = discord.Embed(
title=f"☘️ {author} Решил вам рассказать о себе!",
colour=0x2f3136,
description=f"""
**Имя** — {self.children[0].value},
**Возраст** — {self.children[1].value},
**Любимый фильм** — {self.children[2].value},
**Хобби** — {self.children[3].value},
**Увлечение** — ```{self.children[4].value}```
""",
)
embed.set_footer(text="Спасибо за хорошую информацию!")
await channel.send(embed=embed)
The error explains exactly what's wrong
how can i pass data to after invoke functions of a command
Can you recommend me some docs? I am not that copy paste kinda guy, i won't implement smt im not familliar with
I wanna make an infinte list not a defined one
Like entering giveaways/queues
He clings to line 98, well, there is a heading there, he says that he is needed, I don’t understand at all
Read the error, title is a keyword only argument
Sending the error again won't solve it
the problem is solved, the modal window opens when its button is met, but does not send the most, the modal window
Whatever that means, ok then
the callback function of the modal window is not handled.
well it is an sql structure thing
not sure if there are docs on how to structure your db
so lets say you have a table called guilds
which has your guilds
now lets say you want to store a list of blacklisted users for a guild
earlier you were storing them as a string, but thats very bad practice
what you would rather do is
create another table, lets say bl_users. 1st column would be user_id, 2nd column would be guild which references guilds table
OHHH thx dude u are a big help
but there would be no performance problems if i have like say 30 lists
also what lib were you talking about? asqlite? i am currently using aiosqlite
wdym 30 lists?
what is asqlite?
super().__init__(title=title, ...)
thx
Your table structure has nothing to do with the library you're using.
how can i convert datetime object to timestamp?
.rtfm utils.format_dt
SQL random row selection is extremely fast with barely any performance loss at big sized tables
asqlite and aiosqlite both use the built in sqlite3 library. But asqlite has a slight advantage as it supports connection pooling. This allows for much better async usage
dt.timestamp ?
how can i make 1second has passed live on discord.py?
like the ones in the giveaway bot
This is not discord.py
IMO it's fine to start off with your bot storing stuff in JSON but sooner or later you will want to transition to a database system, and in retrospect to my project I switched probably a lot later then I should.
A lot of useful functionality comes with something so simple as sqlite, stuff that I was implementing myself and wasting time, but I was putting off brushing back up on sql and understanding what each DBMS does/which is right for me
?tag nojson
Why not to use json files for data storage
JSON files are commonly used to store data that is read by a program, however, they are unsuitable for storing dynamic data due to a number of reasons.
It is recommended to use a DBMS (Database Management System) as they come with optimized technologies for storing and retrieving information.
Advantages of using a database:
- Database tables can be related, making it easy to separate your information into multiple tables and only fetch what you need
- Databases allow you to use a query/data processing language to make complex data operations easier with less code
- One misplaced character will corrupt an entire file. A database very rarely experiences corruptions due to their automatic handling of data integrity
- Transactions in SQL databases allow you to revert unwanted changes and prevent data corruption in the case of an error
- Databases have support for indexes, allowing retrieval of some data to be extremely fast
- It is very easy to update existing data in a database, as opposed to re-writing a file
- Databases are reliable
Popular database management systems:
- SQLite3
- MongoDB
- PostgreSQL
- MySQL
- MariaDB
- Microsoft Access
Using json files for data storage is just wrong, it's not what json files are meant to be used for.
The only reason I can think of for using json files as a "database" is because you don't know of any other method. Or just laziness
Just learn how to use a database, like mongodb. Believe it or not, I used to use json files for a little while and I saw some data being lost for some reason and wasn’t very reliable. Learn how to use a database, it will literally save you so much time. We won’t give you help on json databases, since they suck and json isn’t really meant for that.
they're perfectly fine for static data, like configuration files and backups of data. But as soon as you start reading/writing to a json file programmatically it will only cause you pain and confusion.
why do i get this? it means something like: enter a valid integer
I don't think QUIKZ is an int is it?
no i have async def changeserverid(ctx: discord.ApplicationContext, licensekey: str, neue_serverid: int):
the first works
server ids are too big to be accepted as int by discord
accept str and convert to int in your code
oof okay thanks
yea lol np
How do you embed commands into discord markdown?
i remember there was a bot that had some sort of click to use a slash command
</full name:ID>
and the id is the channel id?
command id
name can be anything aslong as the id is right
if it is not - it wont be clickable
</fake command:123123>
how do I get the command id?
Using code, it would be
ctx.command.id
Can someone explain to me how to make my Paginator persistent?
@commands.command(name="showspot", help="Zeigt alle Spots an")
async def page(self, ctx):
paginator = await PaginatorInfoView(self.bot)
await paginator.send(ctx)
class PaginatorInfoView(Paginator):
async def __new__(cls, *args, **kwargs):
obj = super().__new__(cls)
await obj.__init__(*args, **kwargs)
return obj
async def __init__(self, bot: discord.Bot):
self.bot = bot
pages = await self.generate_pages()
view = await self.generate_view()
super().__init__(pages=pages, custom_view=view, timeout=899, author_check=False)
async def generate_pages(self):
SPOTS_PER_PAGE = 6
data = await dab.get_all_spots()
pages = []
.
.
.
embed.add_field(name=name, value=fish_text + spot_text, inline=False)
pages.append(embed)
return pages
async def generate_view(self):
view = SpotDetails(self.bot)
return view```
how do I make a app command only available for the bot owner
You can
- Use the
guild_idsparameter and only register it in a specific guild - Use the
@commands.is_owner()check. (Note that others can still see it, just fails on usage)
Paginators are views too! Just add them to the bot.
so there is no "real" way to make a command owner only? (native discord)
Like this?
class Base(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.persistent_views_added = False
@commands.Cog.listener()
async def on_ready(self):
if not self.persistent_views_added:
self.bot.add_view(PaginatorInfoView())
self.persistent_views_added = True```
yes
I'm not Python, but that looks right.
Hmm when I restart the bot the buttons still don't work, maybe someone who knows Python can help me? 🤔
Add a print in your on_ready to see if it runs
How can I add the custom_id to the paginator? When I add it in the super init I get the error that it is not known there?
ValueError: View is not persistent. Items need to have a custom_id set and View must have no timeout
Here I create the view for my Paginator:
async def generate_view(self):
view = SpotDetails(self.bot)
return view```
And that is the view:
```py
class SpotDetails(discord.ui.View):
def __init__(self, bot):
super().__init__(timeout=None)
self.bot = bot
self.message_details = []
@discord.ui.button(label='Spotdetails abrufen', style=discord.ButtonStyle.gray, custom_id='spotdetails', row=1)
async def spotdetails_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message('Test', view=SpotDetailAuswahlView(self.bot, self.message_details), ephemeral=True)```
What I meant to say is that I am not the Python Interpreter so I cannot know for sure if something will work or not.
You can try
for child in view.children:
child.custom_id = "something unique here"
in your __init__
In the init of my view or?
which ever one that works
what am I doing wrong? this appears on startup [resolved (my server is using python 3.8)]
When I try to do it this way, I get my print that the view has been added although there is no paginator and when I try to create one, I get the message that the ID cannot be used multiple times. 🤔
async def generate_view(self):
view = SpotDetails(self.bot)
for child in view.children:
child.custom_id = "Info_View"
return view```
The print works, I can also create the paginator with the view but when I restart the bot the paginator still does not work.
@commands.Cog.listener()
async def on_ready(self):
if not self.persistent_views_added:
self.bot.add_view(await PaginatorInfoView(self.bot))
print("Views added")
self.persistent_views_added = True```
```py
class SpotDetails(discord.ui.View):
def __init__(self, bot):
super().__init__(timeout=None)
self.bot = bot
self.message_details = []
self.custom_id = 'spot_details_view'```
Paginatorclass:
```py
async def __init__(self, bot: discord.Bot):
self.bot = bot
self.pages = await self.update_pages()
view = await self.generate_view()
super().__init__(pages=self.pages, custom_view=view, timeout=None, author_check=False)
async def generate_view(self):
view = SpotDetails(self.bot)
return view```
is there a way to make text commands cuz the docs are giving me aids
"text commands"?
yeah but im trying to make slash commands too
like a mix
does that overwrite @bot.command?
ok so if i import i use @bot.command for non slash commands and @bot.slash_command for slash commands?
try it and see 
discord.errors.LoginFailure: Improper token has been passed. dude i just reset the token 4 times wtf
are you sure you are using the token, not the client secret?
yes
The error doesn't lie, you're either using the wrong token or passing it incorrectly
the tokens don't even start with same letters
wait
wtf
WHY WASNT IT COPYING TO MY CLIPBOARD
GODDAMNIT
nope still not working
same token now
let me regen a 5th time
are you running the right thing
yuh
it was working fine yesterday
i made no changes other than changing the bot token
cant your bot get temporarily fucked if it does something malicious
mine wasnt, just asking
you can try inviting the bot and see if the "quarentined" error shows up
create a new guild and add it to it
yeah it works
friends token isnt working either
import asyncio
import discord
import colorama
from datetime import datetime
colorama.init()
bot = discord.Bot(intents=discord.Intents.all())
def print_info(message):
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(f'[{colorama.Fore.BLUE}+{colorama.Style.RESET_ALL}] {colorama.Fore.LIGHTBLACK_EX}{timestamp}{colorama.Style.RESET_ALL} | {message}')
def print_error(message):
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(f'[{colorama.Fore.RED}-{colorama.Style.RESET_ALL}] {colorama.Fore.LIGHTBLACK_EX}{timestamp}{colorama.Style.RESET_ALL} | {message}')
def print_success(message):
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(f'[{colorama.Fore.GREEN}+{colorama.Style.RESET_ALL}] {colorama.Fore.LIGHTBLACK_EX}{timestamp}{colorama.Style.RESET_ALL} | {message}')
@bot.event
async def on_ready():
print_info('Bot is ready')
@bot.command()
async def test(ctx):
print_success("Works")
await ctx.send("works")
bot.run('tokenlol')
is this not right???
@limber urchin @silver moat help me figure this out for a dollar
nvm
if I have a view class, how can i add a modal class item to it ?
You can't add a modal to a view 
A view has buttons, select menu etc which can be sent on a message.
A modal is sort of a user input form. Those aren't related
How much ram is sufficient for hosting a bot?
My bot is on a 5k + member server and does alot of storing and stuff
and what vps are the cheapest options?
I was asking about select menu. My brain was processing things regarding modal, so accidently asked abt it. I meant select menu
So you mean a Menu to a Modal?
Depends on what your bot is doing. 2-4GB should be enough for just about anything.
I recommend looking at GalaxyGate, DigitalOcean or Vultr, but that's only to name a few. Do your own research on what server suits you best.
A Raspberry Pi is also great for that
And if by "does alot of storing" you mean storing things in a database. RAM has nothing to do with that, you want to look at disk space
Uh...forget what I said
My question is: How can i add a "Select Menu" to a view "class" ?
I have the Select menu class ready
just need to add it
The same like a button
Can anyone help me and know what I am doing wrong or how to solve it correctly? 🙂
Thx, also do you know how to make smt like this-
How can i get live aware time smt like ends in 5 mins, ends in 2secs etc.
?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.
If you have subclassed select menu then yes
You can also use this ⬇️
.rtfm utils.format
if ur a student, you can ask for your github student pack. Once you got it, you basically have a free vps with digital ocean (100 or 200$ free credit that u can use for a vps)
hmm ill look into it thans
can i get this same type of interface with my discord bot? I feel like i saw it somewhere but can't find it in the documnetation
my idea is to get a from-to date using slash commands
not possible in discord (yet)
accept string and parse it. that should be your best option rn
alright, thanks
Does anyone know how to put that in a bot message or about me?
?tag slashcommandmention
</full name:ID>
Hello, what i do wrong?
Why pycord dont install?
I use pjcharm and windows
try py -m pip install py-cord or python -m pip install py-cord
thanks
The print works, I can also create the paginator with the view but when I restart the bot the paginator still does not work.
@commands.Cog.listener()
async def on_ready(self):
if not self.persistent_views_added:
self.bot.add_view(await PaginatorInfoView(self.bot))
print("Views added")
self.persistent_views_added = True```
```py
class SpotDetails(discord.ui.View):
def __init__(self, bot):
super().__init__(timeout=None)
self.bot = bot
self.message_details = []
self.custom_id = 'spot_details_view'```
Paginatorclass:
```py
async def __init__(self, bot: discord.Bot):
self.bot = bot
self.pages = await self.update_pages()
view = await self.generate_view()
super().__init__(pages=self.pages, custom_view=view, timeout=None, author_check=False)
async def generate_view(self):
view = SpotDetails(self.bot)
return view```
View doesn't have a custom id
Does the paginator have a custom id? 🤔
Unfortunately I can't add a custom_id here, it doesn't exist in the Paginator class. 😬
def __init__(self, bot: discord.Bot):
self.bot = bot
self.pages = await self.update_pages()
view = await self.generate_view()
super().__init__(pages=self.pages, custom_view=view, timeout=None, author_check=False)```
You can use buttons for it. But there's a slight issue. You can then only have 25 days for 25 buttons (maximum amount) after which you gotta figure out what you can do...
what?
Doesn't anyone know how I can make a Paginator persistent? 🙄
The same like a button
I have my Paginator class but when I want to add a custom_id here I always get the error message that Paginator does not have a custom_id 🤔
class PaginatorInfoView(Paginator):
def __init__(self, bot: discord.Bot):
self.bot = bot
self.pages = await self.update_pages()
view = await self.generate_view()
super().__init__(pages=self.pages, custom_view=view, timeout=None, author_check=False)```
Why do you need a custom id on your paginator class?
Because I want to make the Paginator persistent 🙄
That is not how you make the paginator persistent
Here I create my Paginator with the command and call the Paginator class here and then send it to the channel:
@commands.command(name="showspot", help="Zeigt alle Spots an")
async def page(self, ctx):
paginator = await PaginatorInfoView(self.bot)
await paginator.send(ctx)```
When I try this to make the paginator persistent I always get the error that there is no custom_id....
```py
@commands.Cog.listener()
async def on_ready(self):
if not self.persistent_views_added:
self.bot.add_view(await PaginatorInfoView(self.bot))
print("Views added")
self.persistent_views_added = True```
Yes? Because the paginator class doesn't have anything called custom_id
But then how can I make the Paginator persistent?
Same as you would for a normal view, give the components custom IDs and initialize on your bot startup
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/dropdown.py at master · Pycord-Development/pycord
But I use the standard Paginator buttons which have no custom_id or?
Then give them a custom id
How can I do that? 😯
Why do I get: AttributeError: 'str' object has no attribute 'name'
code?
1s
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I have opened a post with my code then maybe it is easier.
Maybe someone could look in there and help me there how I do the whole thing correctly 🙂
Can't seem to figure out why it doesn't work lol
Have ya found anything in that?
Automod rule's name
so you dont have to use .name?
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 ...
Wdym
I use it to check if the name is as the one I want
oh, AutoModRule
Yeah
what is rules returning?
wym
oh shoot
its automoderation in pycord
Should return a list of AutoModRule objects https://neil.hrzn.pics/Xv8Zu51h7V.png
is the list empty?
Might be
But that error is on startup, not when I run the command
at which line is the error?
That's what I can't find out File "/home/container/.local/lib/python3.10/site-packages/discord/enums.py", line 786, in from_datatype if datatype.__name__ in ["Member", "User"]: AttributeError: 'str' object has no attribute '__name__'. Did you mean: '__ne__'?
File "/home/container/.local/lib/python3.10/site-packages/discord/cog.py", line 786, in _load_from_module_spec
setup(self)
File "/home/container/cogs/antiping.py", line 127, in setup
bot.add_cog(AntiPing(bot))
File "/home/container/.local/lib/python3.10/site-packages/discord/cog.py", line 656, in add_cog
cog = cog._inject(self)
File "/home/container/.local/lib/python3.10/site-packages/discord/cog.py", line 548, in _inject
command._set_cog(self)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 603, in _set_cog
self.cog = cog
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 830, in cog
self._validate_parameters()
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 708, in _validate_parameters
self.options: list[Option] = self._parse_options(params)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 748, in _parse_options
option = Option(option)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/options.py", line 225, in __init__
self.input_type = SlashCommandOptionType.from_datatype(input_type)
File "/home/container/.local/lib/python3.10/site-packages/discord/enums.py", line 786, in from_datatype
if datatype.__name__ in ["Member", "User"]:
AttributeError: 'str' object has no attribute '__name__'. Did you mean: '__ne__'?
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/bot.py", line 28, in <module>
load_cogs()
File "/home/container/bot.py", line 23, in load_cogs
client.load_extension(f"cogs.{file[:-3]}")
File "/home/container/.local/lib/python3.10/site-packages/discord/cog.py", line 910, in load_extension
self._load_from_module_spec(spec, name)
File "/home/container/.local/lib/python3.10/site-packages/discord/cog.py", line 791, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.antiping' raised an error: AttributeError: 'str' object has no attribute '__name__'``` it happens on setup but I doubt that
he can use:
5 buttons in each row - 5 days
and repeat this for 25 times using numpy
but for the rest 5, he gotta figure out himself what he can do
do you still get it if you dont load the cog?
I don't
since, uhm he can not use more than 25 buttons
uh ye, that is a Discord Limit not a py-cord limit
The error is simple, the thing that's returned is string not a class object. you should try to print first what's being returned then debug and modify code accordingly.
Where is it returned though
can you do a copy of the file and save it and delete like some lines of codes for testing to see at which line it is
Where, inside the class, in the setup func?
just print (datatype)
before you are doing that check
right before it
NameError: name 'datatype' is not defined
?
I could but like uhm
sure lets do that
It happens in the command
I removed the whole command and it works
Just wondering but is it possible to have a slash command without named arguments? This just returns 'NoneType' object has no attribute 'content' even though I have all possible intents and permissions. It's an example in the docs (https://docs.pycord.dev/en/stable/faq.html#how-do-i-get-the-original-message), no idea what I'm doing wrong
@bot.command
async def whatever(ctx):
await ctx.respond(ctx.message.content)
dont delete anything
only a few lines everytime
to test it
why dont I add print statements every few lines
to see where the error occurs, and then we can do the deletion
because deleting straight up gives me errors
its @bot.slash_command
not bot.command
doesnt matter
?
only if you use commands.Bot
yeah...
It doesn't work either way
you are not sending a message?
Oh wait, you have to use commands.Bot for this?, won't work with discord.Bot?
it should
but I prefer commands.Bot
if you use discord.Bot you can stay with bot.command
debug just cant import anything from my utils folder so
mhm
what do I do lol
helppp
I fixed it somehow
it was something with cog loading ig
this is literally all I'm trying to run now, doesn't work, bot has all perms and intents on the dev page too 
from discord import Bot, Intents
bot = Bot(intents = Intents.all())
@bot.command()
async def echo(ctx):
await ctx.respond(ctx.message.content)
bot.run("TOKEN")
await ctx.respond(ctx.message.content)
AttributeError: 'NoneType' object has no attribute 'content'
must be doing something really stupid here
read the error
both message and content are None
can you just send a message?
yeah it works eg with await ctx.respond("test")
do you know basic python?
to an extent, yes
yes, this is just a simple example I'm trying to debug
It looks like that you dont know the basic of it...
Slash commands don't have a message
There's no message that triggered the slash command
sorry but I really don't see what's wrong with this? Not sure what you mean by basics here, I can see the error but it doesn't help, the message just doesn't exist
oh, that makes sense, so do I need a named argument for this?
Alright, thanks.. I was just hoping to be able to pass a message to the command like /chat message without having to specify /chat message:message
Then where would you type the message if there's no option lol
I guess I was confused since discord lets me send the command without any warnings
Hey ya'll whenever I try to make a discord.AutoModAction object, it requires me to pass in metadata but I'm trying to block the message, and there is no meta data for that. So what should I do?
you can use message commands
in the context menu
why do you want to create that object yourself? 
I want to create a auto mod rule
ah hmm
r = await guild.create_auto_moderation_rule(
name="Anti Ping",
event_type=discord.AutoModEventType.message_send,
trigger_type=discord.AutoModTriggerType.keyword,
trigger_metadata=discord.AutoModTriggerMetadata(keyword_filter=members),
actions=[discord.AutoModAction(action_type=discord.AutoModActionType.block_message)],
enabled=True,
reason=f"Blacklist role {role.name} ({role.id}) from being mentioned",
exempt_roles=([exempt] if exempt is not None else []) # type: ignore
)```
thats my code ^
pass AutoModActionMetadata ig
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: AutoModActionMetadata.to_dict() missing 1 required positional argument: 'self'
rtfm cmd gave wrong output
I passed in AutoModAction()?
create an object of it AutoModActionMetadata()
ye
bruh Application Command raised an exception: TypeError: AutoModRule.__init__() got an unexpected keyword argument 'reason
oh wait I just remove that
Welp
ill make a pr
ty lol but gonna take ages to be accepted prob
you can edit it yourself for now
what do i do lol
can u make a pr ill just copy paste the edits
- return AutoModRule(state=self._state, data=data, reason=reason)
+ return AutoModRule(state=self._state, data=data)
alr
in create_auto_moderation_rule
yeah Im already there
how do I do that in a pterodactyl container lol
uh. probably check where the library is stored
welp idk about that
another complicated way would be creating a fork and using it
plannned on doing that
whoop
site-packages found
ayye nice
FOUND IT
@proud mason May have found another bug ```discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'AutoModRule' object has no attribute 'trigger'
nvm its not
ypeyep
oops
Works like a charm
cool
@bot.event
async def on_voice_state_update(member, before, after):
vc = bot.get_channel(channel_IDVC3)
if before.channel is None and after.channel is not None:
tab = list(filter(lambda m: m.voice, member.guild.members))
print(len(tab))
await vc.edit(name=f"Voice: [{len(tab)}]")
if before.channel is not None and after.channel is None:
tab = list(filter(lambda m: m.voice, member.guild.members))
print(len(tab))
await vc.edit(name=f"Voice: [{len(tab)}]")
it doesn't change the channel name but it prints the right number of users
print vc and see what it is
it prints 1 when I join and then 0 when I leave
oh wait
"Voice: [0]"
the channel name
hmm
and does the bot have perms to edit the channel?
How do I check if a member has got a higher role than another member?
I am trying to create a kick/ban command, and I want to prevent lower-ranked staff to ban higher-ranked staff.
I know you can check what permissions a member with member.guild_permissions.permission
Nevermind, just found out you can compare Member.top_role
if not evoker.guild_permissions.kick_members:
await ctx.response.send_message('You do not have permission to kick members!', ephemeral=True)
return
if evoker.top_role <= affected.top_role:
await ctx.response.send_message(f'That member has a higher permission level than you!', ephemeral=True)
return
if self_member.top_role <= affected.top_role:
await ctx.response.send_message(f'The bot does not have a high enough permission level to kick that user.', ephemeral=True)
return
How would shorten this code, as it gets kind of repetitive when writing commands. (It checks if a member has a permission + got a higher role than another + the bot can kick the member)
Well, you can't really shorten it. But you could move to a function and use that in every command. Or even better, make it a decorator.
is it possible to send a channel select menu with some values preselected?
if not, what is the best way to achieve this?
If I save a message e.g. message = await interaction.channel.send() and then edit the message at some point with await message.edit().
Do I then have to save the message again or does the data remain so that I can edit the message again later?
So do I then have to make message = await message.edit() and save message again or would that be superfluous?
.tias
I got a discord music bot with buttons (pause, skip, resume, stop) and after 5-7 minutes the buttons just stop working.
How can I fix this
Hello guys. I wanted to ask, if you click on the menu options, then a role is issued, and if you click on it, then the role is deleted, can you do this?
How do you expect anyone to help you if you don't show your code?
@discord.ui.button(label="Skip", style=discord.ButtonStyle.primary)
async def skip_callback(self, button, interaction):
embed = discord.Embed(
description=f"⏩ Song has been skiped!",
color=discord.Color.blue()
)
await interaction.response.send_message(embed=embed)
vc = bot.voice_clients
vc[0].stop()
@discord.ui.button(label="Pause", style=discord.ButtonStyle.success)
async def pause_callback(self, button, interaction):
embed = discord.Embed(
description=f"⏸ Song has been paused!",
color=discord.Color.blue()
)
vc = bot.voice_clients
vc[0].pause()
await interaction.response.send_message(embed=embed)
@discord.ui.button(label="Resume", style=discord.ButtonStyle.success)
async def resume_callback(self, button, interaction):
embed = discord.Embed(
description=f"⏭ Song has been resumed!",
color=discord.Color.blue()
)
await interaction.response.send_message(embed=embed)
vc = bot.voice_clients
vc[0].resume()
@discord.ui.button(label="Stop", style=discord.ButtonStyle.danger)
async def stop_callback(self, button, interaction):
embed = discord.Embed(
description=f"⏹ Song has been stopped!",
color=discord.Color.blue()
)
await interaction.response.send_message(embed=embed)
vc = bot.voice_clients
vc[0].stop()
...Here just music command (cant send it cause messgae would be to long)
await ctx.respond(embed=embed, view=PlayControlsView())```
But this would be the play command
async def play(ctx, *, query):
voice_client = ctx.voice_client
if voice_client is not None:
if voice_client.channel != ctx.author.voice.channel:
return await ctx.send("You must be in the same voice channel as the bot!")
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': 'bestaudio',
}],
'download_archive': 'download_cache.txt',
'limit_rate': 10 * 1024 * 1024
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
result = ydl.extract_info(f"ytsearch1:{query}", download=False)
url = result['entries'][0]['url']
thumbnail_url = result['entries'][0]['thumbnail']
voice_channel = ctx.author.voice.channel
vc = bot.voice_clients
if vc:
vc[0].play(discord.FFmpegPCMAudio(url))
vc[0].source = discord.PCMVolumeTransformer(vc[0].source)
vc[0].source.volume = 0.07
await ctx.send(f"Now playing: {result['entries'][0]['title']}")
else:
vc = await voice_channel.connect()
vc.play(discord.FFmpegPCMAudio(url))
vc.source = discord.PCMVolumeTransformer(vc.source)
vc.source.volume = 0.07
embed = discord.Embed(title = f"🎵 LunarBot - New Song Selected", description = f"", color = discord.Color.blue())
embed.add_field(name = '', value = f"{ctx.author.mention} has selected **{result['entries'][0]['title']}** to play next!", inline = True)
embed.set_thumbnail(url=f"{thumbnail_url}")
embed.set_footer(text = f"🎧 Input: ")
await ctx.respond(embed=embed, view=PlayControlsView())```
You need to set the timout of the View to None, otherwise it will timeout after 3 minutes
thank you!
And next time read #help-rules. Keep your issues in one place
!
try it yourself and see
How? Let me explain. I made a menu for issuing a role. I press the trace, it gives out the role, and if again, then it is a reception. I looked in the documentation on the site - no. I demand your help, dear and experienced athletes.
What?
So within on_application_command_error, we're passed in an Exception
How can I get just the file (without path, preferably) and line that the exception was specifically generated from?
I've tried several ways using sys.exc_info() (which is None when in the exception handler) or traceback and I can't seem to get ahold of what I want
error.__traceback__?
I mean, it contains an object. But the current frame context is the error handler, not the source of the error
traceback.format_exception(type(error), error, error.__traceback__) at least includes the source of the error, but still provides the error handler context, which I don't care about.
Not sure why it's so difficult just get the file and line number (e.g. mycog.py:1234) that caused the error 😕
convert it to a string and parse it
ooh, traceback.extract_tb(error.__cause__.__traceback__) at least drills down to a more useful list.
hi
i want to put @commands.has_role('admin') in every command of adminstuff class without manually adding them in the code
is it possible?
class adminstuff(commands.Cog):
...
@commands.command()
@commands.has_role('admin') #this
async def cmd1(self, ctx,):
...
@commands.command()
@commands.has_role('admin')
async def cmd2(self, ctx,):
...
@commands.command()
@commands.has_role('admin')
async def cmd3(self, ctx,):
...
#more commands
Why do you not want to add them manually?
There comes a point in your bot’s development when you want to organize a collection of commands, listeners, and some state into one class. Cogs allow you to do just that. The gist: Each cog is a P...
Can you do a case-insensitive search with discord.utils.get? Didn't see anything in the docs
just make your own, it's open-source
So... "The library does not provide a case-insensitive search".
precisely
use utils.find instead
you pass in your own lambda function which you could make a case-insensitive search with
(also fwiw find is similar to python's filter, but it only returns one result like get)
can you make a dashboard with the modal?
would be interesting without hosting a website
quick
very, quick question
if message.channel.id == int(rep_secrets["channel_verify"]):
role = message.guild.get_role(int(rep_secrets["role_verified"]))
await message.author.add_roles(role, reason="Verification.")
await message.add_reaction(":white_check_mark:")
the role isnt being added
the if clause runs
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10011): Unknown Role
ok nvm imma start a thread
How to set a description for a slash option that is using discord.User type hinting?
async def command(ctx, user: discord.User)```
use @option decorator
Here's the slash options example.
okay
Hey, i'm trying to work on an autocomplete, but the things I came across only allow me to return one option. Is there a way to return a list of strings as options for the autocomplete to show ?
TypeError: BotBase.add_command() missing 1 required positional argument: 'command'
Bro wtf this error for discord.py on slash command error
can anyone help me (FAST AS POSSIBLE)
you are in fact supposed to return a list of strings
Here's the slash autocomplete example.
have you seen that
this py-cord server
not discord.py
if you meant py-cord then show full error
also send relevant code
ok wait a second
When do I change this somehow so that I can specify a specific role and not just administrator?
@discord.default_permissions(administrator=True)```
@bot.add_command()
async def mute_voice(ctx, member: discord.Member):
await member.edit(mute=True)
await ctx.send(f"{member.mention} has been muted in voice channels.")
the code and the error
.
it should @bot.command()
what bot class are you using?
if you havent used the library before, make sure to read the whole guide
.guide
then @bot.slash_command
not pycord
bruh
wait a second then
dpy uses a different implementation of slash cmds
this was for pycord
google?
check on their github or docs
i found it thanks
Hi, I previously asked on preventing users from using slash commands in a blacklist system (https://discord.com/channels/881207955029110855/1036877530633863168).
It works, but is there a way to to do the same thing for Views or any button/select/modal interaction? Or would I have to implement a interaction_check for all those views?
Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.
