protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("Discord Bot Hosted Service started");

            await _client.LoginAsync(TokenType.Bot, _discordSettings.Token);

            await _client.StartAsync();

            _client.MessageReceived += (eventArgs) =>
            {
                // fire and forget
                _ = Task.Run(async() =>
                {
                    try
                    {
                        await PollyExceptionHandlerHelper.HandleExceptionAndRetry <SqlException>(OnMessageReceived(eventArgs), _logger, stoppingToken);
                    }
                    catch (HttpException ex) when(ex.Message.ContainsAny("50013", "50001", "Forbidden", "160002") || ex.HttpCode == HttpStatusCode.BadRequest)
                    {
                        _logger.LogWarning(ex, ex.Message);
                    }
                    catch (SqlException ex) when(ex.Message.Contains("SHUTDOWN"))
                    {
                        _logger.LogWarning(ex, "Sql Server shutdown in progress");
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, ex.Message);

                        await _githubService.CreateBugIssue($"Application Exception: {ex.Message}", ex, GithubIssueLabels.Discord);
                    }
                });

                return(Task.CompletedTask);
            };

            // Keep hosted service alive while receiving messages
            await Task.Delay(Timeout.Infinite, stoppingToken);
        }
Пример #2
0
    public async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
    {
        var handler = update.Type switch
        {
            UpdateType.Message => BotOnMessageReceived(botClient, update.Message),
            UpdateType.CallbackQuery => BotOnCallbackQueryReceived(update.CallbackQuery),
            _ => UnknownUpdateHandlerAsync(update)
        };

        try
        {
            await PollyExceptionHandlerHelper.HandleExceptionAndRetry <SqlException>(handler, _logger, cancellationToken);
        }
        // TODO: Handle this SqlException in HandleErrorAsync() method
        catch (SqlException ex) when(ex.Message.Contains("SHUTDOWN"))
        {
            _logger.LogWarning(ex, "Sql Server shutdown in progress");
        }
        catch (Exception exception)
        {
            await HandleErrorAsync(botClient, exception, cancellationToken);
        }
    }