Beispiel #1
0
        public async Task <Update> WaitUserInputAsync()
        {
            Botlog.WriteInfo($"Wait for update", ChatId, false);
            var upd = await _senderChannel.Reader.ReadAsync();

            string text = null;

            if (upd.CallbackQuery != null)
            {
                await _client.AnswerCallbackQueryAsync(upd.CallbackQuery.Id);

                text = upd.CallbackQuery.Data;
            }
            else
            {
                text = upd.Message?.Text;
            }

            foreach (var botCommandHandler in CommandHandlers)
            {
                if (botCommandHandler.Acceptable(text))
                {
                    var argument = botCommandHandler.ParseArgument(text);
                    Botlog.WriteInfo($"Interrupt flow with command {text}", ChatId, false);
                    throw new ProcessInterruptedWithMenuCommand(argument, botCommandHandler);
                }
            }

            Botlog.WriteInfo($"Got update", ChatId, false);
            return(upd);
        }
Beispiel #2
0
 private static void Bot_OnMessage(object sender, MessageEventArgs e)
 {
     if (e.Message.Text != null)
     {
         Botlog.WriteInfo($"Received a text message to chat {e.Message.Chat.Id}.", e.Message.Chat.Id.ToString());
     }
 }
Beispiel #3
0
        private static void BotClientOnOnUpdate(object sender, UpdateEventArgs e)
        {
            long?chatId = null;

            try
            {
                Botlog.WriteInfo($"Trying to got query: {e.Update.Type}...");

                if (e.Update.Message != null)
                {
                    chatId = e.Update.Message.Chat?.Id;
                    Botlog.WriteInfo($"Got query: {e.Update.Type}", chatId.ToString());
                    var chatRoom = GetOrCreate(e.Update.Message.Chat);
                    chatRoom?.ChatIo.OnUpdate(e.Update);
                }
                else if (e.Update.CallbackQuery != null)
                {
                    chatId = e.Update.CallbackQuery.Message.Chat?.Id;
                    Botlog.WriteInfo($"Got query: {e.Update.Type}", chatId.ToString());

                    var chatRoom = GetOrCreate(e.Update.CallbackQuery.Message.Chat);
                    chatRoom?.ChatIo.OnUpdate(e.Update);
                }
            }
            catch (Exception)
            {
                Botlog.WriteError(chatId, $"BotClientOnOnUpdate Failed: {e.Update.Type}", true);
            }
        }
Beispiel #4
0
        internal void OnUpdate(Update update)
        {
            Botlog.WriteInfo($"Received msg from chat {ChatId.Identifier} {ChatId.Username}", false);
            foreach (var hook in _updateHooks)
            {
                if (hook.CanBeHandled(update))
                {
                    var _ = hook.Handle(update);
                    return;
                }
            }

            _senderChannel.Writer.TryWrite(update);
        }
Beispiel #5
0
        private static void Main()
        {
            TaskScheduler.UnobservedTaskException +=
                (sender, args) => Console.WriteLine($"Unobserved ex {args.Exception}");

            _settings = ReadConfiguration(substitudeDebugConfig: false);
            var yandexDictionaryClient = new YandexDictionaryApiClient(_settings.YadicapiKey, _settings.YadicapiTimeout);
            var client = new MongoClient(_settings.MongoConnectionString);
            var db     = client.GetDatabase(_settings.MongoDbName);
            //StatsMigrator.Do(db).Wait();
            var userWordRepo        = new UserWordsRepo(db);
            var dictionaryRepo      = new LocalDictionaryRepo(db);
            var userRepo            = new UsersRepo(db);
            var examplesRepo        = new ExamplesRepo(db);
            var questionMetricsRepo = new QuestionMetricRepo(db);
            var learningSetsRepo    = new LearningSetsRepo(db);

            userWordRepo.UpdateDb();
            dictionaryRepo.UpdateDb();
            userRepo.UpdateDb();
            examplesRepo.UpdateDb();
            questionMetricsRepo.UpdateDb();
            learningSetsRepo.UpdateDb();

            Botlog.QuestionMetricRepo = questionMetricsRepo;

            _userWordService        = new UsersWordsService(userWordRepo, examplesRepo);
            _localDictionaryService = new LocalDictionaryService(dictionaryRepo, examplesRepo);
            _userService            = new UserService(userRepo);
            _learningSetService     = new LearningSetService(learningSetsRepo);
            _addWordService         = new AddWordService(
                _userWordService,
                yandexDictionaryClient,
                _localDictionaryService,
                _userService);

            QuestionSelector.Singletone = new QuestionSelector(_localDictionaryService);

            _botClient = new TelegramBotClient(_settings.TelegramToken);

            Botlog.CreateTelegramLogger(_settings.BotHelperToken, _settings.ControlPanelChatId);

            var me = _botClient.GetMeAsync().Result;

            Botlog.WriteInfo($"Waking up. I am {me.Id}:{me.Username} ", true);

            _botClient.SetMyCommandsAsync(new[] {
                new BotCommand {
                    Command = BotCommands.Help, Description = "Help and instructions (Помощь и инстркции)"
                },
                new BotCommand {
                    Command = BotCommands.Start, Description = "Main menu (Главное меню)"
                },
                new BotCommand {
                    Command = BotCommands.Translate, Description = "Translator (Переводчик)"
                },
                new BotCommand {
                    Command = BotCommands.Learn, Description = "Learning translated words (Учить слова)"
                },
                new BotCommand {
                    Command = BotCommands.New, Description = "Show learning sets (Показать наборы для изучения)"
                },
                new BotCommand {
                    Command = BotCommands.Stats, Description = "Your stats (Твоя статистика)"
                },
                new BotCommand {
                    Command = BotCommands.Words, Description = "Your learned words (Твои выученные слова)"
                },
                new BotCommand {
                    Command = BotCommands.Chlang, Description = "Change interface language (Сменить язык интерфейса)"
                },
            }).Wait();

            var allUpdates = _botClient.GetUpdatesAsync().Result;

            Botlog.WriteInfo($"{allUpdates.Length} messages were missed");

            foreach (var update in allUpdates)
            {
                OnBotWokeUp(update);
            }
            if (allUpdates.Any())
            {
                _botClient.MessageOffset = allUpdates.Last().Id + 1;
                Botlog.WriteInfo($"{Chats.Count} users were waiting for us");
            }
            _botClient.OnUpdate  += BotClientOnOnUpdate;
            _botClient.OnMessage += Bot_OnMessage;

            _botClient.StartReceiving();
            Botlog.WriteInfo($"... and here i go!", false);
            // workaround for infinity awaiting
            new TaskCompletionSource <bool>().Task.Wait();
            // it will never happens
            _botClient.StopReceiving();
        }