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.
WebApp Maker make web apps (Duh). It is open source and make with python and shell.

WebApp Maker make web apps (Duh). It is open source and make with python and shell. This app can take any website and turn it into an app. I highly recommend turning these few websites into webapps:

2 Jan 09, 2022
topalias - Linux alias generator from bash/zsh command history with statistics, written on Python.

topalias topalias - Linux alias generator from bash/zsh command history with statistics, written on Python. Features Generate short alias for popular

Sergey Chudakov 38 May 26, 2022
Postgres CLI with autocompletion and syntax highlighting

A REPL for Postgres This is a postgres client that does auto-completion and syntax highlighting. Home Page: http://pgcli.com MySQL Equivalent: http://

dbcli 10.8k Jan 02, 2023
(BionicLambda Universal SHell) A simple shell made in Python. Docs and possible C port incoming.

blush 😳 (BionicLambda Universal SHell) A simple shell made in Python. Docs and possible C port incoming. Note: The Linux executables were made on Ubu

3 Jun 30, 2021
CLI to show end-of-life dates for tools and technologies.

Python 3.9+ interface to endoflife.date to show end-of-life dates for tools and technologies.

Hugo van Kemenade 32 Jan 06, 2023
a-shell: A terminal for iOS, with multiple windows

a-shell: A terminal for iOS, with multiple windows

Nicolas Holzschuch 1.7k Jan 02, 2023
A CLI tool that scans through a directory and organizes all loose files into folders by file type.

Organizer CLI Organizer CLI is a python command line tool that goes through a given directory and organizes all un-folder bound files into folders by

Mulaza Jacinto 6 Dec 14, 2022
CLI tool to develop StarkNet projects written in Cairo

⛵ Nile Navigate your StarkNet projects written in Cairo. Installation pip install cairo-nile Usage Install Cairo Use nile to install a given version o

Martín Triay 305 Dec 30, 2022
Joji convert a text to corresponding emoji if emoji is available

Joji Joji convert a text to corresponding emoji if emoji is available How it Works ? 1. There is a json file with emoji names as keys and correspondin

Gopikrishnan Sasikumar 28 Nov 26, 2022
Easily turn single threaded command line applications into a fast, multi-threaded application with CIDR and glob support.

Easily turn single threaded command line applications into a fast, multi-threaded application with CIDR and glob support.

Michael Skelton 1k Jan 07, 2023
Command-line interface to PyPI Stats API to get download stats for Python packages

pypistats Python 3.6+ interface to PyPI Stats API to get aggregate download statistics on Python packages on the Python Package Index without having t

Hugo van Kemenade 140 Jan 03, 2023
A terminal tool for git. When we use git, do you feel very uncomfortable with too long commands

PIGIT A terminal tool for git. When we use git, do you feel very uncomfortable with too long commands. For example: git status --short, this project c

Zachary 1 Apr 09, 2022
EODAG is a command line tool and a plugin-oriented Python framework for searching, aggregating results and downloading remote sensed images while offering a unified API for data access regardless of the data provider

EODAG (Earth Observation Data Access Gateway) is a command line tool and a plugin-oriented Python framework for searching, aggregating results and downloading remote sensed images while offering a un

CS GROUP 205 Jan 03, 2023
An ZFS administration tool inspired on Midnight commander

ZC - ZFS Commander An ZFS administration tool inspired on Midnight commander Work in Progress Description ZFS Commander is a simple front-end for the

34 Dec 07, 2022
Sebuah tools agar tydak menjadi sider :v vrohh

Sebuah tools agar tydak menjadi sider :v vrohh

xN7-SEVEN 1 Mar 27, 2022
A dec-bin converter uses 2's complement.

2's Complement Dec-Bin Converter A dec-bin converter uses 2's complement. Visit my Medium Post. What is 2's complement? Two's complement is the most c

C.H Jacky 9 Mar 01, 2022
A very simple python script to encode and decode PowerShell one-liners.

PowerShell Encoder A very simple python script to encode and decode PowerShell one-liners. I used Raikia's PowerShell encoder ALOT, but one day it wen

John Tear 5 Jul 29, 2022
Another (unofficial) Qt CLI Installer on multi-platforms

Another Qt installer(aqt) Release: Documentation: Test status: and Coverage: This is a utility alternative to the official graphical Qt installer, for

Hiroshi Miura 528 Jan 02, 2023
A Python module and command-line utility for converting .ANS format ANSI art to HTML

ansipants A Python module and command-line utility for converting .ANS format ANSI art to HTML. Installation pip install ansipants Command-line usage

4 Oct 16, 2022
spade is the next-generation networking command line tool.

spade is the next-generation networking command line tool. Say goodbye to the likes of dig, ping and traceroute with more accessible, more informative and prettier output.

Vivaan Verma 5 Jan 28, 2022