我使用Discord.Net创建了一个Discord机器人。当它在我的笔记本电脑上本地托管时,就可以正常工作。但是,当我将其上传到安装了Ubuntu的Azure虚拟机上并设法使其在GNU Screen或tmux下工作时,它开始显示出奇怪的行为。如果在2-5分钟内未使用bot的命令,则下一条命令在服务器中发布,而bot在2分钟内未对其做出反应,然后发布“任务已取消”。错误。之后,它又开始正常工作。如果在该延迟时间内发送了多个命令,则bot仅对第一个响应错误响应,并且在发布错误原因后,它将成功处理排队的其他命令。
CommandHandler代码:
class CommandHandler
{
private DiscordSocketClient _client;
private CommandService _service;
public CommandHandler(DiscordSocketClient client)
{
_client = client;
_service = new CommandService();
_service.AddModulesAsync(Assembly.GetEntryAssembly());
_client.MessageReceived += HandleCommandAsync;
}
private async Task HandleCommandAsync(SocketMessage s)
{
var msg = s as SocketUserMessage;
if (msg == null) return;
var context = new SocketCommandContext(_client, msg);
int argPos = 0;
if (msg.HasStringPrefix("!!", ref argPos))
{
var result = await _service.ExecuteAsync(context, argPos);
if (!result.IsSuccess && result.Error != CommandError.UnknownCommand)
{
await context.Channel.SendMessageAsync(result.ErrorReason);
}
}
}
}
和主要代码:
public class Program
{
static void Main(string[] args)
=> new Program().StartAsync().GetAwaiter().GetResult();
private DiscordSocketClient _client;
private CommandHandler _handler;
public async Task StartAsync()
{
_client = new DiscordSocketClient();
await _client.LoginAsync(TokenType.Bot, "token removed for stackoverflow");
await _client.StartAsync();
_handler = new CommandHandler(_client);
await Task.Delay(-1);
}
}