如何在不和谐机器人中添加高级命令

时间:2021-06-06 09:46:35

标签: python discord discord.py

我想向我的不和谐机器人添加高级命令。那么,我怎么能这样做 例如。如果我想使这个命令溢价,我该怎么做

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

1 个答案:

答案 0 :(得分:0)

我了解您正在尝试制作“高级/支持者”命令系统。

这很容易(除非你想设置整个网站和订阅EG: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!")

此命令会将提及的用户添加到列表中!

它会忽略不是你的任何人!

现在我们做同样的事情,但它是删除命令。

@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!")

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

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

首先,从check导入discord.ext

from discord.ext import commands, 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!")

然后,如果您真的想要,您可以让它执行,如果用户没有付费,机器人会以错误消息进行响应:

@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

如果您需要更多帮助,请随时在 Discord 中添加我:LUNA#6969