예제 #1
0
        private async void OnUpdate(object sender, UpdateEventArgs e)
        {
            try
            {
                if (e.Update.CallbackQuery != null)
                {
                    var callBackData = e.Update.CallbackQuery.Data.Split(';');
                    if (callBackData.Length > 0 && callBackData[0] != "Empty")
                    {
                        var handlerCallback = _handlerCallbackRepo.Get(e.Update.CallbackQuery.From.Id);
                        if (handlerCallback != null && handlerCallback.MessageId == e.Update.CallbackQuery.Message.MessageId)
                        {
                            var callback = GetCommandOrCallback <IBotCallback>(handlerCallback.HandlerType);
                            var session  = _sessionRepo.Get(e.Update.CallbackQuery.From.Id);

                            if (callback != null && session != null)
                            {
                                await _telegramBotClient.AnswerCallbackQueryAsync(e.Update.CallbackQuery.Id);

                                await callback.Execute(e.Update.CallbackQuery, e.Update.CallbackQuery.Message, session.State);
                            }
                        }
                    }
                    else
                    {
                        await _telegramBotClient.AnswerCallbackQueryAsync(e.Update.CallbackQuery.Id);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"UserId={e.Update.Message.From.Id.ToString()},ErrorMessage={ex.Message}, StackTrace={ex.StackTrace}");
            }
        }
예제 #2
0
        private async Task HandleDocumentActionAsync(CallbackQuery query, DocumentAction action)
        {
            _documentAction = action;
            await _telegramBotClient.AnswerCallbackQueryAsync(query.Id);

            await _telegramBotClient.SendTextMessageAsync(_chatId, "Okay no problem.",
                                                          replyToMessageId : query.Message.MessageId);
        }
예제 #3
0
        public async Task ProcessUpdate(ITelegramBotClient client, Update update)
        {
            long chatId = update.GetChatId();

            if (this.state == State.WaitingForMessageText)
            {
                if (update.Type == UpdateType.Message)
                {
                    this.reminder.MessageText = update.Message.Text;
                    this.state = State.WaitingForTime;
                    await client.SendTextMessageAsync(chatId, $"Reminder text:\n{this.reminder.MessageText}\n\nEnter redinder time. Use 24-hour HHmm format.", replyMarkup : TelegramHelper.GetHomeButtonKeyboard());
                }
            }
            else if (this.state == State.WaitingForTime)
            {
                if (update.Type == UpdateType.Message)
                {
                    string   timeText = update.Message.Text;
                    TimeSpan time;
                    if (TelegramHelper.TryParseTime(timeText, out time))
                    {
                        this.reminder.DayTime = time;
                        this.state            = State.WaitingForWeekDays;
                        await client.SendTextMessageAsync(chatId, "Select reminder week days", replyMarkup : getWeekDaysKeyboard(this.reminder.WeekDays));
                    }
                    else
                    {
                        await client.SendTextMessageAsync(chatId, "Could not parse time. Use 24-hour HHmm format.", replyMarkup : TelegramHelper.GetHomeButtonKeyboard());
                    }
                }
            }
            else if (this.state == State.WaitingForWeekDays)
            {
                if (update.Type == UpdateType.CallbackQuery)
                {
                    if (update.CallbackQuery.Data == SelectDaysDone)
                    {
                        await client.AnswerCallbackQueryAsync(update.CallbackQuery.Id);

                        await client.EditMessageReplyMarkupAsync(chatId, update.CallbackQuery.Message.MessageId, TelegramHelper.GetHomeButtonKeyboard());

                        Program.RemindersRepository.StoreReminder(this.reminder);
                        this.Finished = true;
                        await client.SendDefaultMessageAsync(chatId);
                    }
                    else if (Enum.TryParse(typeof(WeekDays), update.CallbackQuery.Data, out object parsed))
                    {
                        await client.AnswerCallbackQueryAsync(update.CallbackQuery.Id);

                        WeekDays wdSelected = (WeekDays)parsed;
                        this.reminder.WeekDays ^= wdSelected;
                        await client.EditMessageReplyMarkupAsync(chatId, update.CallbackQuery.Message.MessageId, getWeekDaysKeyboard(this.reminder.WeekDays));
                    }
                }
            }
        }
예제 #4
0
        private async Task HandleIncomingFacultyAsync(Message request, CallbackQuery response, params object[] payload)
        {
            var chatId = response.Message.Chat.Id;

            var faculties = await _scheduleParser.ParseFacultiesAsync();

            var facultyAbbreviation = response.Data;
            var faculty             = faculties.FirstOrDefault(faculty => faculty.TitleAbbreviation.Equals(facultyAbbreviation));

            if (faculty is not null)
            {
                var groups = await _scheduleParser.ParseGroupsAsync(faculty.Id);

                var inlineKeyboard = groups.ToInlineKeyboard
                                     (
                    group => group.Title,
                    columnsCount: 3
                                     );

                await _client.SendChatActionAsync
                (
                    chatId,
                    chatAction : ChatAction.Typing
                );

                await _client.DeleteMessageAsync
                (
                    chatId,
                    messageId : request.MessageId
                );

                var nextRequest = await _client.SendTextMessageAsync
                                  (
                    chatId,
                    text : "Теперь выберите группу:",
                    replyMarkup : inlineKeyboard
                                  );

                _callbackQueryListener.RegisterRequest
                (
                    nextRequest,
                    HandleIncomingGroupAsync,
                    faculty.Id
                );
            }

            await _client.AnswerCallbackQueryAsync(response.Id);
        }
예제 #5
0
        public async Task StartCallbackQueryAsync(long chatId, int messageId, string callbackQueryId, string data)
        {
            try
            {
                var callbackData    = data.Split(";");
                var callbackType    = Enum.Parse <BotCallbackQueryType>(callbackData.First());
                var isCallbackQuery = _callbackQueries.TryGetCallbackQuery(callbackType, out var callbackQuery);

                if (isCallbackQuery)
                {
                    var payload = callbackData.Last();
                    _logger.LogInformation($"Start callback query {callbackQuery.GetType().Name}. CallbackQuery={callbackType.ToString()}, Data={data}");
                    await callbackQuery.ExecuteCallbackQueryAsync(chatId, messageId, callbackQueryId, payload);

                    _logger.LogInformation($"End callback query {callbackQuery.GetType().Name}. CallbackQuery={callbackType.ToString()}, Data={data}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error={ex.Message}, UserId={chatId.ToString()}, Data={data}");

                await _telegramBotClient.AnswerCallbackQueryAsync(
                    callbackQueryId : callbackQueryId,
                    text : CommonMessage.GetErrorMessage(),
                    showAlert : true);
            }
        }
예제 #6
0
        private void OnCallbackQuery(object sender, CallbackQueryEventArgs e)
        {
            ITelegramBotClient telegramBotClient = ModulesManager.GetTelegramBotClient();

            if (string.IsNullOrEmpty(e.CallbackQuery.Data))
            {
                return;
            }

            string[] queryArray = e.CallbackQuery.Data.Split(":");
            if (queryArray.Length == 0)
            {
                return;
            }

            ICallbackQueryHandler callbackQueryHandler;

            switch (queryArray[0])
            {
            case "delete_message":
                callbackQueryHandler = new DeleteMessageHandler();
                break;

            default:
                return;
            }

            callbackQueryHandler.Handle(queryArray, e.CallbackQuery.Message.MessageId);
            telegramBotClient.AnswerCallbackQueryAsync(e.CallbackQuery.Id);
        }
        private async void Bot_Callback(object sender, CallbackQueryEventArgs e)
        {
            var text = "";

            switch (e.CallbackQuery.Data)
            {
            case "do":
                text = @"do / did / done";
                break;

            case "be":
                text = @"be / was|were / been";
                break;

            case "go":
                text = @"go / went / gone";
                break;

            case "begin":
                text = @"begin / began / begun";
                break;

            default:
                break;
            }

            await botClient.SendTextMessageAsync(e.CallbackQuery.Message.Chat.Id, text);

            await botClient.AnswerCallbackQueryAsync(e.CallbackQuery.Id);
        }
예제 #8
0
        private async void Bot_Callback(object sender, CallbackQueryEventArgs e)
        {
            var text = "";

            switch (e.CallbackQuery.Data)
            {
            case "pushkin":
                text = @"Я помню чудное мгновенье:
                                    Передо мной явилась ты,
                                    Как мимолетное виденье,
                                    Как гений чистой красоты.";
                break;

            case "esenin":
                text = @"Не каждый умеет петь,
                                Не каждому дано яблоком
                                Падать к чужим ногам.";
                break;

            default:
                break;
            }

            await botClient.SendTextMessageAsync(e.CallbackQuery.Message.Chat.Id, text);

            await botClient.AnswerCallbackQueryAsync(e.CallbackQuery.Id);
        }
예제 #9
0
        private async void BotOnCallbackQueryReceived(object sender, CallbackQueryEventArgs callbackQueryEventArgs)
        {
            //Here implements actions on reciving
            var callbackQuery = callbackQueryEventArgs.CallbackQuery;

            var inlineKeyboard = GetInlineKeyboardMarkup(callbackQuery.Data);

#if DEBUG
            await _bot.AnswerCallbackQueryAsync(
                callbackQuery.Id,
                $"Received {callbackQuery.Data}");
#endif
            if (inlineKeyboard.Text != null && inlineKeyboard.ReplyMarkup != null)
            {
                await _bot.EditMessageTextAsync(
                    callbackQuery.Message.Chat.Id,
                    callbackQuery.Message.MessageId,
                    inlineKeyboard.Text,
                    ParseMode.Default,
                    false,
                    inlineKeyboard.ReplyMarkup);
            }

            //Send message back
            //await Bot.SendTextMessageAsync(
            //    callbackQuery.Message.Chat.Id,
            //    $"Received {callbackQuery.Data}");
        }
        public async void Bot_CallBack(object sender, CallbackQueryEventArgs e)
        {
            var text = "";
            var id   = e.CallbackQuery.Message.Chat.Id;
            var chat = trainingChats[id];

            switch (e.CallbackQuery.Data)
            {
            case "rustoeng":
                training.Add(id, TrainingType.RusToEng);
                text = chat.GetTrainingWord(TrainingType.RusToEng);
                break;

            case "engtorus":
                training.Add(id, TrainingType.EngToRus);
                text = chat.GetTrainingWord(TrainingType.EngToRus);
                break;

            default:
                break;
            }
            chat.IsTraningInProcess = true;
            activeWord.Add(id, text);
            if (trainingChats.ContainsKey(id))
            {
                trainingChats.Remove(id);
            }

            await botClient.SendTextMessageAsync(id, text);

            await botClient.AnswerCallbackQueryAsync(e.CallbackQuery.Id);
        }
예제 #11
0
 public static async void Spiner(ITelegramBotClient botClient, CallbackQueryEventArgs eventArgs)
 {
     try
     {
         await botClient.AnswerCallbackQueryAsync(eventArgs.CallbackQuery.Id);
     }
     catch { }
 }
예제 #12
0
        private static async void BotOnCallbackQueryReceived(object sender, CallbackQueryEventArgs callbackQueryEventArgs)
        {
            var callbackQuery = callbackQueryEventArgs.CallbackQuery;

            await botClient.AnswerCallbackQueryAsync(callbackQuery.Id, $"Selecionado {callbackQuery.Data}");

            Versao = callbackQuery.Data.ToLower();
        }
예제 #13
0
        private async void BotOnCallbackQueryReceived(object sender, CallbackQueryEventArgs callbackQueryEventArgs)
        {
            var command = _commandFactory
                          .GetCommand(callbackQueryEventArgs.CallbackQuery.Data);
            var arguments = callbackQueryEventArgs.CallbackQuery.Data.GetArguments(command.CommandType);
            await command
            .ProcessAsync(callbackQueryEventArgs.CallbackQuery.Message, arguments);

            await _botClient.AnswerCallbackQueryAsync(callbackQueryEventArgs.CallbackQuery.Id);
        }
예제 #14
0
        private async Task HandleIncomingWeekAsync(Message request, CallbackQuery response, params object[] payload)
        {
            var chatId = response.Message.Chat.Id;

            var weekDates = _weekDatesProvider.GetCurrentWeekDates
                            (
                DateTime.Parse(response.Data)
                            );

            var inlineKeyboard = weekDates.ToInlineKeyboard
                                 (
                dateTime => $"{dateTime:dd.MM (ddd)}",
                columnsCount: 3
                                 );

            await _client.SendChatActionAsync
            (
                chatId,
                chatAction : ChatAction.Typing
            );

            await _client.DeleteMessageAsync
            (
                chatId,
                messageId : request.MessageId
            );

            var nextRequest = await _client.SendTextMessageAsync
                              (
                chatId,
                text : "Выберите дату:",
                replyMarkup : inlineKeyboard
                              );

            _callbackQueryListener.RegisterRequest
            (
                nextRequest,
                HandleIncomingDateAsync
            );

            await _client.AnswerCallbackQueryAsync(response.Id);
        }
예제 #15
0
        static async void Bot_OnCallbackQuery(object sender, CallbackQueryEventArgs e)
        {
            if (e.CallbackQuery.Id != null)
            {
                if (e.CallbackQuery.Message.Caption != "****All RESERVED****" && (Convert.ToInt16(Convert.ToString(Regex.Match(input: e.CallbackQuery.Message.Caption, pattern: @"[0-9]+"))) > 1 && !buyer.Contains(e.CallbackQuery.From.Username)))
                {
                    buyer.Enqueue(e.CallbackQuery.From.Username);
                    product.Enqueue(e.CallbackQuery.Message.Photo[0].FileId);
                    botClient.EditMessageCaptionAsync(chatId: e.CallbackQuery.Message.Chat.Id,
                                                      messageId: e.CallbackQuery.Message.MessageId,
                                                      caption: "Available in store - " + Convert.ToString(Convert.ToInt16(Convert.ToString(Regex.Match(input: e.CallbackQuery.Message.Caption, pattern: @"[0-9]+"))) - 1),
                                                      replyMarkup: new InlineKeyboardMarkup(inlineKeyboardButton: InlineKeyboardButton.WithCallbackData(text: "order", callbackData: "yan")
                                                                                            )
                                                      );
                    botClient.AnswerCallbackQueryAsync(callbackQueryId: e.CallbackQuery.Id, showAlert: false, text: "Your Order has been requested 👍");
                }
                else if (e.CallbackQuery.Message.Caption != "****All RESERVED****" && (Convert.ToInt16(Convert.ToString(Regex.Match(input: e.CallbackQuery.Message.Caption, pattern: @"[0-9]+"))) == 1 && !buyer.Contains(e.CallbackQuery.From.Username)))
                {
                    buyer.Enqueue(e.CallbackQuery.From.Username);
                    product.Enqueue(e.CallbackQuery.Message.Photo[0].FileId);

                    botClient.EditMessageCaptionAsync(chatId: e.CallbackQuery.Message.Chat.Id,
                                                      messageId: e.CallbackQuery.Message.MessageId,
                                                      caption: "****All RESERVED****",
                                                      replyMarkup: new InlineKeyboardMarkup(inlineKeyboardButton: InlineKeyboardButton.WithCallbackData(text: "order", callbackData: "h")
                                                                                            )

                                                      );

                    botClient.AnswerCallbackQueryAsync(callbackQueryId: e.CallbackQuery.Id, showAlert: false, text: "Your Order has been requested 👍");
                }
                else if (e.CallbackQuery.Message.Caption == "****All RESERVED****")
                {
                    botClient.AnswerCallbackQueryAsync(callbackQueryId: e.CallbackQuery.Id, showAlert: false, text: "Sorry all units are currently reserved 😔");
                }
                else
                {
                    botClient.AnswerCallbackQueryAsync(callbackQueryId: e.CallbackQuery.Id, showAlert: false, text: "Your previose order is Still inprogress 🥶");
                }
            }
        }
예제 #16
0
        /// <summary>
        /// Проверка пользователя
        /// </summary>
        /// <param name="query">Запрос</param>
        /// <returns>Результат проверки</returns>
        private async Task <bool> Authenticate(CallbackQuery query)
        {
            if (!_botHelper.IsAuthorized(Convert.ToInt32(query.From.Id)))
            {
                await _botClient.AnswerCallbackQueryAsync(
                    query.Id, cancellationToken : Token);

                await _botClient.SendTextMessageAsync(
                    chatId : query.Message.Chat.Id,
                    text : "Not authorized", cancellationToken : Token);

                _logger.Error($"Not authorized user - {query.From.Id} ({query.From.FirstName})");
                return(false);
            }

            return(true);
        }
예제 #17
0
 public static bool AnswerCallback(CallbackQuery callback, string text = null, bool showAlert = false, string url = null)
 {
     try
     {
         return(Api.AnswerCallbackQueryAsync(callback.Id, text, showAlert, url).Result);
     }
     catch
     {
         //...
         return(false);
     }
 }
예제 #18
0
        static void Main()
        {
            botClient = new TelegramBotClient("1680338133:AAGMYEWsEeq04ry4WQhG6CmzYBfEYAk1ezs");

            var me = botClient.GetMeAsync().Result;

            Console.WriteLine(
                $"Hello, World! I am user {me.Id} and my name is {me.FirstName}."
                );

            botClient.OnMessage += Bot_OnMessage;
            List <InlineKeyboardButton> keyboardButtonsRow1 = new List <InlineKeyboardButton>();
            List <InlineKeyboardButton> keyboardButtonsRow2 = new List <InlineKeyboardButton>();

            keyboardButtonsRow1.Add(InlineKeyboardButton.WithCallbackData("А какие есть?", "callback1"));
            keyboardButtonsRow1.Add(InlineKeyboardButton.WithCallbackData("Другой тип ответа", "callback2"));
            keyboardButtonsRow2.Add(InlineKeyboardButton.WithCallbackData("снизу", "callback23"));
            List <List <InlineKeyboardButton> > rowList = new List <List <InlineKeyboardButton> >();

            rowList.Add(keyboardButtonsRow1);
            rowList.Add(keyboardButtonsRow2);
            keyboard = new InlineKeyboardMarkup(rowList);

            botClient.OnCallbackQuery += async(object sc, CallbackQueryEventArgs ev) =>
            {
                var message = ev.CallbackQuery.Message;
                if (ev.CallbackQuery.Data == "callback1")
                {
                    message = await botClient.SendTextMessageAsync(
                        chatId : ev.CallbackQuery.Message.Chat,
                        text : "hello - отправит вам сообщение Hello, world!\n" +
                        "sendpic - отправит вам любую картинку\n" +
                        "sendpoll - отправит вам любое голосование\n" +
                        "sendfile - отправит вам любой файл\n" +
                        "sendsticker - отправит стикер\n" +
                        "sendlocation - отправит вам локацию главного офиса компании\n" +
                        "sendcontact - отравит вам рабочий телефон директора компании",
                        parseMode : ParseMode.Default,
                        disableNotification : false);
                }
                else
                if (ev.CallbackQuery.Data == "callback2")
                {
                    await botClient.AnswerCallbackQueryAsync(ev.CallbackQuery.Id, "ответ типа callBackQueryAnswer");
                }
            };
            botClient.StartReceiving();

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();

            botClient.StopReceiving();
        }
예제 #19
0
        public async Task HandleCallbackAsync(CallbackQuery callbackQuery)
        {
            if (callbackQuery.From.Id != _userId)
            {
                await _bot.AnswerCallbackQueryAsync(callbackQuery.Id);

                return;
            }

            if (callbackQuery.Data.StartsWith("set_animal"))
            {
                await SetAnimalAsync(callbackQuery.Data.Split('_', 3).Last());
            }
            else if (callbackQuery.Data.StartsWith("set_sticker"))
            {
                await SetStickerAsync(callbackQuery.Data.Split('_', 3).Last());
            }
            else
            {
                Func <string, Task> callbackFunction = callbackQuery.Data switch
                {
                    "edit_animal" => EditAnimalAsync,
                    "edit_sticker" => EditStickerAsync,
                    "cancel_order" => CancelOrderAsync,
                    "place_order" => PlaceOrderAsync,
                    _ => null
                };

                if (callbackFunction != null)
                {
                    await callbackFunction.Invoke(callbackQuery.Id);
                }
                else
                {
                    await EditPropertyAsync(callbackQuery.Id, callbackQuery.Data.Split('_', 2).Last());
                }
            }

            await _bot.AnswerCallbackQueryAsync(callbackQuery.Id);
        }
예제 #20
0
        private async void BotClient_OnCallbackQuery(object sender, Telegram.Bot.Args.CallbackQueryEventArgs e)
        {
            var message = e.CallbackQuery.Message;

            if (e.CallbackQuery.Data == "callback1")
            {
                await botClient.AnswerCallbackQueryAsync(e.CallbackQuery.Id, "Проверяем статус установки");

                //await botClient.SendTextMessageAsync(message.Chat.Id, " Статус IBAD: \n");
                IbadStatusGet?.Invoke(message, null);
            }

            if (e.CallbackQuery.Data == "callback2")
            {
                await botClient.AnswerCallbackQueryAsync(e.CallbackQuery.Id, "Проверяем  установку на ошибки");

                IbadErrorsGet?.Invoke(message, null);

                // await botClient.AnswerCallbackQueryAsync(e.CallbackQuery.Id); // отсылаем пустое, чтобы убрать "частики" на кнопке
            }

            if (e.CallbackQuery.Data == "callback3")
            {
                await botClient.AnswerCallbackQueryAsync(e.CallbackQuery.Id, "Проверяем статус установки");

                //await botClient.SendTextMessageAsync(message.Chat.Id, "В разработке");
                MoikaStatusGet?.Invoke(message, null);
                // await botClient.SendTextMessageAsync(message.Chat.Id, "IBAD status: \n" + MOIKAStatusGet()) ;
            }

            if (e.CallbackQuery.Data == "callback4")
            {
                await botClient.AnswerCallbackQueryAsync(e.CallbackQuery.Id, "Проверяем  установку на ошибки");

                await botClient.SendTextMessageAsync(message.Chat.Id, "Ошибок нет");

                MoikaErrorsGet?.Invoke(message, null);
                // await botClient.AnswerCallbackQueryAsync(e.CallbackQuery.Id); // отсылаем пустое, чтобы убрать "частики" на кнопке
            }
        }
        public async Task HandleAsync(Update update)
        {
            var messageBuilder = new StringBuilder();

            messageBuilder.AppendLine("Report");
            messageBuilder.AppendLine(DateTime.Now.ToString("MM/dd/yyyy hh:mm TT"));
            messageBuilder.AppendLine("-------------------");
            messageBuilder.AppendLine("Nothing to report.");

            await _botClient.SendTextMessageAsync(update.CallbackQuery.Message.Chat.Id, messageBuilder.ToString());

            await _botClient.AnswerCallbackQueryAsync(update.CallbackQuery.Id);
        }
예제 #22
0
        public async Task <bool?> Handle(Update update, OperationTelemetry telemetry, CancellationToken cancellationToken = default)
        {
            var callbackQuery = update.CallbackQuery;

            telemetry.Properties["uid"]      = callbackQuery.From?.Id.ToString();
            telemetry.Properties["username"] = callbackQuery.From?.Username;
            telemetry.Properties["data"]     = callbackQuery.Data;
            try
            {
                (var text, var showAlert, string url) = await HandlerExtentions <(string, bool, string)> .Handle(myCallbackQueryHandlers.Bind(update), callbackQuery, GetContext(update), cancellationToken).ConfigureAwait(false);

                await myTelegramBotClient.AnswerCallbackQueryAsync(callbackQuery.Id, text, showAlert, url, cancellationToken : cancellationToken);
            }
            catch (OperationCanceledException) when(!cancellationToken.IsCancellationRequested)
            {
                await myTelegramBotClient.AnswerCallbackQueryAsync(callbackQuery.Id, "Operation timed out. Please, try again.", true, cancellationToken : cancellationToken);

                throw;
            }

            return(true);
        }
예제 #23
0
        public static async void BotOnCallbackQueryRecieved(object sender, CallbackQueryEventArgs callbackQueryEventArgs)
        {
            var callbackQuery = callbackQueryEventArgs.CallbackQuery;

            Console.WriteLine($"botCliente>> El usuario selecciono {callbackQuery.Data}");

            if (callbackQuery.Data == "Circulacion")
            {
                DiaCirculacionAsync(callbackQuery);
            }
            else if (callbackQuery.Data == "AutoEvaluate")
            {
                CuestionarioSintomas(callbackQuery);
            }
            else if (callbackQuery.Data == "/help")
            {
                await botClient.SendTextMessageAsync(
                    chatId : callbackQuery.Message.Chat.Id,
                    text : "Comandos:\n" +
                    "/start - ejecuta los comandos COVID 19\n" +
                    "/circulacion - muestra los dias de circulación\n" +
                    "/stats - muestra las estadisticas de COVID 19\n" +
                    "/evaluate - muestra una serie de preguntas sobre los sintomas que padeces\n" +
                    "/recomendaciones - muestra una serie de recomendaciones para prevenir el COVID 19\n"
                    );
            }
            else if (callbackQuery.Data == "prevenir")
            {
                await botClient.SendTextMessageAsync(
                    chatId : callbackQuery.Message.Chat.Id,
                    text : "Consejos para prevenir COVID-19\n" +
                    "1. Utiliza constantemente alcohol en gel\n" +
                    "2. Toma abundante agua y cuida tu alimentación para que mantengas tu sistema inmunologico fortalecido\n" +
                    "3. Si tienes algún sintoma busca un medio y comunicate con tu supervisor\n" +
                    "4. No saludes de mano o beso a las personas\n" +
                    "5. Lávate las manos frecuentemente con agua y jabón\n" +
                    "6. Limpia y desinfecta las superficies y objetos de uso común\n" +
                    "7. Evita tocar tus ojos, nariz y boca sin haberte lavado las manos\n" +
                    "8. Cubre tu nariz y boca con el antebrazo o con un pañuelo desechable al estornudar o toser"
                    );
            }
            else
            {
                await botClient.AnswerCallbackQueryAsync(
                    callbackQueryId : callbackQuery.Id,
                    text : $"..."
                    );
            }
        }
예제 #24
0
        /// <summary>
        /// действия при нажатии на пунты меню
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static async void BotOnCallbackQueryRecived(object sender, CallbackQueryEventArgs e)
        {
            string textMessage = e.CallbackQuery.Data;                                                //получем данные из названия кнопки
            string buttonText  = textMessage.Trim();                                                  //если есть пробелы спереди или сзади - убераем
            string name        = $"{e.CallbackQuery.From.FirstName} {e.CallbackQuery.From.LastName}"; //достаем имя пользователя

            Console.WriteLine($"{name} нажал {buttonText}");                                          //отображаем в консоли что выбрал юхер

            string dateToday = Convert.ToString(DateTime.Now);

            dateToday = dateToday.Substring(0, dateToday.Length - 9);
            dateToday = dateToday.Replace(".", "");
            string linkMenu = "https://sch883sz.mskobr.ru/files/" + $"ss{dateToday}.pdf";

            switch (buttonText)                                                                  //обрабатываем кнопки
            {
            case "Где столовая?":
                await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id,
                                                     "https://youtu.be/crnClMC1wec");

                break;

            case "Где актовый зал?":
                await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id,
                                                     "Сначала ты покушай, а представления потом");

                break;

            case "Расписание":
                await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id,
                                                     "https://sun1-24.userapi.com/Q6UFwrHOeRxliIGYCPMa-LgRiDQ41VUflTXdbQ/oJ0TZWN0frM.jpg");

                break;

            case "Меню в столовой":
                await botClient.SendTextMessageAsync(e.CallbackQuery.From.Id, $"{linkMenu}");

                break;
            }

            try
            {
                await botClient.AnswerCallbackQueryAsync(e.CallbackQuery.Id, $"Вы выбрали {buttonText}"); //отображаем юзеру, что он выбрал
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);                                                            //или не отображаем))
            }
        }
