コード例 #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
ファイル: Program.cs プロジェクト: NatShep/TestingGit
 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
ファイル: Program.cs プロジェクト: NatShep/ChoTISkazal
 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
ファイル: Program.cs プロジェクト: NatShep/TestingGit
        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
ファイル: Program.cs プロジェクト: NatShep/ChoTISkazal
        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
ファイル: Program.cs プロジェクト: NatShep/ChoTISkazal
        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
ファイル: Program.cs プロジェクト: tmteam/Chotiskazal
        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
ファイル: Program.cs プロジェクト: tmteam/Chotiskazal
        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
ファイル: Program.cs プロジェクト: NatShep/ChoTISkazal
        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
ファイル: Program.cs プロジェクト: tmteam/Chotiskazal
        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
ファイル: Program.cs プロジェクト: NatShep/TestingGit
        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
ファイル: Program.cs プロジェクト: NatShep/ChoTISkazal
        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();
        }