#Basic Pycord Help (Quick Questions Only)
1 messages · Page 42 of 1
So when im defining the perms like
perms = chat.overwrites_for(ctx.guild.default_role);perms.send_messages=False
How can I define multiple roles?
Without duplicating lines twice
I wanna change the permission for 2 roles
You can just loop over the roles
If I change the permission for "send-messages" do I have to manually define all the other perms?
It seems when I change the perm it removes all existing perms.
@commands.command()
async def test(self, ctx):
await ctx.message.delete()
casino = self.bot.get_channel(mpcasinoid)
overwrite = discord.PermissionOverwrite()
overwrite.send_messages = False
await casino.set_permissions(ctx.guild.get_role(976315422708228107), overwrite=overwrite)```
This works but I got a problem. It's not keeping the current permissions it's updating the send_messages perm and removing the others.
Hmm. I don't get how to keep the existing perms.
wait that's a slash command?
You're not "updating" any permissions, you're setting new permission overrides for the role, so obviously it's not going to keep the others. To "keep" the other permissions you would have to fetch them first and merge your new permission value to them.
issue already resolved.
huh?
oh yeah resolved in DMs
oh, okay
My bot printed this
Could someone help me understand what this is saying and how can i fix it if it needs any fixing?
Hey people! I'd like to ask a question concerning cogs and the default help command(the output is what I'm talking about here).
When using cogs(by inheriting commands.Cog), and extending the class by adding a few methods(adding commands, @commands.command();async def....), the default help command(which is DefaultHelpCommand) will format the commands like the image below:
My goal is to not want that happen, what I wish is that the commands in snipe (snipe is a class, one of the cogs), to be mixed with others(initially no_category but I changed it to others).
Can I achieve this without inheriting and extending the HelpCommand?
i don't think you can do that without inheritance
So I have to manually inherit the help command to achieve this?
yeah, this way you can customize it better iirc
Thank you!
might be helpful tho
Thanks for the reference.
You created a ClientSession, made a request but never closed the session.
How do we close it?
session.close()
My code is as follows:
import asyncio
import aiohttp
urls = [
'http://www.163.com/',
'http://www.sina.com.cn/',
'https://www.hupu.com/',
'http://www.csdn.net/'
]
async def get_ur...
Oh
Thanks, but i never import that aiohttp package in my code?
And I'm not really sure where I'm creating that session in my code
Is it something happening in the background?
Latest
Are you overriding the close method on the bot?
Just a second please
Oh god save me
I'm basically trying to fetch new posts from certain subreddits and send to discord
Why you're doing stuff on on_ready and why a WHILE loop
I'm sorry I'm not very good at programming with async or programming in general. Where else can i put it? And i need an infinite while loop to keep checking for new posts
If you're not good at programming or with async stuff. Then refer to #help-rules 1
Well
Second, py-cord has a tasks extension which can do that or you can use asyncio itself
Here's the background task example.
I go to learn async and they say make something with it, i make something with it and you guys say go back and learn it first
Good while loop going on there
But thanks for the example
A Discord bot is no simple thing to start with
Hey is there a way to suppress link embed preview on sending message ?
<link>
?
Just like that... add <> around the link.
ah ok 🙂 thx
Is it possible to disable the keyboard input for slash commands with autocomplete so that you can only select values from the list that are predefined?
So if for $var1 [1 , 2 , 3 , 4] are available, that you can not enter a 5 via keyboard?
Yeah.
number: discord.Option(int, "Select a number from the provided list", choices=[1, 2, 3, 4])
Here's how I have it:
art = ["Raub", "Überfall"]
@staticmethod
def artAutocomplete(self: discord.AutocompleteContext):
return art
@option("art",description="Welche Art wurde durchgeführt?",autocomplete=artAutocomplete)
async def bank(self, ctx: ctx_parse, art: str):
await ctx.respond(f"{art}")
And would like that only the two options are selectable and one can enter no other values.
Do you have an example?
Literally what I provided here lol
But I have 4 variables in a row
/bank var1 var2 var3 var4
How that matters?
This is my whole code and there I want that the variables that have a default can't accept keyboard input anymore but only the selection from the list.
That's what literally the choices kwarg does
Provide the list in all options
And that's it. Don't know what you don't understand about it
And there's no reason to use autocomplete because you don't need to dynamically provide options.
was zum geier wird das haha
Hey people! Me again. I have a question whether it is possible to access discord.ClientUser in another file without cogs.
Imagine a file named echo.py with a simple function in it used to output arguments.
from discord.ext import commands
@commands.command()
async def echo(ctx, *arg):
arg = ' '.join(arg)
await ctx.send(f"out: \`\`\`\n{arg}\n\`\`\`")
def setup(bot):
bot.add_command(echo)
(You'd then load this with the load_extension() function in other files)
I can't seem to find a way to make this possible(to access the properties in discord.ClientUser, like bot.user.id, bot.user and etc) without the help of cogs(in cogs, you'd normally use self to access these(self.user.id, self.user and etc.).
Habe den Ansatz nun von dark verstanden. Gibt es da irgendwie die Möglichkeit wenn ich bei Art: Raub auswähle, dass locationb erst gar nicht angezeigt wird?
async def setglobal(self, ctx, art: Option(str, "Select a number from the provided list", choices=["Raub", "Überfall"]),
locationa: Option(str, "Select a number from the provided list", choices=["Mond", "Erde"]),
locationb: Option(str, "Select a number from the provided list", choices=["Erde", "Mond"]),
number: Option(int, "Select a number from the provided list", choices=[1, 2, 3, 4])):
Nope
Ignorier den Input einfach und setz die restlichen Optionen auf optional.
Okay.
Und ist es möglich das man noch Inputs hinzufügt ohne vorgegebene Options sondern mit Tastatureingabe?
Müsste. Kann aber nicht mehr helfen. Wechsel mal zurück auf englisch.
Anyone free?
You can make a _init_ function in the cog class. The bot instance is passed to this.
def __init__(bot):
self.bot =bot
no codeblock?
I tried :(
So I need to use cogs for this?
I don't think you understand my point here
My point is not to use cogs to achieve this
you should use cogs to have a clean code
I understand your point, but it is possible to not use cog? To access the methods of discord.ClientUser.
why should it not possible to access it?
Look at the code above.
Not to suggest it is impossible, if it is possible. Is there any way?
Without the help of cogs, no cogs or inheritance involved.
do you know basic python?
What are you implying? Yes, I know the basics well.
You should know the basics of python and OOP before using py-cord.
Good lord. Ok. Nevermind then, thanks for all the help. I appreciate it.
Why does the selection not work with autocomplete. If I have e.g. house in the list and then type in the field hou then all options are still shown and not only all with hou 🤔
Sorry I read the question wrong. You should be able to import the bot instance into other classes.
bot = discord.Bot()
from main import bot
What's your autocomplete function
Can you show your code for autocomplete?
I'm expecting to get a list of banned users in the last hour in _ub, is there something I don't understand or am I doing wrong?
art = ["Raub", "Überfall"]
locationa = ["Mond", "Erde"]
@staticmethod
def locationbtypeAutocomplete(self: discord.AutocompleteContext):
chosen_art = self.options["art"]
match chosen_art:
case "Überfall":
return ["Erde", "Mars", "Pluto", "Mond"]
case "Raub":
return ["NONE",]
case _:
return ["Error"]
@slash_command(description="Das ist ein Test")
async def setglobal(self, ctx : ctx_parse, art: Option(str, "Select a number from the provided list", choices=art),
locationa: Option(str, "Select a number from the provided list", choices=locationa),
locationb: Option(str, autocomplete=locationbtypeAutocomplete),
number: Option(int, "Select a number from the provided list", choices=[1, 2, 3, 4]),
player: Option(str,"Trage hier den Namen des Spielers ein")):
await ctx.respond(f"Die Einstellungen für {number}")
@discord.ui.button(label="Close Ticket",style=discord.ButtonStyle.red, emoji="❌")
async def button_callback(self,ctx,button, interaction):
await self.fetch_channel(NewChannel)
await interaction.guild.delete(NewChannel)
class Support(discord.ui.View):
@discord.ui.button(label="General Support",style=discord.ButtonStyle.success, emoji="📄")
async def button_callback(self,button, interaction: discord.Interaction ):
category = interaction.client.get_channel(1052267160724049970)
global NewChannel
NewChannel = await interaction.guild.create_text_channel(name=f"Ticket ",category=category)
await NewChannel.send(embed = StartMsg, view=NewButtons())``` No error, Im trying to delete the channel once the button is clicked
You're returning the list as is
?
How can I fix the problem?
Check if the content is in the list and return the items that contain it
class MyModal(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(
discord.ui.InputText(
label="Discord Name & Tag Ex: Bob#3456",
placeholder="Please put your discord ID",
),
discord.ui.InputText(
label="How old are you?",
placeholder="Please put your age!",
),
discord.ui.InputText(
label="Country & Time Zone",
placeholder="Please put your Country & Time Zone",
),
discord.ui.InputText(
label="Job/Education Status",
placeholder="Please put your job or education",
),
discord.ui.InputText(
label="Please provide an about you [ 150 words ]",
placeholder="Please fill this out fully!",
style=discord.InputTextStyle.long,
),
*args,
**kwargs,
)
async def callback(self, interaction: discord.Interaction):
channel = bot.get_channel(STAFF_APP_LOGS)
staff_embed = discord.Embed(
title="Your Staff Application",
fields=[
discord.EmbedField(
name="Discord Tag", value=self.children[0].value, inline=False
),
discord.EmbedField(
name="Age", value=self.children[1].value, inline=False
),
discord.EmbedField(
name="Country/Timezone", value=self.children[2].value, inline=False
),
discord.EmbedField(
name="Job/Education", value=self.children[3].value, inline=False
),
discord.EmbedField(
name="About You", value=self.children[4].value, inline=False
),
],
color=discord.Color.random(),
)
await channel.send(embed=staff_embed)```
Need help getting this in my staff application logs channel.
Do you have an example?
class NewButtons(discord.ui.View):
@discord.ui.button(label="Close Ticket",style=discord.ButtonStyle.red, emoji="❌")
async def button_callback(self,button, interaction: discord.Interaction):
await self.fetch_channel(NewChannel)
await interaction.guild.delete(NewChannel)```
Traceback (most recent call last):
File "C:\Users\Wacky\Documents\FoolishBot\.venv\Lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: NewButtons.button_callback() missing 1 required positional argument: 'interaction'
Here's the slash autocomplete example.
slighly updated code
@green hinge
ctx?
I added ctx tryna fix it
Buttons don't receive ctx
Edited
Then try again
dark, Can you help me with my question, please?
.
You never provided errors or what's not working
Ctx removed, No error no fixed
What the hell is self.fetch_channel
And interaction.guild.delete?
You're getting the channel from the cache, and it's not cached.
... an attempt to fetch the new channel i created then delete it once close ticket is clicked
.rtfm fetch_channel
i believe i am getting the channel
And wheres NewChannel defined?
How would i fetch(or get) the channel i just created though? as i wont have a pre-set ID or name (as its going to have a new name each time)
1 sec
You have to fetch it. Its not cached.
class Support(discord.ui.View):
@discord.ui.button(label="General Support",style=discord.ButtonStyle.success, emoji="📄")
async def button_callback(self,button, interaction: discord.Interaction ):
category = interaction.client.get_channel(1052267160724049970)
global NewChannel
NewChannel = await interaction.guild.create_text_channel(name=f"Ticket ",category=category)
await NewChannel.send(embed = StartMsg, view=NewButtons())```
ay okay
That's another class?..
Another class for something else
Do you realize classes don't share variables
I remember I told you to pass the channel into the NewButtons init and then use it in the class
yeah then i thought i had a better way 💀
sorryyy
channel = bot.get_channel(STAFF_APP_LOGS)```
this isnt getting the channel?
How would i do this sorry?
class NewButtons(discord.ui.View):
def __init__(self, channel):
super().__init__()
self.channel = channel```
Then when you send the view:
await NewChannel.send(embed=..., view=NewButtons(NewChannel))```
You're indeed getting it. But if it's not cached, it'll return None and you'll have to fetch it.
Get and fetch mean two different things here.
how would I d this? im moving from discord.py to pycord so
The Get function gets the channel from the bot cache. The fetch function makes an API call
and i was just doing simple embed on prefixed commands.
You could also try
channel = interaction.guild.get_channel(STAFF_APP_LOGS)```
thanks ❤️
Have i messed up here dark?
class NewButtons(discord.ui.View):
def __init__(self, NewChannel):
super().__init__()
self.channel = NewChannel
@discord.ui.button(label="Close Ticket",style=discord.ButtonStyle.red, emoji="❌")
async def button_callback(self,button, interaction: discord.Interaction):
await self.fetch_channel(NewChannel)
await interaction.guild.delete(NewChannel)``` The button no longer shows but im unsure what i did wrong
Do i need to change it to self.channel.fetch.channel or smth?
You indented it inside the init function
And you don't even need to fetch the channel now. You already have a channel object stored.
You just do await self.channel.delete()
Oh thank you
Consider reading the docs because you're making up functions or attributes that don't exist.
same error as before. Could it be how im sending the embed?
await channel.send(embed=staff_embed)
im pretty sure it is
No
mhm ok
its my config
TICKET_CHANNEL = config.TICKET_CHANNEL #Ticket Pan Channel
MEMBER_ROLE_ID = config.MEMBER_ROLE_ID
CATEGORY_ID1 = config.CATEGORY_ID1 #Support1 Channel
CATEGORY_ID2 = config.CATEGORY_ID2 #Support2 Channel
CATEGORY_ID3 = config.CATEGORY_ID3
CATEGORY_ID4 = config.CATEGORY_ID4
CATEGORY_ID5 = config.CATEGORY_ID5
WELCOME_LOGS = config.WELCOME_LOGS
STAFF_APP_LOGS = config.STAFF_APP_LOGS
TEAM_ROLE1 = config.TEAM_ROLE1 #Permissions for Support1
TEAM_ROLE2 = config.TEAM_ROLE2 #Permissions for Support2
LOG_CHANNEL = config.LOG_CHANNEL #Log Channel
TOKEN = config.TOKEN```
What's in the variable
an ID
Is it an int
Then try this
channel = bot.get_channel(STAFF_APP_LOGS)
channel = await bot.fetch_channel(STAFF_APP_LOGS) if channel is None else channel```
thx
The interaction is needed at the start as its a button right? Hasnt worked though
await interaction.self.channel.delete()
Ohh yeah
That hasnt fixed it
I dont see whats causing it
As theres no error to help me
def __init__(self, NewChannel):
super().__init__()
self.channel = NewChannel
@discord.ui.button(label="Close Ticket",style=discord.ButtonStyle.red, emoji="❌")
async def button_callback(self,button, interaction: discord.Interaction):
await self.channel.delete()
class Support(discord.ui.View):
@discord.ui.button(label="General Support",style=discord.ButtonStyle.success, emoji="📄")
async def button_callback(self,button, interaction: discord.Interaction ):
category = interaction.client.get_channel(1052267160724049970)
NewChannel = await interaction.guild.create_text_channel(name=f"Ticket ",category=category)
await NewChannel.send(embed = StartMsg, view=NewButtons(NewChannel))``` if you want full file i can send
Ignoring exception in view <MyView timeout=None children=1> for item <Select type=<ComponentType.string_select: 3> placeholder='Choose a Ticket option' min_values=1 max_values=1 options=[<SelectOption label='Support' value='support1' description=None emoji=None default=False>, <SelectOption label='Player Reports' value='support2' description=None emoji=None default=False>, <SelectOption label='VPN Whitelist' value='support3' description=None emoji=None default=False>, <SelectOption label='VIP/Payment Issues' value='support4' description=None emoji=None default=False>, <SelectOption label='Staff Application' value='support5' description=None emoji=None default=False>, <SelectOption label='Ban Appeal' value='support6' description=None emoji=None default=False>] channel_types=[] disabled=False>:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ui/view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "/home/container/main.py", line 283, in callback
await interaction.response.send_message(embed=embed, ephemeral=True)
File "/home/container/.local/lib/python3.10/site-packages/discord/interactions.py", line 765, in send_message
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
Ignoring exception in modal <__main__.MyModal object at 0x7fecc6e8e170>:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ui/modal.py", line 341, in dispatch
await value.callback(interaction)
File "/home/container/main.py", line 385, in callback
channel = await bot.fetch_channel(STAFF_APP_LOGS) if channel is None else channel
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 1628, in fetch_channel
data = await self.http.get_channel(channel_id)
File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 360, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access```
Looks like missing permissions, could be wrong
the bot has admin
nvm then
your good ❤️
thanks tho
np
?
Trying to make a quick slash command but for some reason the bot isn't accepting any arguments when the command gets run?
import discord
bot = discord.Bot()
@bot.slash_command(guild_ids=[513201373169319937])
async def chat(ctx, message):
print(message)
bot.run(open('token.tok','r').read())
```Terminal only shows "None" whenever the command is run. Any help would be appreciated!
Ehm just try typing a message after chat
So /chat hello then enter
?
same result
ctx.respond("the content")
async def say(self,ctx,message):
await ctx.defer()
message = discord.utils.escape_mentions(message)
await ctx.respond(message)``` Heres my old code for this (updated though) 3rd and 4th line isnt needed
well yeah but their printing the result
so wouldnt it be fine without that?
dont use self if its not in a cog
In my case it was a cog, sorry forgot to tell them its in a cog for me
Here's the slash basic example.
@frozen holly ^
May you help me?
class NewButtons(discord.ui.View):
def __init__(self, NewChannel):
super().__init__()
self.channel = NewChannel
@discord.ui.button(label="Close Ticket",style=discord.ButtonStyle.red, emoji="❌")
async def button_callback(self,button, interaction: discord.Interaction):
await self.channel.delete()
class Support(discord.ui.View):
@discord.ui.button(label="General Support",style=discord.ButtonStyle.success, emoji="📄")
async def button_callback(self,button, interaction: discord.Interaction ):
category = interaction.client.get_channel(1052267160724049970)
NewChannel = await interaction.guild.create_text_channel(name=f"Ticket ",category=category)
await NewChannel.send(embed = StartMsg, view=NewButtons(NewChannel))``` It isnt deleting the channel, no error either
so i have to put ctx: discord.ApplicationContext instead of just ctx? that seems to have been the issue
kinda weird 
thanks for the help!
Any clue? been working on this for ages
you have two times the same button_callback()
Oh didnt notice that
This hasnt fixed it but i renamed it
can you do try and except?
Soo? try:
(channel delettion code)
except:
??
except Exception as e
print(e)
zervyrel can you help with this please and thank you ❤️
async def delete_channel(self,button, interaction: discord.Interaction):
try:
await self.channel.delete()
except Exception as e:
print(e)``` this?
It could be an ident thing
like that yes
so now test?
the error tells you what is wrong
Yeh its probably Intents, zervyrel correct me if im wrong
Nothing prints..
await interaction.channel.delete()
I was told i didnt need interaction as its being passed through the class
def __init__(self, NewChannel):
super().__init__()
self.channel = NewChannel
@discord.ui.button(label="Close Ticket",style=discord.ButtonStyle.red, emoji="❌")
async def delete_channel(self,button, interaction: discord.Interaction):
await interaction.NewChannel.delete()```
I tried it but dosent fix it
if you do it like that, it will the channel where the button is pressed
You mean it will delete in the channel where the buttons located?
if you send the button in a channel and press the button, it will delete the channel where the button was pressed
Yeah thats what im wanting, but it hasnt happened
I have no error to help me figure this out either
def __init__(self, NewChannel):
super().__init__()
self.channel = NewChannel
@discord.ui.button(label="Close Ticket",style=discord.ButtonStyle.red, emoji="❌")
async def delete_channel(self,button, interaction: discord.Interaction):
await interaction.NewChannel.delete()
class Support(discord.ui.View):
@discord.ui.button(label="General Support",style=discord.ButtonStyle.success, emoji="📄")
async def button_callback(self,button, interaction: discord.Interaction ):
category = interaction.client.get_channel(1052267160724049970)
NewChannel = await interaction.guild.create_text_channel(name=f"Ticket ",category=category)
await NewChannel.send(embed = StartMsg, view=NewButtons(NewChannel))``` full code (kinda)
Yeah but i have it defined as newchannel, so wouldnt it be that?
well i kinda do
change "NewChannel" to just channel
like in that
Pass the author to the view and then either check before running the callback or override the interaction_check method
Hi, I have my bot in pycord 2.1.1 and I have in requeriments py-cord==2.1.1. But when I add my repro in Replit It download the last version
?tag replit
Read this to find out how you can install Pycord in Replit
Old instructions: https://web.archive.org/web/20211128084858/https://namantech.me/pycord/installation/#replit
New instructions: #998272089343668364 message
ModuleNotFoundError: No module named 'discord.commands'
pip list and send output. pip3 if unix
aiohttp 3.8.3
aiosignal 1.3.1
async-timeout 4.0.2
attrs 22.1.0
certifi 2022.12.7
charset-normalizer 2.1.1
discord 2.1.0
discord.py 2.1.0
frozenlist 1.3.3
idna 3.4
keyboard 0.13.5
MouseInfo 0.1.3
multidict 6.0.3
PyAutoGUI 0.9.53
PyGetWindow 0.0.9
PyMsgBox 1.0.9
pyperclip 1.8.2
PyRect 0.2.0
PyScreeze 0.1.28
pytweening 1.0.4
requests 2.28.1
urllib3 1.26.13
yarl 1.8.2
well, I don't see py-cord.
oh shit yeah
important, you need to uninstall discord.py before installing py-cord
done thank you
first thing
learn python ty
^
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)
show the pip list again
await msg.edit(embed=embed3)
@fervent cradle
aiohttp 3.8.3
aiosignal 1.3.1
async-timeout 4.0.2
attrs 22.1.0
captcha 0.4
certifi 2022.12.7
charset-normalizer 2.1.1
discord 2.1.0
frozenlist 1.3.3
idna 3.4
keyboard 0.13.5
MouseInfo 0.1.3
multidict 6.0.3
Pillow 9.3.0
py-cord 2.3.2
PyAutoGUI 0.9.53
PyGetWindow 0.0.9
PyMsgBox 1.0.9
pyperclip 1.8.2
PyRect 0.2.0
PyScreeze 0.1.28
pytweening 1.0.4
requests 2.28.1
typing_extensions 4.4.0
urllib3 1.26.13
yarl 1.8.2
discord 
uninstall discord and py-cord and reinstall py-cord..
?tag replit
Read this to find out how you can install Pycord in Replit
Old instructions: https://web.archive.org/web/20211128084858/https://namantech.me/pycord/installation/#replit
New instructions: #998272089343668364 message
#help-rules Nr. 1
Official Beginner's Guide: https://wiki.python.org/moin/BeginnersGuide
Official Tutorial: https://docs.python.org/3/tutorial/
Shortcuts:
https://wiki.python.org/moin/BeginnersGuide/NonProgrammers
https://wiki.python.org/moin/BeginnersGuide/Programmers
Learn Python:
https://automatetheboringstuff.com/ (for complete beginners to programming)
https://learnxinyminutes.com/docs/python3/ (for people who know programming already)
https://docs.python.org/3/tutorial/ (official tutorial)
http://python.swaroopch.com/ (useful book)
http://www.codeabbey.com/ (exercises for beginners)
Am trying to get an emoji for a reaction through a modal, all i get is the :sunglasses: text, but when passing into await msg.add_reaction(discord.PartialEmoji.from_str({emoji))i get an error Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In emoji_id: Value "" is not snowflake. Help please
print emoji and see what you get
The :sunglasses:
.rtfm discord.PartialEmoji.from_str
you are supposed to pass one of the following formats with .from_str https://cdn.nziie.is-a.dev/u/Rn5jHYmJebqQ
Oh... will try something
Nah did not go.. Then a followup question forms of how do i get the id? I guess the :sunglasses: is name not the id, yet that is all i get anyway so i don't have much to work with there
well for an emoji like :sunglasses:, it's automatically turned into an emoji in markdown; so it doesn't really have an ID. i think there is a converter for emojis
.rtfm discord.EmojiConverter
Target not found, try again and make sure to check your spelling.
if i pass in just the :sunglasses: in await msg.add_reaction(discord.PartialEmoji.from_str(":sunglasses:") it still throws the same error, seems like what i am trying to do is probably not feasable
show code ty
what is that and how to do that it in pycord?
Here's the context menus example.
Learn all about Context Menus (User Commands & Message Commands) and how to implement them into your Discord Bot with Pycord!
which intent is needed to get member from a guild using his id
members intent iirc
interaction.respond returns another interaction. not the message object
.rtfm edit_original_response
use that to edit the msg sent
is there an ability to purge a member?
like await ctx.channel.purge(limit=messages) but for a member?
.rtfm purge
you can define a check that checks the author id with the member id you have
noice. ty.
np 👍
.rtfm ephemeral
Is there a way to make a response message as ephemeral ?
ephemeral=True
slash commands doens't show for me but for my friend it does
Restart your discord client
Hard reload if using discord web
And clear chahe if using mobile
didn't do anyhing
Check server Slash perms
--> python3 -m poetry add py-cord
Using version ^2.3.2 for py-cord
Updating dependencies
Resolving dependencies...
SolverProblemError
Because no versions of replit match >3.2.4,<3.2.5 || >3.2.5,<4.0.0
and replit (3.2.5) depends on typing_extensions (>=3.7.4,<4.0.0), replit (>3.2.4,<4.0.0) requires typing_extensions (>=3.7.4,<4.0.0).
And because replit (3.2.4) depends on typing_extensions (>=3.7.4,<4.0.0), replit (>=3.2.4,<4.0.0) requires typing_extensions (>=3.7.4,<4.0.0).
Because no versions of py-cord match >2.3.2,<3.0.0
and py-cord (2.3.2) depends on typing-extensions (>=4,<5), py-cord (>=2.3.2,<3.0.0) requires typing-extensions (>=4,<5).
Thus, py-cord (>=2.3.2,<3.0.0) is incompatible with replit (>=3.2.4,<4.0.0).
So, because python-template depends on both replit (^3.2.4) and py-cord (^2.3.2), version solving failed.
at venv/lib/python3.8/site-packages/poetry/puzzle/solver.py:241 in _solve
237│ packages = result.packages
238│ except OverrideNeeded as e:
239│ return self.solve_in_compatibility_mode(e.overrides, use_latest=use_latest)
240│ except SolveFailure as e:
→ 241│ raise SolverProblemError(e)
242│
243│ results = dict(
244│ depth_first_search(
245│ PackageNode(self._package, packages), aggregate_package_nodes
/home/runner/OutrageousPlainGame/venv/lib/python3.8/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
warnings.warn(
exit status 1
Replit: Package operation failed.
?tag norepl
Why NOT to use Repl as a hosting platform
You should not use Repl.it to host your bot.
It may be a nice option as its "free" but you should use something else considering the major flaws.
- The machines are super underpowered.
-
- This means your bot will lag a lot as it gets bigger.
- You'll need a web server alongside your bot to prevent it from being shut off.
-
- This isn't a trivial task, and eats more of the machines power.
- Repl.it uses an ephemeral file system.
-
- This means any file you saved via your bot will be overwritten when you next launch.
IMPORTATNT
- They use a shared IP for everything running on the service.
This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.
Please avoid using repl.it to host your bot. It's not worth the trouble.
If you're looking for free options, consider using AWS/Google Cloud Platform/Azure and its respective free tiers or just pay for an actual VPS.
ModuleNotFoundError: No module named 'cogs'
Is it possible to make global app commands with this api wrapper
yes
Yes, just don't include debug_guilds or guild_ids
Yeah lmao
Yes. It is "harder" to make a guild only command XD
😂
Ok
I will try that
Ig
yes
fixed that but now i have a new error discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: OSError: cannot open resource
I don't know how to explain but do your cogs "load" themselves?
I just know that in the examples there were 2 functions that needed to be in there
yeah my cog verifaction.py loads
all that is in that is exten=["cogs.verification"]
where verification.py console logs when loaded
def setup(bot):
try:
bot.add_cog(Verification(bot))
print("Loaded verification.py")
except Exception as e:
print(f"Error loading verification.py: {e}")
Ahh i won't be knowledgable enough to help after all, sorry, i hope you find the solution!
thanks for trying
wait it didnt work
i got trolled
By global commands did you mean so they can be executed on any server right?
yes
any server the bot is in
Then it was the right thing, it just takes sometimes a lil bit to sync with all of the discord physical servers. When you specify which guilds exactly to sync with it does it instantly, with global it can take 5-30min
If you get unlucky once mine synced only after 2 hours...
ok but all my other commands arent working
By not working do you mean it throws an error?
no in discord it says
the thing
oh i forgot to ping when i replied
and dose it have to be online mean while
While syncing?
yes
Of course, how else would it sync with the bot? xD
r u trolling me or no
No
I usually leave my bot on if i need to sync the commands, but recently it has only taken like 5min
quick question. when I restart my bot, do my tasks create duplicate instances? they are being started at on_ready()
what should i do
Here's the slash basic example.
bot.slash_command did you mean to write?
wait i dont need @
Right there in the error it says that you have @bot.slashcommand, but proper way is @bot.slash_command
Aka you forgot the underscore
it worked to write this
without the @
@astral mist please check https://guide.pycord.dev/interactions/application-commands/slash-commands for proper slash command creation.
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
Thanks squid
that means the bot has slash commands
Yea
Anyone know of any open-source Poll implementations? I know Pycord Manager has one, but seems it's just creating the poll. Looking for something that actually watches votes and issues results.
do i have to wait for it to fully sync to remove the other ones
or the clones
I had a makeshift thingy for similar use case made, don't have it anymore, but i saved the votes into a database and when called would count them up and issue them. You probably can make something like that aswell + learn something new possibly
refresh discord
alr
No doubt I could make one, just mostly looking for something as a reference (specifically the monitoring aspects)
Unfortunately i don't have anything, sorry, i can just kinda pitch ideas xd
if they are still there, you would comment on all commands and reset your token and your bot. uncomment the commands and re-run the bot.
alr
didnt work
and i tried to refresh discord
with ctrl + r
try using them
Well if you had it reaction based then you could just pull up data from there rather than storing it
it dosent work
@astral mist add this auto_sync_commands=True to where you define the bot
I also had the problem
alr
wait in the ()
you need intents for ban commands and other stuff
hm
well its still not syncing
if this needs a new thread let me know
Make a thread please
its been syncing for 10 min
could you use
for command in bot.walk_application_commands():
print(command)
in on_ready and show output?
should i just make a new bot
me?
yes, you
its not outputting
Pong!
205ms
this is the latency of the bot
this is my output because i have a loop running to tell me
the ping
so is on_ready not firing?
yeh i think so
Do you have on_connect in your code?
dont think so
like under the bot event thing
huh
wait could it be cus i have a loop under my @bot.event
what event? and what kind of loop?
He wants so you add print in your on_ready() function
To see if it executes
If it doesn't, somethin wrong big time
it works
its printing
you still haven't answered the question
what event? and what kind of loop?
@bot.event
async def on_ready():
while True:
game = discord.Game("syncing slash commands")
await bot.change_presence(status=discord.Status.idle, activity=game)
print(f'Pong! \n {round(bot.latency * 1000)}ms \n this is the latency of the bot ')
hook.send(STATUS)
time.sleep(30)
print(f'Pong! \n {round(bot.latency * 1000)}ms \n this is the latency of the bot ')
hook.send(STATUS)
like this type
that dose stuff on being run
bruh
?tag codeblock
Please put your code in a code block:
```py
Here is your Code
```
That makes reading code in Discord a lot easier:
print("This is an example.")
and also
and its a while true loop that dose for me
facepalm
what
async is basic
yes i think so
So why are you constantly changing the presence, and using time.sleep in a blocking infinite while loop?
because i want it to send a webhook every 30 sec
to my server while being online
so why time.sleep? which is blocking
use tasks for that
because i dont want it to spam my channel
that's going to permanently block all code execution, meaning your bot won't be able to do anything else
while that loop is running
which is forever
so remove loop ??
Learn async/await in python and use tasks
cant u just help me
I have helped you
You need to learn stuff not only copy code
I have told you everything you need to know
at least the bot works now
Jo, I am new writing Discord Bots and i have a weird error message. You can see the code on the picture. I try to make a member Join message, but when the event get triggerd, than the console giving me a weird error message and I dont check why. Can someone maybe help me?
why ctx?
remove that and use member.guild
oh yeah it worked, thx 😄
Should I just read the python docs and then learn use of this api wrapper

When you want to make something, search about it on the docs and use that to make it, 2 days ago i didn't know how to add reactions, now i have a modal input system from which it takes emojis and reacts to a message with them, so yes. But also learn basic python and asyncio, need that to know what all the commands in api do.
Alr bet I guess I will try to fully learn python before the new year
How can i get the interaction.user (or interaction.user.name) from another button, so for eg
I am creating an embed but need the user who used a button from another button
Im not sure if that makes sense
Not going to happen
Why is that
Learning to code takes time, and effort
Anyone know this?
I have effort
👍
Technically you have all the time in the world
.
A janky way i can think of is to store that either as a variable alone or in a text file/database, but that probably isn't the "best programmer" way of doing that, yet i did that for a different type of reason
It works, definitely will get either slow or overwrite stuff if it gets executed quickly and a lot at the same time
What would be the best way to do it?
No idea, that's why i said about the janky way
That's not janky
That's a legit way. Using db
That's is soo much better than using global variables
You can store it in a dict and get it from there
Or like the other guy said, db
Personally i would suggest sqlite, it's easy to learn, not that heavy on the system too i believe
If you don't care about persistence, redis will be fine too
i keep getting this error but dont know how to fix it, this was working some time ago but doesnt work now for some reason
any ideas on how i can fix this and why this is happening?
Can I limit the length of the str for an input option?
eh you could check how many characters it's got then have an if statement to allow or deny it
interaction.message isn't a thing, look at https://docs.pycord.dev/en/stable/api/models.html#discord.Interaction
But this is not possible with slash commands
But that only works for INT and not for STR, right?
Oh nvm I am stupid 😄
hi, how can i start/stop/restart a task that's defined in a different cog?
whats the task for? and code for task so we can help you.
You place your super().init first
def __init__(self):
super()...
options = ....```
interaction.response.edit_message should be
Not interaction.message.edit
Oh
.rtfm interaction.original_message
message = interaction.original_message
message.edit
Then send the modal
You always could
You were not able to delete them
I think you are mis-understanding what interaction.message is. It is the response message, not the message it is attached to.
.rtfm interaction.message
Yeah a couroutine. Forgot about it
Yes you can
You're doing it with the original_message
Fetches the original interaction response message associated with the interaction.
Not the message the view is associated to
you can use self.view.message to retrieve the message
Isn't it the message the view is in? I've used it
Which is what they want.
Oh you were just quoting the docs lmao
how do i add text like this with an embed
Just like you did
mentions in embed don’t ping
So how do I mention in general
user.mention returns a string that you can use to mention people
or <@{user.id}>, but preferably user.mention
native solutions are usually preferred.
another question. how do i check if a the command was typed in a specific channel
docs are down rn thats why im asking
Works fine for me
do you guys know how to make the bot appear on the user list?
give the bot the permissions?
same for the channel?
this?
Uh oh! This site is in maintenance mode. Something big is coming, check back later!
so either way whats the answer if you know
Compare discord.TextChannel objects or ids
.rtfm channel.id
await interaction.edit_original_response(embed=embed, view=view, ephemeral=True) Why doesnt this work? I get unexpected keyword 'ephemeral'
You don’t need to pass ephemeral
You can’t edit a message to be hidden.
You can only send a message as hidden from an interaction
Send full code and full error
@rare ice
@rare ice
You need to use interaction.response.edit_message iirc
.edit_original_response is mainly used for ephemeral messages
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ui/view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "/home/container/main.py", line 283, in callback
await ticket_channel.send(embed=embed, view=StaffApp)
File "/home/container/.local/lib/python3.10/site-packages/discord/abc.py", line 1550, in send
components = view.to_components()
TypeError: View.to_components() missing 1 required positional argument: 'self'```
Error!!
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Staff Application", style=discord.ButtonStyle.primary)
async def button_callback(
self, button: discord.ui.Button, interaction: discord.Interaction
):
modal = MyModal(title="Staff Application")
await interaction.response.send_modal(modal)```
code
im removing it rn
channel = ctx.message.channel
?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.
module 'discord' has no attribute 'slash_command'
keep getting this error on my AWS server, not on local. I suppose someone is going to ask for my pip list, so here it is: https://pb.envs.net/?f0678d12369abb8e#5hVPV3ae4hnKkZ3j7yjde6wu2tcV8tE3vQ2peuR9q9kL
Visit this link to see the note. Giving the URL to anyone allows them to access the note, too.
File "d:\Coding\Discord.py\Trignometry Bot\main.py", line 19, in ping
channel = ctx.message.channel
^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'channel'
channel = ctx.message.channel
```` solve this
clearly ur ctx is undefined
whats the context here.
this is
send the entire code for what you want to send in the channel.
@bot.slash_command()
async def ping(ctx):
channel = ctx.message.channel
t1 = time.perf_counter()
await bot.send_typing(channel)
t2 = time.perf_counter()
await bot.say("pseudo-ping: {}ms".format(round((t2-t1)*1000)))
print("Ping Command activated")
ctx: Context
also u dont have to await that, I don't think.
async def ping(ctx):
channel = await ctx.message.channel
t1 = time.perf_counter()
await bot.send_typing(channel)
t2 = time.perf_counter()
await channel.send("pseudo-ping: {}ms".format(round((t2-t1)*1000)))
print("Ping Command activated")```
there.
u changed nothing??
I did.
await channel.send("pseudo-ping: {}ms".format(round((t2-t1)*1000)))
that was
await bot.say("pseudo-ping: {}ms".format(round((t2-t1)*1000)))
This was their error
hmm
after removing that also it didn't work
did u change bot.say????
not working
please check the guide to know how to create slash commands
?tag guide
oh yeah noticed his decorator was completely wrong lol
@bot.slash_command(guild_ids=[ID], description="Ping")
async def ping(ctx):
channel = ctx.message.channel
t1 = time.perf_counter()
await bot.send_typing(channel)
t2 = time.perf_counter()
await ctx.respond("pseudo-ping: {}ms".format(round((t2-t1)*1000)))
print("Ping Command activated")
@daring trout this prolly works.
discord.slash_command is used in cogs while bot.slash_command is used outside of cogs
oops yeah sorry forgot
await bot.send_typing(channel) also no longer works
ah jesus christ

ctx.message.channel also would not work
the message would be None. The correct is ctx.channel, but channel isn't used.
what should i do now?
which would not work
please check out the guide for how to create slash commands
very sadge
finally that works
thanks
you're welcome
In what sense?
I have completed learning python a few months ago
I want to know how to use pycord
becuz earlier i am using discord.py
Pycord Guide is a complete guide for Pycord. Learn how to create Discord Bots today!
so i am facing problem
did you learn these concepts?
hmm what to do after this
you can begin by reading the guide
after that what to do
Do whatever you want with pycord.
Implement your own Discord bot, wherever your imaginations take you.
It comes with practice.
ok
is the correct link
this is what i am saying
how to understand docs
i am not able to justify it
.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.
Microsoft Windows [Version 10.0.22621.963]
(c) Microsoft Corporation. All rights reserved.
D:\Coding\Discord.py\Trignometry Bot>C:/Users/Dell/AppData/Local/Programs/Python/Python311/python.exe "d:/Coding/Discord.py/Trignometry Bot/main.py"
Traceback (most recent call last):
File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\cog.py", line 561, in _inject
bot.add_command(command)
^^^^^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'add_command'. Did you mean: 'all_commands'?
see
import discord
from dotenv import load_dotenv
import os
load_dotenv()
client = discord.Bot()
client.load_extension("cogs.basics")
token = str(os.getenv("TOKEN"))
client.run(token)
No tag codeblocks found.
?tag codeblock
Please put your code in a code block:
```py
Here is your Code
```
That makes reading code in Discord a lot easier:
print("This is an example.")
and also show code for the cog itself
import discord
from discord.ext import commands
import time
import random
class Greetings(commands.Cog):
def __init__(self, client):
self.client = client
self.random = random
@discord.slash_command(name = 'gtn', description = 'A Slash Command to play a Guess-the-Number game.')
async def guess_no(self, ctx):
await ctx.respond('Guess a number between 1 and 10.')
guess = await self.client.wait_for('message', check=lambda message: message.author == ctx.author)
if int(guess.content) == self.random.randint(1, 10):
await ctx.send('You guessed it!')
else:
await ctx.send('Nope, try again.')
def setup(client): # this is called by Pycord to setup the cog
client.add_cog(Greetings(client))
print("Greetings Cog Loaded")
full traceback?
send in multiple messages
bruh!!!
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "d:\Coding\Discord.py\Trignometry Bot\main.py", line 9, in <module>
client.load_extension("cogs.basics")
File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\cog.py", line 910, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\cog.py", line 791, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.basics' raised an error: AttributeError: 'Bot' object has no attribute 'remove_command'
this is the remaining
I don't see the first part?
#998272089343668364 message
try using Python 3.10 or lower
bruh
pip list in terminal and send output please
see
try re-installing.
re-installing py-cord?
bruh
why??
The installation may be at fault
not working now also
some problem in your library
restarted IDE?
Is the problem resolved?
is there a way to pass in parameters to a button view?
class MyView(discord.ui.View):
def __init__(self, msglink):
self.msglink = msglink
@discord.ui.button(label="Message Link", style=discord.ButtonStyle.link, url=self.msglink)
async def callback(self, button, interaction):
...
I've tried ^ but it says self is not defined where I say url=self.msglink
my installation of py-cord works fine with your code
Not working for me
😶
since link buttons don't have a callback, you can create the button inside of __init__
e.g.
link_button = discord.ui.Button(label="foo", style = discord.ButtonStyle.link, url = self.msglink)
self.add_item(link_button)
I'm sorry. I don't know what else I can help you with. The code is correct and all.
ah I see, thank you!
also is there a way to ctx.send_response and get the message that is sent? (as a discord.Message object)
you can use ctx.message to get the message that you responded with.
I know that
that's not what I mean
like if you send a message with await ctx.send_response("foo")
I want to get that message, the one the bot sent
you can either store the return value and get the response message with https://docs.pycord.dev/en/master/api/models.html#discord.Interaction.original_response or just simply use ctx.message.
I see
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: filter expected 2 arguments, got 4
filter is defined here:
async def filter(self, ctx, img, usr, op):
called like this:
@discord.slash_command(guild_ids=config['main_guilds'],description="turns an image to black & white.")
async def bw(self, ctx, image: discord.message.Attachment = None, user: discord.Member = None):
image = await filter(ctx, image, user, "bw")
If it's in the same class it'd need to be await self.filter()
But not sure about the 2 args 
YEAH, it's cus filter is an internal arg.
which takes two.
that was the fck up........
OH that makes sense
is there a way to like abort a command?
You can raise an exception that'll be caught in on_application_command_error if thats what you mean
dope, that works.
what is rate limit for editing a guild command?
I don't get how there is no description?
@discord.slash_command(guild_ids=config['main_guilds'], description="Mass deletes messages")
@commands.has_permissions(manage_messages=True)
@option("messages", description="Amount of messages to delete.")
@option("member", description="Specific member to delete from.")
async def purge(self, ctx: Context, messages: int, user: discord.Member = None):
in any example, it doesn't look like I can provide multiple options
is there a quick way to get a datetime of the last activity in a thread? could use the creation time of the last message but that would ignore reactions etc yes?
There is some discord rate limits and in pycord sync is automatically so i guess pycord handle the rate limits and your command will updates later but I'm not sure please read discord api docs before doing this
Also not recommended for production
i want to use this in production
Lmao, don't do this in production
yeah 😅
It's on you what you wanna do but it's not recommended
yeah but thats what i want to do
Because discord has rate limits and you are saying you are gonna update your command in every second then it will hit the rate limits and you will get warning and then you will get rate limited from discord or ban
i can reduce that to every 5 sec or more
Also there is not any reason that you are have to update a command 😂
Still you will get rate limited
I don't know the current amount of time, I'll prefer read their api docs before doing this crazy thing in production
Also Your bot will die soon if you do this in production
yeah ik that and i am trying to solve it
What you are trying to solve ?
I dont want guild to see commands they dont want
What do you mean ? You are hiding those commands which user don't want to see ??
Then why are you creating your bot ?? Know one use it too 😂
What is the best way to test a discord bot? I typically develop on my personal computer and then when I've tested it push it to a home server and run it there -- but I have to then take down the bot every time I am developing it. I was thinking I could either:
- Create another bot, and just replace the token on my personal computer to the test bot
- Subclass my existing bot as like a test bot and have it run differently on my personal computer?
The first option seems easier and less complicated than the second one, but I saw that the Pycord docs use the second method
jk
объясни на русском лучше
Нужно чтобы кнопку мог нажимать только member
Я с ролями такое делал
||god, dang it, why would you need to name a fucking function in russian 💀||
с участниками не понял
ну используй if
там в конструкторе interaction
есть interaction.user.id
а при создании view
ты можешь передавать туда айди чела, который команду юзанул
и просто сверять
а там только через айди работает?
это самый удобный способ
👍
chat was encrypted 👍
Can you create a new discord bot account through pycord?
forgive the stupid question, is there something like an on_command event? I am looking to perform some sort of operation every time any slash command is invoked. I wasn't able to find anything in the docs 😦
if someone has a link to it in documentation, that totally works
I notice discord.on_application_command(context), but I am looking to do something in between the actual invocation of the command and its actual operation (and perhaps be able to stop the command from triggering under certain conditions)
discord.Bot.add_check
discord.Bot.check
discord.Bot.check_once
discord.Bot.remove_check
discord.AutoShardedBot.add_check
discord.AutoShardedBot.check
discord.AutoShardedBot.check_once
discord.AutoShardedBot.remove_check
discord.Cog.bot_check
discord.Cog.bot_check_once
discord.Cog.cog_check
discord.EmbeddedActivity.checkers_in_the_park
discord.EmbeddedActivity.checkers_in_the_park_dev
discord.EmbeddedActivity.checkers_in_the_park_staging
discord.EmbeddedActivity.checkers_in_the_park_qa
discord.CheckFailure
discord.CheckFailure.args
discord.CheckFailure.with_traceback
discord.ui.View.interaction_check
discord.ui.View.on_check_failure
Oof those are too many
well, I'm not entirely sure. can this be accomplished with checks? I would like to be able to intervene with the command being called if possible
Yeah command checks are run before invoking the command callback. You can raise errors to stop the callback from being run. These errors and be picked up by the command error handler or the global error handler to respond something like "you can't run this cmd"
@limber urchin hey I saw you typing. You got any example/docs links or tags for checks? I'm a noob with tags
https://docs.pycord.dev/en/stable/ext/commands/commands.html#checks
I guess this should do
How to make slash command response hidden to everyone except the executor
Add ephemeral=True in your response method
Alright thanks mate, got to google what ephemeral means lol.
@stoic sage
You likely forgot to update the message with the new view.
interaction.edit_original_message(view=view)
https://cdn.discordapp.com/attachments/1045825525924507708/1053341798895988867/image.png is there any way to remove this from slash commands?
Remove what? The tooltip?
No, you can not
?tag install github
- Uninstall discord.py or any other forks of discord.py you might have with the namespace
discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.
Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
@fervent cradle move to #app-commands if you're going to spam random commands
alright some1 was asking me if I could or not.
I didnt spam, but yes ill use that chat for future use sorry
You can send the response as it's own message and then respond with an ephemeral message saying something like "Message sent"
that way it won't display above the message
going to do that right now thank you so much!
I am learning to create a slash command group, and i dont understand what this is doing/for?
"secret_greetings",
"Secret greetings",
checks=[
commands.is_owner().predicate
], # Ensures the owner_id user can access this group, and no one else
)```
Is that command groups that only owner can use?
anyone can see, but only owner can use
is there any public repos that have a good setup with examples of the different functionality, like cogs, slash commands, buttons, embeds, tasks etc? Looking at some of these, but they are all very different in some ways https://github.com/topics/pycord-bot
talking about "best practice" in terms of naming, setup etc. Maybe some included default slash commands like unload, reload, help etc?
you can take a look at https://github.com/Dorukyum/Toolkit for that
It is structurally sound
TypeError: issubclass() arg 1 must be a class
from discord.ext import commands
from discord.commands import SlashCommandGroup
from discord import option
class poll(commands.Cog):
def __init__(self, bot: discord.Bot):
self.bot = bot
Poll = SlashCommandGroup("poll", "Different Poll Groups")
PollOptions = Poll.create_subgroup(
"pollcreate", "help", "anonymous"
)
@Poll.command()
async def poll(self,
ctx: discord.ApplicationContext,
message,
choice1: option(str,"First Poll Option"),
choice2: option(str,"Second Poll Option"),
choice3: option(str,"Third Poll Option"),
choice4: option(str,"Fourth Poll Option"),
choice5: option(str,"Fifth Poll Option"),
choice6: option(str,"Sixth Poll Option"),
choice7: option(str,"Seventh Poll Option"),
choice8: option(str,"Eighth Poll Option"),
choice9: option(str,"Ninth Poll Option"),
choice10: option(str,"Tenth Poll Option")):
await ctx.respond()
def setup(bot):
bot.add_cog(poll(bot))
I've never gotten this error before, i have no idea whats happened
I changed them from discord.Option to option because the params wouldnt show
option can only be used as a decorator, use discord.Option if you're going to typehint
or message param
Is using @real compasstion better for this?
@real compasstion
sorry mate its auto corrected to ping ya
But spaxter yk what i mean?
Option with O capital
Okay
So should i revert back from discord.Option to Option?
I recommend using the decorator cuz you still retain the python typehinting of str and all that
So @ Option (
blah blah
)
Uh i meant you imported option and used it as a typehint.
discord.option is the decorator
discord.Option is the typehint
Im litearly just trying to follow past knowledge and an example on gh
aight
"age",
description="Enter your age",
min_value=1,
max_value=99,
default=18,
# Passing the default value makes an argument optional.
# You also can create optional arguments using:
# age: Option(int, "Enter your age") = 18
)``` should i do this sorta thing then
Its cleaner + probably better?
Yep
Alright thanks
In a string, would min and max value set the max charecters?
There is min and Max length
Alright
Weird, Have i done something wrong? Choice1 isnt showing
from discord.ext import commands
from discord.commands import SlashCommandGroup
from discord import option
class poll(commands.Cog):
def __init__(self, bot: discord.Bot):
self.bot = bot
Poll = SlashCommandGroup("poll", "Different Poll Groups")
PollOptions = Poll.create_subgroup(
"pollcreate", "help", "anonymous"
)
@Poll.command()
@option("choice1",
description = "Option one of the poll",
default=None,)
async def poll(self,
ctx: discord.ApplicationContext,
message,
choice1: str,
choice2: str,
choice3: str,
choice4: str,
choice5: str,
choice6: str,
choice7: str,
choice8:str,
choice9: str,
choice10: str,
):
await ctx.respond("Works")
def setup(bot):
bot.add_cog(poll(bot))``` No error btw
Hmm
You named the cog and the command the same
Gonna conflict
Name the cog smth like PollCog
Oh thanks, i always just forget abt the cog related code
yeah i will, that shouldnt stop choice1 showing tho right? Still isnt shown
Oh and if you make an option optional or set a default then don't forget to do the same for the python typehint
Ig not, but not sure
Im just having a look over the code again
Weird i dont see anything still, if anyone else knows please lmk and @ me
Hello,
is it possible to create a slashcommand where you tag users from the server?
/slash @User1 @User2 @User3
And then evaluate the corresponding User.IDs from the bot, so that I can move these users? 🙂
Anyone?
https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_options.py
Look at this, you can see how you can specify a type on a slash command option
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/slash_options.py at master · Pycord-Development/pycord
Use options
what?
Are you overriding the on connect event? Also send python version and pip list
But I never know exactly how many users I need to tag. It can be sometimes 2 and the next time 7
😓
Oh wait you already did right no you hadn't
I only have pycord github installed, python dotenv 3.11 version and no i amnt
Then you need to figure our your own way of parsing a comma separated input or something. There currently isn't a way to tag multiple users in one option
Hmm update pycord to latest. Your might have been old
Use user select menus
Or accept a string and parse mentions to get ids. This would need regex
I installed https://github.com/Pycord-Development/pycord
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - GitHub - Pycord-Development/pycord: Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API
In the select menu I can select multiple users?
Yep
Try the pypi version
But the select options are also static and can not be built dynamically or?
How do i see that?
pip install -U py-cord
Isnt that version like v1?
There are new select menus that allow you to select users, roles, channels natively into discord
.rtfm user_select
2nd one
No that's latest stable release
Okay
It just said req already satisified for everything
Okay thanks 🙂
Is there somewhere an example to the one can look at? 🙂
There should be something on the GitHub examples folder
Here's the dropdown example.
Check if that has an example
Hmm
Uninstall and reinstall
from discord.ext import commands
from discord.commands import SlashCommandGroup
from discord import option
class pollCog(commands.Cog):
def __init__(self, bot: discord.Bot):
self.bot = bot
poll = SlashCommandGroup("poll", "Different Poll Groups")
PollOptions = poll.create_subgroup(
"pollcreate", "help", "anonymous"
)
@poll.command()
@option("choice1",
description = "Option one of the poll",
default=None,)
async def poll(self,
ctx: discord.ApplicationContext,
message,
choice1: str,
choice2: str,
choice3: str,
choice4: str,
choice5: str,
choice6: str,
choice7: str,
choice8:str,
choice9: str,
choice10: str,
):
await ctx.respond("Works")
def setup(bot):
bot.add_cog(pollCog(bot))
``` The command isnt even showing up at all anymore...??
Not sure if its my discord or not
Okay thanks 🙂
I'll have a read 🙂
poll is both the Slash group and func name 
Np
Btw that link doesn't have example
It's an example for a normal select menu. Not a user select menu
Reverted back to this code, it runs, no command but i get this
Traceback (most recent call last):
File "C:\Users\Wacky\Documents\Poll Bot\venv\Lib\site-packages\discord\client.py", line 377, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Wacky\Documents\Poll Bot\venv\Lib\site-packages\discord\bot.py", line 1164, in on_connect
await self.sync_commands()
File "C:\Users\Wacky\Documents\Poll Bot\venv\Lib\site-packages\discord\bot.py", line 719, in sync_commands
registered_commands = await self.register_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Wacky\Documents\Poll Bot\venv\Lib\site-packages\discord\bot.py", line 599, in register_commands
registered = await register("bulk", data, _log=False)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Wacky\Documents\Poll Bot\venv\Lib\site-packages\discord\http.py", line 366, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 0.options.1.options.2: Required options must be placed before non-required options
In 0.options.1.options.3: Required options must be placed before non-required options
In 0.options.1.options.4: Required options must be placed before non-required options
In 0.options.1.options.5: Required options must be placed before non-required options
In 0.options.1.options.6: Required options must be placed before non-required options
In 0.options.1.options.7: Required options must be placed before non-required options
In 0.options.1.options.8: Required options must be placed before non-required options
In 0.options.1.options.9: Required options must be placed before non-required options
In 0.options.1.options.10: Required options must be placed before non-required options
do i need to finish the options
The error explains exactly what's wrong
whats the formatting for that?
Okay I don't really know how to incorporate this 😄
discord.Bot has no add_command attribute, as their error said. They probably want to use add_application_command. -> https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.
@daring trout If you still need help. ^
How can i have
choice2: str,
choice3: str,
choice4: str,
choice5: str,
choice6: str,
choice7: str,
choice8:str,
choice9: str,
choice10: str,``` in a variable sorta thing? so i can check for eg if len(options) is 2 then reacts with certian reactions
The error is within the library itself and add_command does exist internally.
add_command exists even with discord.Bot? I though discord.Bot was only for slash commands, therefore it would make sense there is no add_command method for it & only add_application_command?
how can we get label instead of value from discord.ui.Select
select.values[0] works for value but select.labels[0] doesn't for labels
The issue is that with their code, the library works on everyone else's machine, but not on their machine.
set the label to value.
or you can iterate through select.options and find the discord.SelectOption with said value.
I don't understand?
Why do you need the label?
i've title for level and an id for value
bot should display the title so it set in label
but i require both on select callback
you can set the value to include the label as well.
any other method?
.
This is rather inefficient because it is linear time complexity, while the previous method is constant time complexity.
https://discord.com/channels/881207955029110855/1051510480373563392 This user had a similar error?
Well create a view, then create a user select menu along with the callback, then add the select menu to the view and send the view
Okay, now I have a first version.
How can I access the User.ID of the selected people?
Well, there isn't sufficient information to draw any conclusions.
select.values should have a list of users selected
You can get the id using user.id
What am I doing wrong?
import discord
from discord.ui import Select, View
from discord.ext import commands
bot = discord.Bot()
@bot.event
async def on_ready():
print('Bot is Online!')
class MySelect(View):
@discord.ui.user_select(
placeholder='Wähle einen User'
)
async def select_callback(self, select, interaction):
select.disabled=True
print(select.values)
@bot.command()
async def menu(ctx):
view = MySelect()
await ctx.send(view=view)
bot.run('TOKEN')```
What are you intending to do? What isn't working? What is supposed to happen? What is actually happening?
When I use /menu I get the menu displayed but it also always says "Application not responding".
errors in console?
