Discord bot C#没有执行/读取命令

时间:2017-09-04 19:27:59

标签: c# discord

using Discord.Commands;
using Discord;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Remoting.Contexts;
using System.ServiceModel.Channels;

namespace Leaf
{
    class Leaf
    {
        [Command("!!Gpurge")]
        [RequireBotPermission(Discord.GuildPermission.ManageMessages)]
        [RequireUserPermission(Discord.GuildPermission.ManageMessages)]
        [Alias("Clear", "delete")]
        public async Task Purge(IUserMessage msg, int num = 100)
        {
        var purgeMessage = await msg.Channel.SendMessageAsync("!!Gpurge");
            var lastMessageID = purgeMessage.Id;
        if (num <= 100)
        {
            var messageToDelete = await msg.Channel.GetMessagesAsync(lastMessageID, Direction.Before, 15).OfType<IUserMessage>().ToList();
            await purgeMessage.DeleteAsync();
        }
    }

**我改为前缀使用!! G with purge是一个命令,用于删除1-100范围内的多条消息,但遗憾的是,它不会在不和谐应用程序中读取或响应

1 个答案:

答案 0 :(得分:0)

对于Discord.NET,检查消息是否是通过前缀的命令应该已经由异步处理程序处理。

如果您按照文档/源代码的示例进行操作,则可以在文件中的某处搜索HandleCommandAsync函数。

基本上从文档的示例中,它看起来像这样:

private async Task HandleCommandAsync(SocketMessage arg)
    {
        // Bail out if it's a System Message.
        var msg = arg as SocketUserMessage;
        if (msg == null) return;

        // Create a number to track where the prefix ends and the command begins
        int pos = 0;
        // Replace the '!' with whatever character
        // you want to prefix your commands with.
        // Uncomment the second half if you also want
        // commands to be invoked by mentioning the bot instead.
        if (msg.HasCharPrefix('!', ref pos) /* || msg.HasMentionPrefix(_client.CurrentUser, ref pos) */)
        {
            // Create a Command Context.
            var context = new SocketCommandContext(_client, msg);

            // Execute the command. (result does not indicate a return value, 
            // rather an object stating if the command executed succesfully).
            var result = await _commands.ExecuteAsync(context, pos, _services);

            // Uncomment the following lines if you want the bot
            // to send a message if it failed (not advised for most situations).
            //if (!result.IsSuccess && result.Error != CommandError.UnknownCommand)
            //    await msg.Channel.SendMessageAsync(result.ErrorReason);
        }
    }

注意部分msg.HasCharPrefix('!', ref pos)
基本上它会在尝试执行命令之前检查消息是否包含您想要的前缀。如果没有,那么它什么都不做 (请注意msg.HasStringPrefix()也存在!)