interactions-py / interactions.py Goto Github PK
View Code? Open in Web Editor NEWA highly extensible, easy to use, and feature complete bot framework for Discord
Home Page: https://interactions-py.github.io/interactions.py/
License: MIT License
A highly extensible, easy to use, and feature complete bot framework for Discord
Home Page: https://interactions-py.github.io/interactions.py/
License: MIT License
Seeing a lot of users using str
for their snowflakes. Specifically for guild_ids
. The issue with this is that it doesn't cause any errors for the user, causing confusion, but obviously breaks their commands and is very hard to debug
I think we should be either converting the snowflake to int
on the library side, or throwing a warning on creation of the command
I'm trying to make a slash command. If i make one without args, it works fine. But when i try to add args, the command breaks.
Command code:
@slash.slash(name="echo")
async def _echo(ctx: SlashContext, text_to_echo):
await ctx.send(text_to_echo)
when i registered the command, I did add an option in the POST json
json = {
"name": "echo",
"description": "echo something",
"options": [
{
"name": "text_to_echo",
"description": "text that will be echoed",
"type": 3,
"required": True,
}
]
}
my error seems to be in the request itself though: "Request failed with resp: 400 | {"code": 50035, "errors": {"type": {"_errors": [{"code": "NUMBER_TYPE_COERCE", "message": "Value "a" is not int."}]}}, "message": "Invalid Form Body"}"
any help would be greatly appreciated
also another thing, how do i add commands using the library? right now im just using a different file to add commands with requests, but it would be a lot easier if i could just add all the commands as my bot loads/as i code them
I'm trying to download a file from the web but I get the error FileNotFoundError: [Errno 2] No such file or directory: 'cosmeticIcons/cache/icon.png'
. It does exist but it can't find it.
ctx.edit()
uses ctx._http.edit()
which returns the result of the PATCH when executed, but ctx.edit()
doesnt return that, pls change that
If I use the subcommand
decorator without the base_desc
parameter I encounter the following exception:
INFO:discord_slash:Registering commands...
ERROR:asyncio:Task exception was never retrieved
future: <Task finished name='Task-1' coro=<SlashCommand.register_all_commands() done, defined at ./venv/lib64/python3.8/site-packages/discord_slash/client.py:150> exception=RequestFailure('Request failed with resp: 400 | {"code": 50035, "errors": {"description": {"_errors": [{"code": "BASE_TYPE_REQUIRED", "message": "This field is required"}]}}, "message": "Invalid Form Body"}')>
I'm not clear on how to get slash commands working. Inside one of my cogs, I have
@cog_ext.cog_slash(name="test")
async def _test(self, ctx: SlashContext):
await ctx.send("Test!")
I make sure the cog is added to the bot. However, the command doesn't show up, even in guilds where I added it with permission to have slash commands. Therefore, I decide to try to add it specifically to one guild. I manually registered it by having the bot execute
from discord_slash import utils
await utils.manage_commands.add_slash_command(MYID, MYTOKEN, SERVERID, "test", "Test Description!", [])
Now, that guild sees the slash command. However, when I run it, it just says "This interaction failed." I have no errors on my end, so I'm not sure where it's failing? What am I missing here?
So, I've been trying to make slash commands work for my bot, but I didn't quite get it to work the way I wanted it to. I was only able to make slash commands work if I put them in the main bot file.
# main.py
from discord_slash import SlashCommand, SlashContext
cogs = []
for cog_file in os.listdir('cogs/'):
if cog_file.endswith('.py'):
cog_import = 'cogs.' + cog_file.split('.')[0]
cogs.append(cog_import)
bot = commands.Bot( # Create a new bot
# ...
)
bot.slash = SlashCommand(bot, override_type=True, sync_commands=True, sync_on_cog_reload=True)
@bot.slash.slash(name="testnt", guild_ids=[1234567890])
async def _test(ctx: SlashContext):
await ctx.send(content="test", hidden=True)
# This works.
bot.run(token, bot=True, reconnect=True)
I cannot get it to work within cogs. Chances are I'm doing something wrong (which is why I opened an issue to get help).
# cogs/slash.py
import discord
from discord.ext import commands
from discord_slash import cog_ext, SlashContext
guild_ids = [1234567890]
class Slash(commands.Cog):
def __init__(self, bot):
self.bot = bot
def cog_unload(self):
self.bot.slash.remove_cog_commands(self)
pass
@cog_ext.cog_slash(name="testcog", description="Test", guild_ids=guild_ids)
async def _test(self, ctx: SlashContext):
embed = discord.Embed(title="embed test")
await ctx.send(content="test", embeds=[embed], hidden=False)
def setup(bot):
bot.add_cog(Slash(bot))
It obviously tries registering testcog
, but just can't, since if I try to define a slash command named testcog
inside main.py
, it throws an error at me talking about "hey there's two commands with the same name i can't register them" or something similar to that.
In discord.py you can have a parameter that converts to a user, is there something similar in this library? I was looking around the docs and couldn't find anything about it.
how do i create multiple options/arguments?
Why am I getting this issue?
Traceback (most recent call last):
File "C:\Users\Thomas Keig\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Thomas Keig\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord_slash\client.py", line 344, in on_socket_response
await selected_cmd["func"](ctx, *args)
File "G:/My Drive/Home/Python Projects/Personal/iFBR Bot/Discord Bot/v2.0/bot (only slash cmds).py", line 547, in export
await ctx.send(embeds=[embed2])
File "C:\Users\Thomas Keig\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord_slash\model.py", line 111, in send
resp = await self._http.post(base, self._discord.user.id, self.interaction_id, self.__token, initial)
File "C:\Users\Thomas Keig\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord_slash\http.py", line 34, in post
raise RequestFailure(resp.status, await resp.text())
discord_slash.error.RequestFailure: Request failed with resp: 404 | {"message": "Unknown interaction", "code": 10062}
It says it can't get the privileged intents
Traceback (most recent call last):
File "R:\row\slash_command\slash.py", line 16, in <module>
bot.run("THE REAL TOKEN IS HERE")
File "C:\Python39\lib\site-packages\discord\client.py", line 708, in run
return future.result()
File "C:\Python39\lib\site-packages\discord\client.py", line 687, in runner
await self.start(*args, **kwargs)
File "C:\Python39\lib\site-packages\discord\client.py", line 651, in start
await self.connect(reconnect=reconnect)
File "C:\Python39\lib\site-packages\discord\client.py", line 586, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000012902E01CA0>
Traceback (most recent call last):
File "C:\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Python39\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Python39\lib\asyncio\base_events.py", line 746, in call_soon
self._check_closed()
File "C:\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000012902E01CA0>
Traceback (most recent call last):
File "C:\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
File "C:\Python39\lib\asyncio\proactor_events.py", line 108, in close
File "C:\Python39\lib\asyncio\base_events.py", line 746, in call_soon
File "C:\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
RuntimeError: Event loop is closed
Going to be porting over the types from Discord docs. Will submit a PR with them in discord_slash.types
?
Completely my own fault but due to lack of type annotations - just fought for a couple hours with what seemed to be a problem with THIS returning when it shouldn't. But was my fault; checking for int ctx.guild.id
in me mistakenly passing List[str]
to guild_ids
.
Regular command contexts have args/kwargs attributes, this is useful for debugging command errors as the user input can be easily accessed by command error events, however, SlashContext doesn't have this (despite it being arguably more important, as there's no message to log).
Would be a nice little enhancement.
The Issue
In the utils.manage_commands
functions for some commands None
can be passed for the guild_id
parameter to specify using a global scope, but the parameter is not optional
It would be expected that if you don't pass a guild id that it would use the global scope, instead of having to pass None
Ideal solution
Make the guild_id parameter optional
Expected behaviour
utils.manage_commands.get_all_commands(id, token)
should work
ATM you have to do (id, token, None)
The code:
@self.slash.slash(name="away")
async def _away(ctx: SlashContext):
await ctx.send(content=f"Interaction received. {}")
What I am trying to accomplish
https://waspy.sheri.bot/2020/12/16/SUd4
I am trying to receive the option "Message". How would I do this?
Reading the docs, subcommands are not yet implemented?
I am looking to integrate this into my bot which is in 30k+ servers, and I am wondering if this will work with the auto sharded bot
I use script that provided in #9 and doesnt seem to working... Prints all, no error, runs, but discord doesnt show this...
It would be nice to be able to pass a type, such as str
or discord.Role
to the option_type
argument of the function discord_slash.utils.manage_commands.create_option
There may be other functions within that module which this could apply to, I haven't checked in depth. All it would need to do is map the type to an integer. For example: str
would be 3
Is it possible that we can get client side messaging support?
Using discord-py-slash-command, release 1.0.9, calling a command with options from the Android app (version 61.1) raises an exception:
Ignoring exception in on_socket_response
Traceback (most recent call last):
File "lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "lib\site-packages\discord_slash\client.py", line 741, in on_socket_response
args = await self.process_options(ctx.guild, to_use["data"]["options"], selected_cmd.connector) \
File "lib\site-packages\discord_slash\client.py", line 652, in process_options
if x["type"] not in types:
KeyError: 'type'
It seems that from the mobile app (I don’t know if that occurs from iOS app too), Discord doesn’t send the "type" of an option in the response.
I’ve made a workaround on my side that solves my problem:
# discord_slash/client.py
async def on_socket_response(self, msg):
[…]
if "options" in to_use["data"]:
for x in to_use["data"]["options"]:
if "type" not in x:
for option in selected_cmd.options:
if option["name"] == x["name"]:
x["type"] = option["type"]
break
if "value" not in x:
return await self.handle_subcommand(ctx, to_use)
[…]
It’s clearly not a good solution on a long term basis as it doesn’t handle subcommands which have probably the same problem, but it avoid adding complexity to the process_options
method.
I've noticed that when I use guild_ids
on a subcommand for a command which is shared between multiple guilds, that subcommand is registered to all guilds where one of its subcommands is allowed.
s1
for command c
for Guild A:
@slash.subcommand(
base="c",
name="s1",
guilds_ids=[GUILD_A_ID],
)
def _handle(ctx):
# ....
s2
for command c
for Guild B:
@slash.subcommand(
base="c",
name="s2",
guilds_ids=[GUILD_A_ID],
)
def _handle(ctx):
# ....
Guild A has /c s1
command only and Guild B has /c s2
command only.
Guild A has /c s1
and /c s2
but only can use /c s1
, and Guild B has /c s1
and /c s2
but only can use /c s2
.
Can you like do commands with arguments?
example:
/say message: hi
something like that
Currently if auto_delete
is True
a GET request will be made for every guild the bot is in on every load.
This could potentially cause thousands of requests (depending on the size of the bot) and discord has indicated that they might be introducing rate limits for slash commands.
This could make the library unusable for some.
Add a check_all_guilds
parameter to SlashCommand
which defaults to False
.
If it's false then check all guilds that have commands registered to them, don't check all guilds.
If it's true check all guilds (like currently), possibly add a WARNING if guilds above a certain number.
The only problem I can see with this is that it won't delete commands in a guild if there are no commands registered to that guild in SlashCommand
False
My code:
async for msg in ctx.channel.history(limit=amount):
await msg.delete()
And when I run this command, exception throws: NoneType object has no attribute 'history'
As you can understand from this exception, it is tells that context not presents channel in direct messages channel.
Why?
Ready!
Task exception was never retrieved
future: <Task finished name='Task-1' coro=<SlashCommand.register_all_commands() done, defined at C:\Users\usr\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\client.py:150> exception=RequestFailure('Request failed with resp: 403 | {"message": "Missing Access", "code": 50001}')>
Traceback (most recent call last):
File "C:\Users\usr\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\client.py", line 215, in register_all_commands
await manage_commands.add_slash_command(self._discord.user.id,
File "C:\Users\usr\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\utils\manage_commands.py", line 40, in add_slash_command
raise RequestFailure(resp.status, await resp.text())
discord_slash.error.RequestFailure: Request failed with resp: 403 | {"message": "Missing Access", "code": 50001}
Used this example code from documentation:
import discord
from discord_slash import SlashCommand
client = discord.Client(intents=discord.Intents.all())
slash = SlashCommand(client, auto_register=True)
guild_ids = [794271205611143178] # Put your testing server ID. _This is my server ID_
@client.event
async def on_ready():
print("Ready!")
@slash.slash(name="ping", guild_ids=guild_ids)
async def _ping(ctx):
await ctx.send(content=f"Pong!")
client.run("my token")
I have given all of the permissions to the bot role on server and enabled members + presence intent. Why am i receiving this error? Btw discord.py version 1.5.1
Slash commands arent registered with discord when using auto_register=True
.
Code to reproduce, running within a cog:
def __init__(self, bot):
self.bot = bot
if not hasattr(bot, "slash"):
bot.slash = SlashCommand(bot, auto_register=True, override_type=True)
self.bot.slash.get_cog_commands(self)
def cog_unload(self):
self.bot.slash.remove_cog_commands(self)
@cog_ext.cog_slash(name="Ping2")
async def ping2(self, ctx: SlashContext):
await ctx.send(content=f"Pong!")
With the above code, I would expect the command to register and be available to users, however, it is not.
Checking registered commands with:
@commands.command()
async def get_slash(self, ctx):
print(self.bot.slash.auto_register)
print("Showing Commands Registered:")
for i in await discord_slash.utils.manage_commands.get_all_commands(id, token, ctx.guild.id):
print(i)
Shows no registered commands.
Setting the command with:
@commands.command()
async def put_cmd(self, ctx):
print("Setting Commands:")
await discord_slash.utils.manage_commands.add_slash_command(id, token, ctx.guild.id, "Ping2", "Test")
successfully makes the command available to users and is visible when checking with the get_slash
function above.
It would be good if there was a default implementation for argument options when they are not provided.
For example, the argument name and description will just be the name of the function parameter and the type can be obtained by checking the type annotation.
I have a rough implementation of this on my fork jordanbertasso@2e30a16
Thanks for creating this project btw.
Let me know what you think!
discord-py-slash-command==1.0.9 (hotfix-command-register branch)
I just added a new command to my bot:
{
"id": "XXX",
"application_id": "YYY",
"name": "help",
"description": "See Game Basics",
"version": "807752974251065344",
"options": [
{
"type": 6,
"name": "user",
"description": "User to send help tutorial to"
}
]
}
Since the option is not required, everything works fine with no options. But when I include a user as specified in the options, I get the following error.
An exception has occurred while executing command `help`:
Traceback (most recent call last):
File "/Users/xxx/Workspace/discord-bot/venv/lib/python3.7/site-packages/discord_slash/client.py", line 725, in on_socket_response
await selected_cmd.invoke(ctx, *args)
File "/Users/xxx/Workspace/discord-bot/venv/lib/python3.7/site-packages/discord_slash/model.py", line 49, in invoke
return await self.func(*args)
TypeError: on_slash() takes 1 positional argument but 2 were given
Here is my code
import discord
from discord_slash import SlashCommand
client = discord.Client(intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True) # Declares slash commands through the client.
guild_ids = [789032594456576001] # Put your server ID in this array.
@client.event
async def on_ready():
print("Ready!")
@slash.slash(name="ping", guild_ids=guild_ids)
async def _ping(ctx):
await ctx.respond()
await ctx.send(f"Pong! ({client.latency*1000}ms)")
client.run("my_bot_token_here")
but I get this error
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aiohttp/connector.py", line 969, in _wrap_create_connection
return await self._loop.create_connection(*args, **kwargs) # type: ignore # noqa
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 1081, in create_connection
transport, protocol = await self._create_connection_transport(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 1111, in _create_connection_transport
await waiter
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/sslproto.py", line 528, in data_received
ssldata, appdata = self._sslpipe.feed_ssldata(data)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/sslproto.py", line 188, in feed_ssldata
self._sslobj.do_handshake()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/ssl.py", line 944, in do_handshake
self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/bag/disocrdcommands/main.py", line 19, in
client.run("ODE4NDEwMjk1NTI5NzAxMzg3.YEXp-w.lhaizxGl9FINV8SRp4i_AysYfO8")
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/client.py", line 718, in run
return future.result()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/client.py", line 697, in runner
await self.start(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/client.py", line 660, in start
await self.login(*args, bot=bot)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/client.py", line 509, in login
await self.http.static_login(token.strip(), bot=bot)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/http.py", line 293, in static_login
data = await self.request(Route('GET', '/users/@me'))
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/http.py", line 185, in request
async with self.__session.request(method, url, **kwargs) as r:
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aiohttp/client.py", line 1117, in aenter
self._resp = await self._coro
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aiohttp/client.py", line 520, in _request
conn = await self._connector.connect(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aiohttp/connector.py", line 535, in connect
proto = await self._create_connection(req, traces, timeout)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aiohttp/connector.py", line 892, in _create_connection
_, proto = await self._create_direct_connection(req, traces, timeout)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aiohttp/connector.py", line 1051, in _create_direct_connection
raise last_exc
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aiohttp/connector.py", line 1020, in _create_direct_connection
transp, proto = await self._wrap_create_connection(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aiohttp/connector.py", line 971, in _wrap_create_connection
raise ClientConnectorCertificateError(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)')]
Could you tell me what I did wrong.
Kind Regards,
Jakob
Hi all, hope all is well and you are safe.
I'm attempting to test my bot with discord-py-slash-command, but I'm getting a RequestFailure: Request failed with resp: 400 | {"code": 50035, "errors": {"application_id": {"_errors": [{"code": "NUMBER_TYPE_COERCE", "message": "Value \"<built-in function id>\" is not snowflake."}]}}, "message": "Invalid Form Body"}
when I try to discord_slash.utils.manage_commands.get_all_commands
, or when I try to manage_commands.add_slash_command
.
I'm only using example code from the docs and in the issues while troubleshooting, so I'm really confused about what's happening!
I'm running this:
def __init__(self, bot):
if not hasattr(bot, "slash"):
# Creates new SlashCommand instance to bot if bot doesn't have.
bot.slash = SlashCommand(bot, override_type=True, auto_register=True)
self.bot = bot
self.bot.slash.get_cog_commands(self)
def cog_unload(self):
self.bot.slash.remove_cog_commands(self)
@cog_ext.cog_slash(name="ping")
async def ping(self, ctx: SlashContext):
await ctx.send(content="Pong!")
def setup(bot):
bot.add_cog(Slash(bot))
Any help would be extremely appreciated!
Thanks,
-Dan
Edit: It's almost definitely my own incompetence and stupidly causing something!
so i need to fetch some data from first option and using this data create choices
The subcommand
decorator has the following paramers:
base_desc
description
sub_group_desc
subcommand_group
They would be easier to remember if they were named consistently. For example:
base_description
description
subcommand_group_description
subcommand_group
I have a simple command I'm trying to use for testing:
allowedIds = [1234567890, 0987654321] # Not the actual list, just showing as an example.
@slash.slash(name="msg", description="Sends an anonymous message.", guild_ids=allowedIds,
options=[create_option("message", "What you want the message to say", 3, True)])
async def _echo(ctx: SlashContext, message: str):
embed = discord.Embed(title="Anonymous message",
description=message,
color=0xeb4034)
await ctx.send(3, embeds=[embed]) # respond with a message, eating the user's input
When I try to run the command, no message is sent because an error occurs.
Ignoring exception in on_socket_response
Traceback (most recent call last):
File "C:\Users\hpenney2\PycharmProjects\SlashBot\venv\lib\site-packages\discord\client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "C:\Users\hpenney2\PycharmProjects\SlashBot\venv\lib\site-packages\discord_slash\client.py", line 288, in on_socket_response
args = self.process_options(ctx.guild, to_use["data"]["options"], selected_cmd["auto_convert"]) \
File "C:\Users\hpenney2\PycharmProjects\SlashBot\venv\lib\site-packages\discord_slash\client.py", line 264, in process_options
loaded_converter = converters[types[auto_convert[selected["name"]]]]
KeyError: 3
3
is the option type I gave, as seen above.
If I remove the options (including the parameter, references to the parameter, and the options
argument in the decorator), the command works fine.
I tried to figure out the issue by looking through the source code to no avail. Did I somehow screw up options, or is this a bug?
Thank you in advance.
Why is embed, embeds?
I am trying to make a simple poll command, and this code is returning no message object..
@self.slash.slash(name="poll")
async def _poll(ctx: SlashContext, message):
reactions = [ "Reactions"]
embed1 = discord.Embed(color=self.bot.color, title="Poll Question", description=message)
embed1.set_author(name=ctx.author, icon_url=ctx.author.avatar_url)
embed2 = discord.Embed(color=self.bot.color, title="How to cast your vote",
description="Please click/press on the reactions on this message to vote.")
sent_message = await ctx.send(embeds=[embed1, embed2])
await ctx.send(content=sent_message)
for reaction in reactions:
await sent_message.add_reaction(reaction)
Please add the possibility to add options to subcommands.
Since the official API allows this feature, I think it should also be available through this library.
Being able to create more complex slash commands would be great.
Anyone else is experiencing this? It returns a weird error.
I've got it working on a brand new bot but when adding to an existing bot I get this error
Traceback (most recent call last):
File "main.py", line 19, in
from discord_slash import SlashCommand
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/init.py", line 11, in
from .client import SlashCommand
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/client.py", line 11, in
from . import context
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/context.py", line 11, in
class SlashContext:
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/context.py", line 120, in SlashContext
allowed_mentions: discord.AllowedMentions = None,
AttributeError: module 'discord' has no attribute 'AllowedMentions'
If I create command with optional options(kwargs):
@slash.slash()
async def cmd(ctx, arg=None, arg2=None):
...
Then in UI, options will not be optional - it is required.
Hi, when trying to send a file with an embed I get this error:
await ctx.send(file=file2, embeds=[embed2])
TypeError: send() got an unexpected keyword argument 'file'
My code:
embed2 = discord.Embed(title=f"ID: {id}", color=defaultColour)
file2 = discord.File("cosmeticIcons/cache/icon.png", filename="image.png")
embed2.set_author(name=f"Successfully generated icon image for {name} (512x512)", icon_url=author_icon)
embed2.set_image(url="attachment://image.png")
embed2.set_footer(text=footer)
await ctx.send(file=file2, embeds=[embed2])
``;
Hey there, when trying this lib out on an old bot (3 years+) I've noticed that the bot is unable to do anything due the fact that the bot's User ID is not the same as its Application ID. So setting the user ID here sadly doesn't work for old bots.
https://github.com/eunwoo1104/discord-py-slash-command/blob/bbec2e0e109a8bcbd3d47206fb8651299e094d3b/discord_slash/http.py#L75
I was trying to get started with the library using the example code here, but run into this error:
Task exception was never retrieved
future: <Task finished coro=<SlashCommand.sync_all_commands() done, defined at .../discord_slash/client.py:293> exception=NotFound('404 Not Found (error code: 10002): Unknown Application',)>
Traceback (most recent call last):
File ".../discord_slash/client.py", line 308, in sync_all_commands
await self.req.put_slash_commands(slash_commands=cmds["global"], guild_id=None)
File ".../discord/http.py", line 243, in request
raise NotFound(r, data)
discord.errors.NotFound: 404 Not Found (error code: 10002): Unknown Application
I traced it down to this bit of the code, specifically line 75.
The endpoint requires the application id, which is not guaranteed to be the same as the bot's user ID.
I suspect that this is not the only point in the codebase with this issue.
Is the code below a new command, how would I add slash commands to and existing @bot.command() command?
@slash.slash(name="test")
async def _test(ctx: SlashContext):
embed = discord.Embed(title="embed test")
await ctx.send(content="test", embeds=[embed])
Traceback (most recent call last):
File "C:\Users\ignac\OneDrive\Pulpit\BOT\botRewrite.py", line 9, in
from discord_slash import SlashCommand
File "C:\Users\ignac\AppData\Roaming\Python\Python38\site-packages\discord_slash_init_.py", line 11, in
from .client import SlashCommand
File "C:\Users\ignac\AppData\Roaming\Python\Python38\site-packages\discord_slash\client.py", line 6, in
from . import model
File "C:\Users\ignac\AppData\Roaming\Python\Python38\site-packages\discord_slash\model.py", line 8, in
class SlashContext:
File "C:\Users\ignac\AppData\Roaming\Python\Python38\site-packages\discord_slash\model.py", line 64, in SlashContext
allowed_mentions: discord.AllowedMentions = None,
AttributeError: module 'discord' has no attribute 'AllowedMentions'
Hello !
Sorry to disturb you.
I use the 1.5.1 version of discord.py and 1.0.6 version of discord-py-slash-command, and I have this error :
Ignoring exception in on_socket_response
Traceback (most recent call last):
File "C:\Users\MOI\AppData\Roaming\Python\Python38\site-packages\discord\client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "C:\Users\MOI\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord_slash\client.py", line 482, in on_socket_response
if ctx.guild.id not in selected_cmd.allowed_guild_ids:
AttributeError: 'int' object has no attribute 'id'
This error is raised when the bot/app is not in the guild where the slash command was made, because at this line (45 and 56), if the guild is not found, ctx.guild
has the id value and not the Guild
object.
So I tried to find a solution in my pull request #36 .
Thank you for reading, have a nice day !
Hi, I recently started using this extension to try out Discord's new slash commands feature. I noticed my commands weren't showing up in the Discord client when entering /
into the chat box, so I went through the issues and found #3 and #4.
Leastrio said in #4:
You need to either use the libs built in way or send a post request to discords api, https://discord.com/developers/docs/interactions/slash-commands#create-guild-application-command
I noticed the lib has discord_slash.utils.manage_commands
which contains methods for adding slash commands with the Discord API, I assume this is what Leastrio was referring to. However, I don't understand how to use this in junction with my slash.slash()
decorated functions or really just the lib in general. This leads to me to have questions like, "How do I link a command to a function? What's the purpose of slash.slash()
's parameters if they're seemingly overwritten by discord_slash.utils.manage_commands.add_slash_command
?"
All help is appreciated, thank you!
@slash.slash(name="test", description="test case.", guild_ids=guild_ids)
async def test(ctx: SlashContext):
await ctx.guild.me.edit(nick='newnick')
await ctx.send('test', tts=True)
await ctx.guild.me.edit(nick='oldnick')
This results in the message being sent but no TTS. It was working fine before the last release. Is it something wrong on my end?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.