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.
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 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;
}
Credit to Anu6is
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.