예제 #25
0
        public async Task ExecuteAsync()
        {
            var replyTo         = $"{callbackQuery.From.FirstName} {callbackQuery.From.LastName}";
            var isCorrectAnswer = bool.Parse(callbackQuery.Data);

            await telegramBotClient.AnswerCallbackQueryAsync(
                callbackQueryId : callbackQuery.Id,
                text : isCorrectAnswer? "You're right" : "Try again"
                );

            await telegramBotClient.SendTextMessageAsync(
                chatId : callbackQuery.Message.Chat.Id,
                text : $"{replyTo} - {(isCorrectAnswer ? "You're right" : "Try again")}"
                );
        }
예제 #26
0
        public async Task AnswerCallbackQuery(string callbackQueryId, string text = null, string url = null)
        {
            try
            {
                await _telegramBotClient.AnswerCallbackQueryAsync(callbackQueryId, text, url : url);
            }
            catch (InvalidParameterException exception)
            {
                // This may crash when the inline query is too old, just ignore it.
                if (exception?.Message == "query is too old and response timeout expired or query ID is invalid")
                {
                    return;
                }

                throw;
            }
        }
예제 #27
0
        private async Task <bool> tryResetConversation(ITelegramBotClient client, Update update)
        {
            if (update.Type == UpdateType.CallbackQuery)
            {
                long chatId = update.CallbackQuery.Message.Chat.Id;
                if (update.CallbackQuery.Data == TelegramHelper.HomeCommand)
                {
                    await client.AnswerCallbackQueryAsync(update.CallbackQuery.Id);

                    this.resetConversation(chatId);
                    await client.SendDefaultMessageAsync(chatId);

                    return(true);
                }
            }
            return(false);
        }
        public async Task ExecuteAsync(object sender, CallbackQueryEventArgs e)
        {
            //Console.WriteLine(e.CallbackQuery.Message.Text);
            //Console.WriteLine(e.CallbackQuery.Id);
            //Console.WriteLine(e.CallbackQuery.Data);//这才是关键的东西,就是上面在按钮上写的那个sendmessage
            var ChatId  = e.CallbackQuery.Message.Chat.Id;
            var IsGroup = e.CallbackQuery.Message.Chat.Id < 0;
            await botClient.AnswerCallbackQueryAsync(e.CallbackQuery.Id, "搜索中。。。");

            try {
                var searchOption = JsonConvert.DeserializeObject <SearchOption>(Encoding.UTF8.GetString(await Cache.GetAsync(e.CallbackQuery.Data)));
                await Cache.RemoveAsync(e.CallbackQuery.Data);

                searchOption.ToDelete.Add(e.CallbackQuery.Message.MessageId);

                searchOption.ReplyToMessageId = e.CallbackQuery.Message.MessageId;
                searchOption.Chat             = e.CallbackQuery.Message.Chat;

                if (searchOption.ToDeleteNow)
                {
                    foreach (var i in searchOption.ToDelete)
                    {
                        await Send.AddTask(async() => {
                            try {
                                await botClient.DeleteMessageAsync(ChatId, (int)i);
                            } catch (AggregateException) {
                                logger.LogError("删除了不存在的消息");
                            }
                        }, IsGroup);
                    }
                    return;
                }

                var searchOptionNext = await sonicSearchService.Search(searchOption);

                if (searchOptionNext.Messages.Count == 0)
                {
                    searchOption = await searchService.Search(searchOption);
                }

                await sendService.ExecuteAsync(searchOption, searchOptionNext.Messages);
            } catch (KeyNotFoundException) {
            } catch (ArgumentException) {
            }
        }
