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.
Because sometimes you need to do it live

doitlive doitlive is a tool for live presentations in the terminal. It reads a file of shell commands and replays the commands in a fake terminal sess

Steven Loria 3.2k Jan 09, 2023
xonsh is a Python-powered, cross-platform, Unix-gazing shell language and command prompt.

xonsh xonsh is a Python-powered, cross-platform, Unix-gazing shell language and command prompt. The language is a superset of Python 3.6+ with additio

xonsh 6.7k Jan 08, 2023
🖍️This is a feature-complete clone of the awesome Chalk (JavaScript) library.

Terminal string styling done right This is a feature-complete clone of the awesome Chalk (JavaScript) library. All credits go to Sindre Sorhus. Highli

Fabian Keller 132 Dec 27, 2022
CLI based diff viewer

Rich Diff CLI based diff viewer

Suresh Kumar 24 Nov 15, 2022
A webmining CLI tool & library for python.

minet is a webmining command line tool & library for python (= 3.6) that can be used to collect and extract data from a large variety of web sources

médialab Sciences Po 165 Dec 17, 2022
A python package to display progress of loops to the user

ProgressBars A python package to display progress of loops to the user. Installation This package can be installed using pip. pip install progressbars

Matthias 3 Jan 16, 2022
Personal and work vim 8 configuration with submodules

vimfiles Windows Vim 8 configuration files based on the recommendations of Ruslan Osipov, Keep Your vimrc file clean and The musings of bluz71. :help

1 Aug 27, 2022
A Python package for Misty II development

Misty2py Misty2py is a Python 3 package for Misty II development using Misty's REST API. Read the full documentation here! Installation Poetry To inst

Chris Scarred 1 Mar 07, 2022
MsfMania is a command line tool developed in Python that is designed to bypass antivirus software on Windows and Linux/Mac in the future

MsfMania MsfMania is a command line tool developed in Python that is designed to bypass antivirus software on Windows and Linux/Mac in the future. Sum

446 Dec 21, 2022
Declarative CLIs with argparse and dataclasses

argparse_dataclass Declarative CLIs with argparse and dataclasses. Features Features marked with a ✓ are currently implemented; features marked with a

Mike DePalatis 29 Dec 06, 2022
Display Images in your terminal with python

Term-Img Display Images in your terminal with python NOTE: This project is a work in progress and not everything on here has actually been implemented

My avatar ;D 118 Jan 05, 2023
Tncli - TON smart contract command line interface

Tncli TON smart contract command line interface State Not working, in active dev

Disintar IO 100 Dec 18, 2022
Ipylivebash - Run shell script in Jupyter with live output

ipylivebash ipylivebash is a library to run shell script in Jupyter with live ou

Ben Lau 6 Aug 27, 2022
A simple cli tool to commit Conventional Commits

convmoji A simple cli tool to commit Conventional Commits. Requirements Install pip install convmoji convmoji --help Examples A conventianal commit co

3 Jul 04, 2022
Python CLI script to solve wordles.

Wordle Solver Python CLI script to solve wordles. You need at least python 3.8 installed to run this. No dependencies. Sample Usage Let's say the word

Rachel Brindle 1 Jan 16, 2022
Unofficial Open Corporates CLI: OpenCorporates is a website that shares data on corporations under the copyleft Open Database License. This is an unofficial open corporates python command line tool.

Unofficial Open Corporates CLI OpenCorporates is a website that shares data on corporations under the copyleft Open Database License. This is an unoff

Richard Mwewa 30 Sep 08, 2022
GanTTY - Project planning from the terminal

GanTTY - Project planning from the terminal

Timeo Sam Pochin 161 Dec 26, 2022
Powerful yet easy command line calculator.

Powerful yet easy command line calculator.

Cruisen 1 Jul 22, 2022
A terminal utility to sort image files based on their characteristics.

About A terminal utility to sort image files based on their characteristics. Motivation This program was developed after I've realized that I had too

José Ferreira 1 Dec 10, 2022
Tmux Based Dropdown Dashboard For Python

sextans It's a private configuration and an ongoing experiment while I use Archlinux. A simple drop down dashboard based on tmux. It includes followin

秋葉 4 Dec 22, 2021