首页 > 解决方案 > Discord.NET 如果消息附加了文件,请等到它上传并删除它

问题描述

我的问题是这个;我正在使用 Discord.NET 1.0.2 制作一个机器人,当用户发送消息时,检查该消息是否附加了文件,然后将其删除。现在我做到了,但有一个问题。在文件上传之前,该消息不会被删除。我尝试了各种方法,但我无法想出如何等到文件上传后再删除消息的解决方案。任何帮助是极大的赞赏。这就是我正在使用的:

private async Task CheckForImageMessage(SocketMessage s)
{
        var msg = s as SocketUserMessage;
        if (msg == null) return;
        var context = new SocketCommandContext(_client, msg);
        if (context.Message.Attachments.ElementAt(0) != null)
        {

        }
    }
}

标签: c#discord.net

解决方案


首先,您没有发出命令,因此您根本没有理由使用命令上下文 - 您已经可以访问消息sAttachments集合存在于IMessage界面下)。

其次,您不可能在文件上传之前拦截消息。如果我理解正确,您想删除任何包含附件的邮件吗?如果是这样,集合上的Any方法就可以了。Attachments

private async Task RemoveAttachmentMsgsAsync(SocketMessage msg)
{
    // check if the source channel is a message channel in a guild
    if (msg.Channel is SocketTextChannel textChannel)
    {
        // get the current user to check for permissions
        var currentUser = textChannel.Guild.CurrentUser;
        // bail if the bot does not have manage message permission
        if (!currentUser.GetPermissions(textChannel).ManageMessages) return;
    }
    // if we made it this far, we can assume that the bot has permission for
    // the channel (including DM channel)
    // use LINQ Any to check if the attachment contains anything
    if (msg.Attachments.Any())
        await msg.DeleteAsync();
}

推荐阅读