简体   繁体   中英

How do I create aliases in discord.py cogs?

I have a discord.py cog set up, ready to use. There is one issue, how do I set up aliases for commands? I'll give you my code below to see what else I need to do:

# Imports
from discord.ext import commands
import bot  # My own custom module


# Client commands
class Member(commands.Cog):
    def __init__(self, client):
        self.client = client

    # Events
    @commands.Cog.listener()
    async def on_ready(self):
        print(bot.online)

    # Commands
    @commands.command()
    async def ping(self, ctx):
        pass


# Setup function
def setup(client):
    client.add_cog(Member(client))

In this case, how should I set up an alias for the ping command under @commands.command()

discord.ext.commands.Command objects have a aliases attribute. Here's how to use it:

@commands.command(aliases=['testcommand', 'testing'])
async def test(self, ctx):
    await ctx.send("This a test command")

You'll then be able to invoke your command by writing !test , !testcommand or !testing (if your command prefix is ! ).
Also, if you plan on coding a log system, Context objects have a invoked_with attribute which takes the aliase the command was invoked with as a value.

Reference: discord.py documentation


Edit: If you want to make your cog admin only, you can overwrite the existing cog_check function that will trigger when a command from this cog is invoked:

from discord.ext import commands
from discord.utils import get

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

    async def check_cog(self, ctx):
        admin = get(ctx.guild.roles, name="Admin")
        #False -> Won't trigger the command
        return admin in ctx.author.role

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM