示例#1
0
        /// <inheritdoc />
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.Debug($"Bot service is starting");
            CancellationTokenSource.CreateLinkedTokenSource(Token, cancellationToken);
            Token.Register(() =>
            {
                _logger.Info($"Bot service stopping");
            }, true);
            string token = _botHelper.GetBotToken();

            if (string.IsNullOrEmpty(token))
            {
                _stoppingCts.Cancel();
            }
            else
            {
                _botClient = new TelegramBotClient(token);
            }

            // StartReceiving does not block the caller thread. Receiving is done on the ThreadPool.
            _executingTask = new Task(() =>
            {
                _botClient.StartReceiving(new DefaultUpdateHandler(HandleUpdateAsync, HandleErrorAsync),
                                          Token);
                _logger.Info($"Telegram bot started receiveing");
            }, Token);

            try
            {
                _executingTask.Start();
                _logger.Debug("Telegram bot initiated");
            }
            catch (OperationCanceledException)
            {
                _logger.Debug($"Работа бота отменена");
            }
            catch (Exception)
            {
                _logger.Error($"Работа бота отменена, не найден токен бота");
            }
            await _executingTask;
        }