예제 #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);
        }
예제 #2
0
 private static void Bot_OnMessage(object sender, MessageEventArgs e)
 {
     if (e.Message.Text != null)
     {
         Botlog.Write($"Received a text message in chat {e.Message.Chat.Id}.");
     }
 }
예제 #3
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());
     }
 }
예제 #4
0
        private static async void BotClientOnOnUpdate(object sender, UpdateEventArgs e)
        {
            long?chatId = null;

            try
            {
                Botlog.Write($"Got query: {e.Update.Type}");

                if (e.Update.Message != null)
                {
                    chatId = e.Update.Message.Chat?.Id;
                    var chatRoom = GetOrCreate(e.Update.Message.Chat);
                    chatRoom?.ChatIo.HandleUpdate(e.Update);
                }
                else if (e.Update.CallbackQuery != null)
                {
                    chatId = e.Update.CallbackQuery.Message.Chat?.Id;
                    var chatRoom = GetOrCreate(e.Update.CallbackQuery.Message.Chat);
                    chatRoom?.ChatIo.HandleUpdate(e.Update);
                    await _botClient.AnswerCallbackQueryAsync(e.Update.CallbackQuery.Id);
                }
            }
            catch (Exception error)
            {
                Botlog.Error(chatId, $"BotClientOnOnUpdate Failed: {e.Update.Type} {error}");
            }
        }
예제 #5
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);
            }
        }
예제 #6
0
        public async Task <Update> WaitUserInput()
        {
            _waitInputCompletionSource = new TaskCompletionSource <Update>();
            Botlog.Write("Wait for any");
            var result = await _waitInputCompletionSource.Task;

            Botlog.Write("Got any");
            return(result);
        }
예제 #7
0
        public async Task <string> WaitUserTextInput()
        {
            Botlog.Write("Wait for text");
            _waitMessageCompletionSource = new TaskCompletionSource <string>();

            var result = await _waitMessageCompletionSource.Task;

            Botlog.Write("Got text");
            return(result);
        }
예제 #8
0
        private static void RunChatRoom(Chat chat, MainFlow newMain)
        {
            var task = newMain.Run();

            task.ContinueWith(
                (t) =>
            {
                Botlog.WriteError(chat.Id, $"Faulted {t.Exception}", true);
                Chats.TryRemove(chat.Id, out _);
            }, TaskContinuationOptions.OnlyOnFaulted);
        }
예제 #9
0
        static async void Bot_OnMessage(object sender, MessageEventArgs e)
        {
            if (e.Message.Text != null)
            {
                Botlog.Write($"Received a text message in chat {e.Message.Chat.Id}.");

                //await botClient.SendTextMessageAsync(
                //    chatId: e.Message.Chat,
                //    text: "You said:\n" + e.Message.Text
                //);
            }
        }
예제 #10
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);
        }
예제 #11
0
        static async void BotClientOnOnUpdate(object?sender, UpdateEventArgs e)
        {
            Botlog.Write($"Got query: {e.Update.Type}");

            if (e.Update.Message != null)
            {
                var chatRoom = GetOrCreate(e.Update.Message.Chat);
                chatRoom?.Chat.HandleUpdate(e.Update);
            }
            else if (e.Update.CallbackQuery != null)
            {
                var chatRoom = GetOrCreate(e.Update.CallbackQuery.Message.Chat);
                chatRoom?.Chat.HandleUpdate(e.Update);

                await _botClient.AnswerCallbackQueryAsync(e.Update.CallbackQuery.Id);
            }
        }
예제 #12
0
        private static void OnBotWokeUp(Update update)
        {
            Telegram.Bot.Types.Chat chat = null;
            Telegram.Bot.Types.User user = null;
            try
            {
                if (update?.Message != null)
                {
                    chat = update.Message.Chat;
                    user = update.Message.From;
                }
                else if (update?.CallbackQuery != null)
                {
                    chat = update.CallbackQuery.Message.Chat;
                    user = update.CallbackQuery.From;
                }
                else
                {
                    return;
                }

                if (Chats.TryGetValue(chat.Id, out _))
                {
                    return;
                }

                var chatRoom = CreateChatRoom(chat);
                if (chatRoom == null)
                {
                    return;
                }
                chatRoom.ChatIo.SendMessageAsync(new EnglishTexts().DidYouWriteSomething).Wait();
                chatRoom.ChatIo.OnUpdate(
                    new Update {
                    Message = new Message {
                        Text = "/start", From = user
                    }
                });

                RunChatRoom(chat, chatRoom);
            }
            catch (Exception e)
            {
                Botlog.WriteError(chat?.Id, "WokeUpfailed" + e, true);
            }
        }
예제 #13
0
        static ChatRoomFlow GetOrCreate(Telegram.Bot.Types.Chat chat)
        {
            if (_chats.TryGetValue(chat.Id, out var existedChatRoom))
            {
                return(existedChatRoom);
            }

            var newChat     = new Chat(_botClient, chat);
            var newChatRoom = new ChatRoomFlow(newChat)
            {
                YaDictionaryApi = _yapiDicClient,
                YaTranslateApi  = _yapiTransClient,
                WordsService    = _wordsService
            };
            var task = newChatRoom.Run();

            task.ContinueWith((t) => Botlog.Write($"faulted {t.Exception}"), TaskContinuationOptions.OnlyOnFaulted);
            _chats.TryAdd(chat.Id, newChatRoom);
            return(null);
        }
예제 #14
0
        private static ChatRoomFlow GetOrCreate(Telegram.Bot.Types.Chat chat)
        {
            if (Chats.TryGetValue(chat.Id, out var existedChatRoom))
            {
                return(existedChatRoom);
            }

            var newChatRoom = new ChatRoomFlow(
                new ChatIO(_botClient, chat),
                new TelegramUserInfo(chat.Id, chat.FirstName, chat.LastName, chat.Username),
                _settings,
                _addWordService,
                _userWordService,
                _userService);

            var task = newChatRoom.Run();

            task.ContinueWith((t) => Botlog.Error(chat.Id, $"Faulted {t.Exception}"), TaskContinuationOptions.OnlyOnFaulted);
            Chats.TryAdd(chat.Id, newChatRoom);
            return(newChatRoom);
        }
예제 #15
0
        internal void HandleUpdate(Update args)
        {
            var msg = args.Message?.Text;

            if (!string.IsNullOrWhiteSpace(msg))
            {
                if (msg[0] == '/')
                {
                    if (!_menuItems.Contains(msg))
                    {
                        SendMessageAsync($"Invalid command '{msg}'").Wait();
                        return;
                    }

                    var textSrc = _waitMessageCompletionSource;
                    var objSrc  = _waitInputCompletionSource;
                    _waitMessageCompletionSource = null;
                    _waitInputCompletionSource   = null;
                    textSrc?.SetException(new ProcessInterruptedWithMenuCommand(msg));
                    objSrc?.SetException(new ProcessInterruptedWithMenuCommand(msg));
                    return;
                }
                if (_waitMessageCompletionSource != null)
                {
                    Botlog.Write("Set text result");
                    var src = _waitMessageCompletionSource;
                    _waitMessageCompletionSource = null;
                    src?.SetResult(args.Message.Text);
                    return;
                }
            }

            if (_waitInputCompletionSource != null)
            {
                Botlog.Write("Set any result");
                var src = _waitInputCompletionSource;
                _waitInputCompletionSource = null;
                src?.SetResult(args);
            }
        }
예제 #16
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();
        }