我正在尝试使用Discord.net,但是我无法使这段代码工作...
我的代码
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Discord;
using Discord.WebSocket;
namespace NetflixManager
{
class Program
{
private readonly DiscordSocketClient _client;
static void Main(string[] args)
{
new Program().MainAsync().GetAwaiter().GetResult();
}
public Program()
{
_client = new DiscordSocketClient();
_client.Log += LogAsync;
_client.Ready += ReadyAsync;
_client.MessageReceived += MessageReceivedAsync;
}
public async Task MainAsync()
{
await _client.LoginAsync(TokenType.Bot, File.ReadAllText("Token.txt"));
await _client.StartAsync();
await Task.Delay(-1);
}
private Task LogAsync(LogMessage log)
{
Console.WriteLine(log.ToString());
return Task.CompletedTask;
}
private Task ReadyAsync()
{
Console.WriteLine($"{_client.CurrentUser} is connected!");
return Task.CompletedTask;
}
private async Task MessageReceivedAsync(SocketMessage message)
{
// The bot should never respond to itself.
if (message.Author.Id == _client.CurrentUser.Id)
return;
// The bot should not reply to private messages
if (message.Channel.Name.StartsWith("@"))
return;
// The bot should not reply to bots
if (message.Author.IsBot)
return;
// The bot should not reply to a webhook
if (message.Author.IsWebhook)
return;
// Commands
if (message.Content.StartsWith("!create"))
{
if (message.Author is SocketGuildUser socketUser)
{
SocketGuild socketGuild = socketUser.Guild;
SocketRole socketRole = socketGuild.GetRole(772788208500211724);
if (socketUser.Roles.Any(r => r.Id == socketRole.Id))
{
await message.Channel.SendMessageAsync("The user '" + socketUser.Username + "' already has the role '" + socketRole.Name + "'!");
}
else
{
await socketUser.AddRoleAsync(socketRole);
await message.Channel.SendMessageAsync("Added Role '" + socketRole.Name + "' to '" + socketUser.Username + "'!");
}
}
}
if (message.Content == "!ping")
await message.Channel.SendMessageAsync("pong!");
}
}
}
我的目标
我想监测是否有人在服务器的任何聊天中写入“!create”,然后检查发送消息的人是否拥有名为“Game Notify”(Id:772788208500211724)的角色。 如果这个人确实拥有这个角色,它应该将此输出到原始消息所在的频道中:
"The user '<Username>' already has the role '<RoleName>'!"
如果用户没有该角色,则将其添加到该用户,并在原始消息所在的频道输出此信息:
"Added Role '<RoleName>' to '<Username>'!"
我的问题
如果我在没有该角色的情况下启动机器人,并写入!create one chat时,它会成功地给我分配该角色。当我执行命令第二次时,它再次给我分配该角色。它不会说我已经有该角色。
它也可以反过来使用: 如果我在启动机器人时拥有该角色并执行命令,则正确地指出我拥有该角色。当我现在手动将该角色从自己身上删除并再次执行命令时,它仍然说我有该角色。
如何解决这个问题?
使用Discord.net Nu-Get包v2.2.0