Skip to content

Instantly share code, notes, and snippets.

@XuaTheGrate
Created November 27, 2020 04:10
Show Gist options
  • Save XuaTheGrate/0d8eb383038321626616a809791e0642 to your computer and use it in GitHub Desktop.
Save XuaTheGrate/0d8eb383038321626616a809791e0642 to your computer and use it in GitHub Desktop.
Another custom command handler
"""
The MIT License (MIT)
Copyright (c) 2020 XuaTheGrate
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
import collections
from discord.ext import commands
class CustomCommands(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.custom_commands = collections.defaultdict(dict)
@commands.group(aliases=('cc',))
@commands.guild_only()
async def customcommand(self, ctx):
"""Group command for custom command related commands."""
@customcommand.command()
@commands.guild_only()
async def add(self, ctx, name: commands.clean_content, *, response: commands.clean_content):
"""Adds a new custom command."""
if self.bot.get_command(name) is not None:
await ctx.send("This command is already a bot command!")
return
if self.custom_commands[ctx.guild.id].get(name) is not None:
await ctx.send("This command is already a custom command!")
return
self.custom_commands[ctx.guild.id][name] = response
await ctx.send(f"Added the command {name!r}!")
@customcommand.command()
@commands.guild_only()
async def remove(self, ctx, *, name: commands.clean_content):
"""Removes a custom command."""
self.custom_commands[ctx.guild.id].pop(name, None)
await ctx.message.add_reaction("\u2705")
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error, commands.CommandNotFound):
custom = ctx.invoked_with
resp = self.custom_commands[ctx.guild.id].get(custom)
if resp is not None:
await ctx.send(resp)
else:
await ctx.send(error)
def setup(bot):
bot.add_cog(CustomCommands(bot))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment