首页 文章

Discord C#Bot - 删除最新消息

提问于
浏览
2

我正在使用我的discord bot的流氓异常包 .

当用户通过命令调用bot时,我希望机器人在执行命令之前删除他的消息 .

所以在我的“MessageReceived”-Event中我到目前为止有这个代码:

private async Task MessageReceived(SocketMessage s)
        {
            var msg = s as SocketUserMessage; // the input

            if (msg == null || !msg.Content.StartsWith("!") || msg.Author.IsBot) // return if null, msg is no command, msg is written by the bot
                return;

            if (msg.Channel is SocketGuildChannel guildChannel) // just delete the command if the msg is written in the guild channel, not a private message channel
                await ??? // Delete the command
}

那么有人知道,在那里写什么=?

2 回答

  • 1

    我可以看到你正在为你的机器人使用Discord.NET API .
    所以从这个文档here .

    看一下 SocketMessage 属性中的 Method 列表 . (顺便说一句,看看网页的右侧,你应该能够看到一个允许你轻松导航的栏)

    如果您想知道我们为什么要查看SocketMessage,那是因为您的委托将在用户发布消息时运行,并且该消息是您的SocketMessage,因此这是您想要删除的内容 .

    您应该能够看到一个名为 DeleteAsync 的方法 . 那就是你想要的 .
    (截图如下)

    对于参数,您可以看到它是 RequestOption 数据类型,默认情况下已为您设置了 null . 您可以更改它,但我强烈建议您使用默认值 .

    同样值得注意的是,如果机器人没有管理消息的权限,机器人将无能为力(并返回异常) .

    Screenshot of the method

  • 1

    示例:

    (对不起,但有些代码字符串是葡萄牙语...这是一个投票系统)

    [Command("Votar")]
            [Summary("Abro uma votação, com opções de Sim e Não.")]
            [RequireBotPermission(ChannelPermission.AddReactions)]
            public async Task NovoVoto([Remainder] string secondPart)
            {
                Log.CMDLog(Context.User.Username, "Votar", Context.Guild.Name);
    
                if (secondPart.Length >= 200)
                {
                    await Context.Channel.SendMessageAsync("Perdão, porém seu voto não deve ter mais de 200 caracteres");
                    return;
                }
    
                var embed = new EmbedBuilder();
                embed.WithColor(new Color(126, 211, 33));
                embed.WithTitle("VOTE AQUI!");
                embed.WithDescription(secondPart);
                embed.WithFooter($"Votação criada por: {Context.User.Username}");
    
                RestUserMessage msg = await Context.Channel.SendMessageAsync("", embed: embed);
                await msg.AddReactionAsync(new Emoji("✅"));
                await msg.AddReactionAsync(new Emoji("❌"));
    
                //Delete the command message from the user
                await Context.Message.DeleteAsync();
            }
    

相关问题