예제 #29
0
        public async Task ProcessUpdate(ITelegramBotClient client, Update update)
        {
            if (update.Type == UpdateType.CallbackQuery)
            {
                long reminderId;
                if (long.TryParse(update.CallbackQuery.Data, out reminderId))
                {
                    await client.AnswerCallbackQueryAsync(update.CallbackQuery.Id);

                    long chatId = update.CallbackQuery.Message.Chat.Id;
                    await client.EditMessageReplyMarkupAsync(chatId, update.CallbackQuery.Message.MessageId, TelegramHelper.GetHomeButtonKeyboard());

                    Program.RemindersRepository.RemoveReminder(chatId, reminderId);
                    this.Finished = true;
                    await client.SendDefaultMessageAsync(chatId);
                }
            }
        }
예제 #30
0
        private void OnCallbackQuery(object sender, CallbackQueryEventArgs e)
        {
            _logger.LogInformation("A callback query received: {@CallbackQuery}", e.CallbackQuery);

            var chatId = e.CallbackQuery.Message.Chat.Id;

            if (chatId != _options.Connection.ChatId)
            {
                _logger.LogWarning("Unexpected chat id in callback query: {@CallbackQuery}", e.CallbackQuery);
                return;
            }

            // fire message removal
            _client.DeleteMessageAsync(chatId, e.CallbackQuery.Message.MessageId, _cancellationToken);

            // fire callback
            _client.AnswerCallbackQueryAsync(e.CallbackQuery.Id, "🐱", cancellationToken: _cancellationToken);
        }