有没有一种方法可以使Discord.net中的命令超载?

时间:2019-12-09 19:23:48

标签: c# discord.net

我的Discord Bot有两个模块:第一个是UserModule,用户可以执行其中的每个命令,第二个是AdminModule,服务器管理员可以在其中自定义并设置机器人。现在,我在UserModule中获得了命令Money,它使机器人告诉执行者他有多少钱。但是管理员还有另外一个money命令:

[Group("Money")]
    class Credits : ModuleBase
    {
        [Command("add")]
        public void AddMoney(IGuildUser user, int amount)
        {
            int money = Convert.ToInt32(DBConnector.GetInstance().GetDBData
                ($"SELECT Money FROM Users WHERE UserID = {user.Id} AND ServerID = {Context.Guild.Id}")[0]);

            //This will be read from the database in the future
            bool capped = false;

            if (capped)
            {
                int maxAmount = Convert.ToInt32(DBConnector.GetInstance().GetDBData
                ($"SELECT Money FROM Users WHERE UserID = {user.Id} AND ServerID = {Context.Guild.Id}")[0]);

                if (money + amount > maxAmount)
                {
                    amount = maxAmount - money;
                }
            }

            DBConnector.GetInstance().ExecuteCommand($"UPDATE Users SET Money=Money+{amount} WHERE UserID = {user.Id} AND ServerID = {Context.Guild.Id}");
        }
//some more commands
...

这是AdminModule中的子模块,显然用于手动向用户添加或删除资金。但是,当我想用​​//money add @user 10测试命令时,出现了错误,即“输入文本有太多参数”。 这表明该机器人使用了UserCommand而不是AdminCommand,所以我想知道如何使该机器人实现

"Hey, that command has a usermention and an integer. This is also the case for the admin command. Let me execute that one"

1 个答案:

答案 0 :(得分:1)

如果我看这个问题,针对这个问题,您有两种解决方案。

1。解决方案

我假设您的不同用户具有不同的角色。因此,您的管理员获得了名为Server Admin或类似角色。您可以创建自定义PreconditionAttribute,有关示例,请参见documentation。对于提供的所有角色,此属性都可能返回错误。这样,您可以“禁止”管理员使用//money add命令。然后是另一个仅允许管理员执行该版本的管理员版本。

2。解决方案

这个比较脏,不建议使用。您只能按住一个Add命令,其中包含普通用户和管理员用户的逻辑。使用if语句,您可以检查他们的角色并决定下一步。

我很确定第一个解决方案会更好地满足您的需求。