如何在discord bot中添加高级命令

2024-06-17 10:31:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想向我的discord机器人添加高级命令。那么,我怎么能这样做呢 如果我想让这个命令成为高级命令,那么我如何才能使它成为高级命令呢

@bot.command()
async def hello(ctx):
  await ctx.send("hi")

Tags: 命令sendhelloasyncdefbot机器人await
1条回答
网友
1楼 · 发布于 2024-06-17 10:31:42

我知道你正在尝试建立一个“高级/支持者”指挥系统

这很容易(除非你想建立整个网站和订阅,例如:mee6)

将命令限制为一组用户的一个好方法是使用数据库和检查功能

您要做的第一件事是在主bot文件所在的文件夹中创建一个文件

让我们称之为“premium_users.json”。在这个文件的内部放上“[]”,这样python就可以打开并读取这个列表

然后在python文件的顶部,放置以下代码“import json”

完成后,我们可以将高级用户添加到列表中

创建一个名为addpremium的新命令(或您选择的任何命令)

此命令的代码为:

@bot.command()
async def addpremium(ctx, user : discord.Member):
    if ctx.author.id != 578485884699: #put your user id on discord here
        return

    with open("premium_users.json") as f:
        premium_users_list = json.load(f)

    if user.id not in premium_users_list:
        premium_users_list.append(user.id)

    with open("premium_users.json", "w+") as f:
        json.dump(premium_users_list, f)

    await ctx.send(f"{user.mention} has been added!")

此命令将向列表中添加提到的用户

它会忽略任何不是你的人

现在我们做同样的操作,但它是remove命令

@bot.command()
async def removepremium(ctx, user : discord.Member):
    if ctx.author.id != 578485884699: #put your user id on discord here
        return

    with open("premium_users.json") as f:
        premium_users_list = json.load(f)

    if user.id in premium_users_list:
        premium_users_list.pop(user.id)
    else:
        await ctx.send(f"{user.mention} is not in the list, so they cannot be removed!")
        return

    with open("premium_users.json", "w+") as f:
        json.dump(premium_users_list, f)

    await ctx.send(f"{user.mention} has been removed!")

现在我们有了添加和删除用户的方法,我们可以让这些用户使用命令了

当您只想让高级用户使用命令时,请执行此操作

首先,从discord.ext.commands导入check

from discord.ext.commands import check

现在我们已经完成了,我们需要做一个检查函数来检查运行命令的用户是否在高级列表中

def check_if_user_has_premium(ctx):
    with open("premium_users.json") as f:
        premium_users_list = json.load(f)
        if ctx.author.id not in premium_users_list:
            return False

    return True

然后,要将此检查应用于高级命令,只需将此代码添加到命令中

@check(check_if_user_has_premium)

因此,该命令将如下所示:

@bot.command()
@check(check_if_user_has_premium)
async def apremiumcommand(ctx):
    await ctx.send("Hello premium user!")

然后,如果您真的想这样做,则如果用户没有premium,则bot会响应一条错误消息:

@apremiumcommand.error
async def apremiumcommand_error(ctx, error):
    if isinstance(error, commands.CheckFailure):
            await ctx.send("Sorry, but you are not a premium user!")
    else:
        raise error

如果您需要更多帮助,请随时添加我的不和谐:露娜#6666

相关问题 更多 >