'How to get the nickname of the author of the message in the discord using Discord.net 2.2.0 C#
How can I get the nickname of the author of the message in Discord using Discord.net 2.2.0.
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;
}
A long search and reading of the documentation unfortunately gave me nothing.
Solution 1:[1]
If you want to get the authors nick name you can cast it to SocketGuildUser, but beware, it can be null if it's a DM.
var UNick = (message.Author as SocketGuildUser).Nickname;
Also you probably should check if the message is from a user and not system
if (!(sockMessage is SocketUserMessage msg))
return;
So your code will look something like this
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 msg.Channel.SendMessageAsync("Test");
}
StartBit = 1;
// I usualy check if the author is not bot, but you can change that back
if (msg.Author.IsBot)
return;
var UName = author.Username;
var UNick = author.Nickname;
var UID = author.Id;
}
Credit to Anu6is
Solution 2:[2]
Try casting your message to an SocketUserMessage. I have attached the correct code for that and please edit your post, so that the code is presented correctly.
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | VollRahm |
