如何使用Discord.net 2.2.0 C#获取不和谐中消息作者的昵称

时间:2020-06-16 13:50:22

标签: c# discord.net

如何使用Discord.net 2.2.0在Discord中获取消息作者的昵称。

private async Task MessageReceivedAsync(SocketMessage message)
{
    if (StartBit == 0)
    { 
    await message.Channel.SendMessageAsync("Test");
    }
    StartBit = 1;
    // The bot should never respond to itself.
    if (message.Author.Id == _client.CurrentUser.Id)
        return;
    var UName = message.Author.Username;
    var UID = message.Author.Id;
}

不幸的是,长时间搜索和阅读文档对我没有任何帮助。

2 个答案:

答案 0 :(得分:0)

尝试将您的消息投射到SocketUserMessage。我已经附上了正确的代码,请编辑您的帖子,以便正确显示代码。

private async Task MessageReceivedAsync(SocketMessage msg) 
{ 
    SocketUserMessage message = msg as SocketUserMessage;

    if (StartBit == 0) 
    { 
        await message.Channel.SendMessageAsync("Test");
    } 
    StartBit = 1; 

    // The bot should never respond to itself.
    if (message.Author.Id == _client.CurrentUser.Id) return; 

    var UName = message.Author.Username; 
    var UID = message.Author.Id; 

}

答案 1 :(得分:0)

如果要获得作者的昵称,可以将其强制转换为SocketGuildUser,但是请注意,如果它是DM,则可以为null

var UNick = (message.Author as SocketGuildUser).Nickname;

您可能还应该检查消息是否来自用户而不是系统

if (!(sockMessage is SocketUserMessage msg))
    return;

因此您的代码将如下所示

private async Task MessageReceivedAsync(SocketMessage sockMessage) 
{ 
    // Check if a user posted the message
    if (!(sockMessage is SocketUserMessage msg))
        return;

    // Check if it is not a DM
    if (!(msg.Author as SocketGuildUser author))
        return;

    if (StartBit == 0) 
    { 
        await message.Channel.SendMessageAsync("Test");
    }

    StartBit = 1; 

    // I usualy check if the author is not bot, but you can change that back
    if (message.Author.IsBot) 
        return; 

    var UName = author.Username; 
    var UNick = author.Nickname;
    var UID = author.Id;
}

贷记Anu6is