A simple discord slash command handler for for discord.py.

Overview


discord-py-slash-command

A simple discord slash command handler for discord.py

Codacy Badge Discord

About ⦿ Installation ⦿ Disclaimer ⦿ Examples ⦿ Documentation ⦿ Discussions

Note that master branch is in development. This means the example, etc. in the bottom is not 100% compatible with the release version. For release version, please see hotfix-command-register branch.

About

Discord Slash Commands are a new implementation for the Bot API that utilize the forward-slash "/" symbol. Released on 15 December 2020, many bot developers are still learning to learn how to implement this into their very own bots. This command handler aims to help serve as a guidance for those looking into wanting to add these new slash commands into their bots for those that use discord.py, building off of the current library code and substituting its own for where it's needed. discord-py-slash-command stands as the first public slash command handler library to be made for Discord Bot API libraries.

Installation

You are able to easily install the discord-py-slash-command library by using the given PIP line below:

pip install -U discord-py-slash-command

Disclaimer

Since slash commands are currently not officially released (They're in public beta), there will be many breaking changes to this extension which may cause it to become unstable. It is recommended to wait until discord officially releases slash commands. Waiting until Release 1.1.0, which is planned to have most features implemented in the code, is also recommended. At this time, the developer of discord.py has no plans to officially support slash commands for their library.

Examples

Quick Startup

This is a quick startup method towards using slash commands.

import discord
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext

bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
slash = SlashCommand(bot)

@slash.slash(name="test")
async def _test(ctx: SlashContext):
    embed = discord.Embed(title="embed test")
    await ctx.send(content="test", embeds=[embed])

bot.run("discord_token")

Advanced

This offers implementation of the slash command library in the usage of a cog.

# bot.py
from discord.ext import commands
from discord_slash import SlashCommand

bot = commands.Bot(command_prefix="prefix")
slash = SlashCommand(bot, override_type = True)

bot.load_extension("cog")
bot.run("TOKEN")

# cog.py
import discord
from discord.ext import commands
from discord_slash import cog_ext, SlashContext

class Slash(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @cog_ext.cog_slash(name="test")
    async def _test(self, ctx: SlashContext):
        embed = discord.Embed(title="embed test")
        await ctx.send(content="test", embeds=[embed])

def setup(bot):
    bot.add_cog(Slash(bot))
Comments
  • [BUG] TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

    [BUG] TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

    Describe the bug message should delete but cannot find id of message Reproducing steps These are the steps I took in order to produce this bug, which should be able to be reproduced for everyone else as well.

    1. Import the module in Python.
    2. Create a client variable for the library.
    3. Try creating a slash command.
    4. send a message
    5. Delete the message
    6. See the traceback error given in the terminal or logger file.

    What's normally expected The message should be deleted

    What actually happened Instead, I received this traceback error given from my Python terminal:

    Traceback (most recent call last):
      File "/root/inter/main.py", line 233, in buy
        await n.delete()
      File "/usr/local/lib/python3.8/dist-packages/interactions/api/models/message.py", line 335, in delete
        message_id=int(self.id), channel_id=int(self.channel_id), reason=reason
    TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
    

    code: https://pastebin.com/qfJU76TF Versions newest unstable wait_for

    bug 
    opened by dontbanmeplz 31
  • refactor: split `_dispatch_event` in two methods

    refactor: split `_dispatch_event` in two methods

    About

    This pull request splits _dispatch_event in two other methods.

    Checklist

    • [x] I've ran pre-commit to format and lint the change(s) made.
    • [x] I've checked to make sure the change(s) work on 3.8.6 and higher.
    • [ ] This fixes/solves an Issue (If existent):.
      • resolves #
    • I've made this pull request for/as: (check all that apply)
      • [x] Documentation
      • [ ] Breaking change
      • [x] New feature/enhancement
      • [ ] Bugfix
    opened by Damego 21
  • Weird issue.

    Weird issue.

    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}
    
    help wanted 
    opened by thomaskeig 21
  • [REQUEST] Limiting cache

    [REQUEST] Limiting cache

    What is the feature you're proposing? As of right now, caching has no limit. I feel like there should be a way to set a limit for each type of cache, preferably in the Client instance.

    Something like:

    bot = interactions.Client(
        ...,
        cache_limits=interactions.CacheLimits(
            messages=100,
            guilds=50,
            ...
        )
    )
    

    This is the best thing that I can think of off the top of my head. Another way is to ~~do what dis-snek did~~ do something with kwargs and have something like this:

    bot = interactions.Client(
        ...,
        message_cache=100,
        guild_cache=50,
        ...
    )
    

    Additional Information

    • [ ] My feature request is related to an existing Issue.
      • Issue (if referenceable):
    documentation enhancement 
    opened by Toricane 19
  • feat: create basic functionality for Extensions

    feat: create basic functionality for Extensions

    Expands Extension.new and adds new functions to mimic client decorators

    About

    This pr adds in basic functionality for the Extension class, along with decorators for commands/components/listeners Marked as a draft because some things are missing, like properly removing commands on removal of the Extension Any suggestions on improvements are welcome

    Checklist

    • [ ] I've ran pre-commit to format and lint the change(s) made.
    • [x] I've checked to make sure the change(s) work on 3.8.6 and higher.
    • [x] This fixes/solves an Issue.
    • [x] I've made this pull request for/as: (check all that apply)
      • [ ] Documentation
      • [ ] Breaking change
      • [x] New feature/enhancement
      • [ ] Bugfix
    documentation enhancement pending breaking priority 
    opened by Catalyst4222 19
  • Slash command greyed out even though I have permission

    Slash command greyed out even though I have permission

    I created a simple bot with this module, and I believe this is a bug. I was working with this bot, everything working normally, when suddenly my permission based commands were greyed out. I can't pinpoint the exact change that caused the issue, but it happened when I added a command I think. I'm still in the process of debugging, but believe this is a bug. What I have tried:

    • [x] Deleting the commands
    • [x] Unloading the cog
    • [x] Deleting all slash commands
    • [x] Restarting the bot
    • [x] Using a different bot

    Let me know if I should try any new debugging steps

    opened by zurgeg 19
  • Add Application Permissions Support

    Add Application Permissions Support

    About this pull request

    Adds support for the slash command permissions. I wanted it for my own bot, got it into a workable state, so I figure I can open a PR to add its feature for everyone if accepted. Feel free to review and test. Let me know of any feedback, happy to accept critics and improve the code 😄.

    Changes

    • Add setting of default_permission and permissions option for slash command.
    • Add get_all_command_permissions and put_command_permissions method to http module.
    • Add support for storing permission data in CommandObject.
    • Add create_guild_permissions and create_permission utils method to facility defining permissions.
    • Add PermissionsData class used for checking for any permission updates since last sync, similar to how CommandData works.
    • Add logic to registers permissions in the sync_all_commands method.
    • Add SlashCommandPermissionsType enum class to match discord api's ApplicationCommandPermissionType.
    • Add relevant documentation needed for the code changes.

    Example decorator with subcommand:

    @slash.subcommand(
        guild_ids=[750556940127436880, 823454213089787914],
        base="test", 
        base_desc="test",  
        subcommand_group="group",
        sub_group_desc="group",
        name="sub",
        description="sub"
    )
    @slash.permission(823454213089787914, generate_permissions(allowed_roles=[823851472982376468, 823851440232857600]))
    @slash.permission(750556940127436880, generate_permissions(allowed_roles=[778838673666998292]))
    async def test_sub(ctx):
        await ctx.send("test_sub")
    

    Checklist

    • [ ] I've checked this pull request runs on Python 3.6.X.
    • [ ] This fixes something in Issues.
      • Issue:
    • [x] This adds something new.
    • [x] There is/are breaking change(s).
    • [x] (If required) Relevant documentation has been updated/added.
    • [ ] This is not a code change. (README, docs, etc.)
    enhancement priority 
    opened by benwoo1110 17
  • Auto delete could potentially make a lot of requests

    Auto delete could potentially make a lot of requests

    The Problem

    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.

    Proposed solution

    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

    Possible alternatives

    • Proposed solution above but default to False
    • Proposed solution above but require it
    • Leave it as is, causing high traffic at startup for large bots, and possibly reaching rate limits
    • The ideal solution would be an endpoint that could be used to get all guilds with commands currently. There's an issue on the discord repo but no one has responded yet
    help wanted 
    opened by AnotherCat 15
  • refactor!: use `attrs.asdict` as a way to get json data of the object

    refactor!: use `attrs.asdict` as a way to get json data of the object

    About

    This pull request:

    1. Makes DictSerializerMixin._json as a property with using attrs.asdict to get json data of the object.
    2. Solves all troubles with editing json. You don't need to edit json anymore lol.
    3. Removes ComponentMixin and json modifing in a lot of objects like Embed.
    4. Limited using _json property in some places: using walrus operators and objects instead of dicts(wsclient).
    5. Removes outdated(since attrs added) code like here

    Checklist

    • [x] The pre-commit code linter has been run over all edited files to ensure the code is linted.
    • [x] I've ensured the change(s) work on 3.8.6 and higher.

    I've made this pull request: (check all that apply)

    • [ ] For the documentation
    • [ ] To add a new feature
    • [x] As a general enhancement
    • [x] As a refactor of the library/the library's code
    • [ ] To fix an existing bug
    • [ ] To resolve #ISSUENUMBER

    This is:

    • [x] A breaking change
    enhancement 
    opened by Damego 14
  • fix!: fix ``guilds`` property in client

    fix!: fix ``guilds`` property in client

    About

    Fixes an error occurring because of the cached guild object already having an HTTPClient

    Checklist

    • [x] I've ran pre-commit to format and lint the change(s) made.
    • [x] I've checked to make sure the change(s) work on 3.8.6 and higher.
    • [x] This fixes/solves an Issue.
      • (If existent): #664
    • [ ] I've made this pull request for/as: (check all that apply)
      • [ ] Documentation
      • [ ] Breaking change
      • [ ] New feature/enhancement
      • [x] Bugfix
    opened by EdVraz 12
  • Heartbeat dropping crashes the bot until manually restarted

    Heartbeat dropping crashes the bot until manually restarted

    This has been discussed in the Discord server, but I thought I'd file an issue for the sake of completeness.

    When a bot can't get a heartbeat, there's no connection logic to reconnect the bot afterwards. This means that bots, even on stable connections (I'm using a Contabo VPS), can have trouble staying online for any extended period of time.

    For now, as a bodge, I'm testing using GNU timeout to restart my bot by force as a pre-emptive measure - if anyone wants the shell script, let me know

    bug 
    opened by dxf 12
  • Delay token

    Delay token

    About

    This pull request adds the ability to pass the token in .start, while still keeping the old way for compatibility

    Checklist

    • [x] The pre-commit code linter has been run over all edited files to ensure the code is linted.
    • [ ] I've ensured the change(s) work on 3.8.6 and higher.
    • [ ] I have added the versionadded, versionchanged and deprecated to any new or changed user-facing function I committed.

    Pull-Request specification

    I've made this pull request: (check all that apply)

    • [ ] For the documentation
    • [ ] To add a new feature
    • [x] As a general enhancement
    • [ ] As a refactor of the library/the library's code
    • [ ] To fix an existing bug
    • [ ] To resolve #ISSUENUMBER

    This is:

    • [ ] A breaking change
    opened by Catalyst4222 0
  • feat: Add `channel` & `guild` properties for `VoiceState`

    feat: Add `channel` & `guild` properties for `VoiceState`

    About

    This pull request adds channel & guild properties for VoiceState. Uses cached guild & channel if exists for get_channel and get_guild methods

    Checklist

    • [x] The pre-commit code linter has been run over all edited files to ensure the code is linted.
    • [ ] I've ensured the change(s) work on 3.8.6 and higher.
    • [ ] I have added the versionadded, versionchanged and deprecated to any new or changed user-facing function I committed.

    Pull-Request specification

    I've made this pull request: (check all that apply)

    • [ ] For the documentation
    • [x] To add a new feature
    • [x] As a general enhancement
    • [x] As a refactor of the library/the library's code
    • [ ] To fix an existing bug
    • [ ] To resolve #ISSUENUMBER

    This is:

    • [ ] A breaking change
    enhancement 
    opened by Damego 0
  • [BUG] Error starting when using scope param in command decorator

    [BUG] Error starting when using scope param in command decorator

    Describe the bug.

    When starting the bot with a command that has a scope as a param specified it results in a KeyError:

    Could not prepare the client:
    Traceback (most recent call last):
      File "----/venv/lib/python3.10/site-packages/interactions/client/bot.py", line 404, in _ready
        await self.__sync()
      File "----/venv/lib/python3.10/site-packages/interactions/client/bot.py", line 621, in __sync
        if _guild_command["name"] not in __check_guild_commands[_guild_id]:
    KeyError: None
    

    List the steps.

    1. Create a bot:
    ids = 8210301307------
    bot = interactions.Client(token="", default_scope=ids)
    
    1. Create a command with a scope param:
    @bot.command(
        name="test",
        description="test",
        scope=ids
    )
    async def _test(ctx):
        await ctx.send("test")
    
    
    1. run the bot
    2. see Traceback

    What you expected.

    The command should be correctly registered for the guilds provided in the default_scope and command scope

    File client/bot.py, line 517, in __resolve_commands:

    if cmd.default_scope and self._default_scope:
        cmd.scope = (
            cmd.scope.extend(self._default_scope)
            if isinstance(cmd.scope, list)
            else self._default_scope
        )
    

    cmd.scope.extend(self._default_scope) extends the cmd.scope, but then sets cmd.scope to its return value, which is None. This overrides the scope, resulting in None being passed as the scope to command in full_data. This passes None as the guild_id to the ApplicationCommand, which is used in when getting a guild_commands _guild_id => KeyError here if _guild_command["name"] not in __check_guild_commands[_guild_id]:

    replace

    if cmd.default_scope and self._default_scope:
      cmd.scope = (
          cmd.scope.extend(self._default_scope)
          if isinstance(cmd.scope, list)
          else self._default_scope
      )
    

    with

    if cmd.default_scope and self._default_scope:
      if isinstance(cmd.scope, list):
        cmd.scope.extend(self._default_scope)
      else:
        cmd.scope = self._default_scope
    

    What you saw.

    Instead, I received this traceback error given from my Python terminal:

    Could not prepare the client:
    Traceback (most recent call last):
      File "----/venv/lib/python3.10/site-packages/interactions/client/bot.py", line 404, in _ready
        await self.__sync()
      File "----/venv/lib/python3.10/site-packages/interactions/client/bot.py", line 621, in __sync
        if _guild_command["name"] not in __check_guild_commands[_guild_id]:
    KeyError: None
    

    What version of the library did you use?

    stable

    Version specification

    4.3.4

    Code of Conduct

    • [X] I agree to follow the contribution requirements.
    bug 
    opened by H3rmt 1
  • fix(attrs): add factory value to interaction resolved data

    fix(attrs): add factory value to interaction resolved data

    About

    This pull request fixes error from this thread Tested locally:

    from interactions import InteractionResolvedData
    
    data = InteractionResolvedData()
    print("a" in data.members)
    

    Checklist

    • [ ] The pre-commit code linter has been run over all edited files to ensure the code is linted.
    • [ ] I've ensured the change(s) work on 3.8.6 and higher.

    I've made this pull request: (check all that apply)

    • [ ] For the documentation
    • [ ] To add a new feature
    • [ ] As a general enhancement
    • [ ] As a refactor of the library/the library's code
    • [x] To fix an existing bug
    • [ ] To resolve #ISSUENUMBER

    This is:

    • [ ] A breaking change
    bug 
    opened by Damego 0
  • refactor!: Change type of permissions attrs to `Permissions`

    refactor!: Change type of permissions attrs to `Permissions`

    About

    This pull request changes the type of permissions attribute of the most dataclasses to Permissions type. Case when you can't change perms for Overwrite Additionally fixes wrong check for type parameter in Channel.add_permission_overwrite.

    Checklist

    • [x] The pre-commit code linter has been run over all edited files to ensure the code is linted.
    • [x] I've ensured the change(s) work on 3.8.6 and higher.

    I've made this pull request: (check all that apply)

    • [ ] For the documentation
    • [ ] To add a new feature
    • [x] As a general enhancement
    • [x] As a refactor of the library/the library's code
    • [x] To fix an existing bug
    • [ ] To resolve #ISSUENUMBER

    This is:

    • [x] A breaking change
    bug enhancement 
    opened by Damego 2
  • feat: Add support for age-restricted commands

    feat: Add support for age-restricted commands

    About

    Title.

    Checklist

    • [x] The pre-commit code linter has been run over all edited files to ensure the code is linted.
    • [x] I've ensured the change(s) work on 3.8.6 and higher.

    I've made this pull request: (check all that apply)

    • [ ] For the documentation
    • [x] To add a new feature
    • [x] As a general enhancement
    • [ ] As a refactor of the library/the library's code
    • [ ] To fix an existing bug
    • [ ] To resolve #ISSUENUMBER

    This is:

    • [ ] A breaking change
    enhancement 
    opened by Damego 0
Releases(4.4.0-beta.1)
Owner
Just a normal high school student in South Korea. I do Python, am learning Java, and will learn C.
null
A Hikari command handler for people who love ducks.

duckari A Hikari command handler made with love by ducks. Currently Duckari is work in progress. Documentation is WIP. The wiki is no longer used as d

null 2 Oct 9, 2022
A cd command that learns - easily navigate directories from the command line

NAME autojump - a faster way to navigate your filesystem DESCRIPTION autojump is a faster way to navigate your filesystem. It works by maintaining a d

William Ting 14.5k Jan 3, 2023
A command-line based, minimal torrent streaming client made using Python and Webtorrent-cli. Stream your favorite shows straight from the command line.

A command-line based, minimal torrent streaming client made using Python and Webtorrent-cli. Installation pip install -r requirements.txt It use

Jonardon Hazarika 17 Dec 11, 2022
commandpack - A package of modules for working with commands, command packages, files with command packages.

commandpack Help the project financially: Donate: https://smartlegion.github.io/donate/ Yandex Money: https://yoomoney.ru/to/4100115206129186 PayPal:

null 4 Sep 4, 2021
AML Command Transfer. A lightweight tool to transfer any command line to Azure Machine Learning Services

AML Command Transfer (ACT) ACT is a lightweight tool to transfer any command from the local machine to AML or ITP, both of which are Azure Machine Lea

Microsoft 11 Aug 10, 2022
Ros command - Unifying the ROS command line tools

Unifying the ROS command line tools One impairment to ROS 2 adoption is that all

null 37 Dec 15, 2022
A Python-based command prompt concept which includes windows command emulation.

PythonCMD A Python-based command prompt concept which includes windows command emulation. Current features: echo: Input your message and it will be cl

null 1 Feb 5, 2022
Simple command line tool for text to image generation using OpenAI's CLIP and Siren (Implicit neural representation network)

Simple command line tool for text to image generation using OpenAI's CLIP and Siren (Implicit neural representation network)

Phil Wang 4.4k Jan 9, 2023
A simple python script to execute a command when a YubiKey is disconnected

YubiKeyExecute A python script to execute a command when a YubiKey / YubiKeys are disconnected. ‏‏‎ ‎ How to use: 1. Download the latest release and d

null 6 Mar 12, 2022
A simple command line dumper written in Python 3.

A simple command line dumper written in Python 3.

ImFatF1sh 1 Oct 10, 2021
3DigitDev 29 Jan 17, 2022
Simple command-line implementation of minesweeper

minesweeper This is a Python implementation of 2-D Minesweeper! Check out the tutorial here: https://youtu.be/Fjw7Lc9zlyU You start a game by running

Kylie 49 Dec 10, 2022
A simple command line tool written in python to manage a to-do list

A simple command line tool written in python to manage a to-do list Dependencies: python Commands: todolist (-a | --add) [(-p | --priority)] [(-l | --

edwloef 0 Nov 2, 2021
A simple automation script that logs into your kra account and files your taxes with one command

EASY_TAX A simple automation script that logs into your kra account and files your taxes with one command Currently works for Chrome users. Will creat

leon koech 13 Sep 23, 2021
jrnl is a simple journal application for the command line.

jrnl To get help, submit an issue on Github. jrnl is a simple journal application for the command line. You can use it to easily create, search, and v

jrnl 5.7k Dec 31, 2022
A super simple terminal command shortener 🐟

pcmd A super simple terminal command shortener ?? Source code : https://github.com/j0fiN/pcmd Documentation : https://j0fin.github.io/pcmd About Durin

null 9 Mar 2, 2022
A simple command-line tracert implementation in Python 3 using ICMP packets

Traceroute A simple command-line tracert implementation in Python 3 using ICMP packets Details Traceroute is a networking tool designed for tracing th

James 3 Jul 16, 2022
Limit your docker image size with a simple CLI command. Perfect to be used inside your CI process.

docker-image-size-limit Limit your docker image size with a simple CLI command. Perfect to be used inside your CI process. Read the announcing post. I

wemake.services 102 Dec 14, 2022
A simple command line tool for changing the icons of folders or files on MacOS.

Mac OS File Icon Changer Description A small and simple script to quickly change large amounts or a few files and folders icons to easily customize th

Eroxl 3 Jan 2, 2023