public InlineKeyboardMarkup(InlineKeyboardButton[] inlineKeyboardRow)
 {
     InlineKeyboard = new[]
     {
         inlineKeyboardRow
     };
 }
Example #2
0
        public async Task SendMessageAsync(long chatId, string html, TelegramButton button = null)
        {
            metricSender.SendCount("send_to_telegram.try");
            metricSender.SendCount($"send_to_telegram.try.to.{chatId}");
            html = PrepareHtmlForTelegram(html);
            log.Info($"Try to send message to telegram chat {chatId}, html: {html.Replace("\n", @" \\ ")}" + (button != null ? $", button: {button}" : ""));

            InlineKeyboardMarkup replyMarkup = null;

            if (button != null)
            {
                replyMarkup = new InlineKeyboardMarkup(new[] { InlineKeyboardButton.WithUrl(button.Text, button.Link) });
            }

            try
            {
                await bot.SendTextMessageAsync(chatId, html, parseMode : ParseMode.Html, replyMarkup : replyMarkup);
            }
            catch (Exception e)
            {
                metricSender.SendCount("send_to_telegram.fail");
                metricSender.SendCount($"send_to_telegram.fail.to.{chatId}");

                var isBotBlockedByUser = (e as ApiRequestException)?.Message.Contains("bot was blocked by the user") ?? false;
                if (isBotBlockedByUser)
                {
                    metricSender.SendCount("send_to_telegram.fail.blocked_by_user");
                    metricSender.SendCount($"send_to_telegram.fail.blocked_by_user.to.{chatId}");
                    log.Warn(e, $"Can\'t send message to telegram chat {chatId}");
                }
                else
                {
                    log.Error(e, $"Can\'t send message to telegram chat {chatId}");
                }

                throw;
            }

            metricSender.SendCount("send_to_telegram.success");
            metricSender.SendCount($"send_to_telegram.success.to.{chatId}");
        }
        protected virtual InlineKeyboardMarkup GenerateUserMarkup(Strings strings, string apikey)
        {
            if (delete)
            {
                return(null);
            }
            InlineKeyboardMarkup inline = new InlineKeyboardMarkup {
                InlineKeyboard = new List <List <InlineKeyboardButton> >()
            };

            if (!closed)
            {
                inline.InlineKeyboard.Add(new List <InlineKeyboardButton> {
                    InlineKeyboardButton.Create(strings.GetString(Strings.StringsList.publish), switchInlineQuery: pollText)
                });
                if (pollType != EPolls.board)
                {
                    inline.InlineKeyboard.Add(new List <InlineKeyboardButton> {
                        InlineKeyboardButton.Create(strings.GetString(Strings.StringsList.publishWithLink), switchInlineQuery: "$c:" + pollText)
                    });
                    inline.InlineKeyboard.Add(new List <InlineKeyboardButton> {
                        InlineKeyboardButton.Create(strings.GetString(Strings.StringsList.buttonVote), callbackData: "comm:iwannavote:" + Cryptography.Encrypt(chatId + ":" + pollId, apikey)),
                        InlineKeyboardButton.Create(strings.GetString(Strings.StringsList.commPageRefresh), callbackData: "comm:update:" + chatId + ":" + pollId)
                    });
                }
                else
                {
                    inline.InlineKeyboard.Add(new List <InlineKeyboardButton> {
                        InlineKeyboardButton.Create(strings.GetString(Strings.StringsList.buttonVote), url: "https://t.me/" + Globals.GlobalOptions.Botname + "/?start=" + Cryptography.Encrypt("board:" + chatId + ":" + pollId, apikey)),
                        InlineKeyboardButton.Create(strings.GetString(Strings.StringsList.commPageRefresh), callbackData: "comm:update:" + chatId + ":" + pollId)
                    });
                }
            }
            inline.InlineKeyboard.Add(new List <InlineKeyboardButton>()
            {
                InlineKeyboardButton.Create(strings.GetString(Strings.StringsList.commPageOptions), callbackData: "comm:options:" + chatId + ":" + pollId),
                InlineKeyboardButton.Create((closed ? strings.GetString(Strings.StringsList.commPageReopen) : strings.GetString(Strings.StringsList.commPageClose)), callbackData: "comm:" + (closed ? "reopen:" : "close:") + chatId + ":" + pollId),
                InlineKeyboardButton.Create(strings.GetString(Strings.StringsList.commPageDelete), callbackData: "comm:delete:" + chatId + ":" + pollId),
            });
            return(inline);
        }
Example #4
0
        protected override async void EditInlinePanel(int userId, int messageId)
        {
            try
            {
                string[] news =
                {
                    "http://planeta-grupp.ru/news/postuplenie-novyh-modeley-svetilnikov-brixoll-0",
                    "http://planeta-grupp.ru/news/cena-na-kabel-eshche-nizhe",
                    "http://planeta-grupp.ru/news/my-stali-distribyutorami-kompanii-ekf",
                    "http://planeta-grupp.ru/news/postuplenie-absolyutnyh-novinok-svetilnikov-ambrella",
                    "http://planeta-grupp.ru/news/kabel-gost-cena-super"
                };
                Random rand = new Random();
                int    i    = rand.Next(news.Length);
                string n    = news[i];

                var inlineKeyBoard = new InlineKeyboardMarkup(new[]
                {
                    new[]
                    {
                        InlineKeyboardButton.WithUrl("Новости", $"{n}"),
                        InlineKeyboardButton.WithCallbackData("Начало")
                    }
                });

                await BotController.Bot.EditMessageMediaAsync(
                    chatId : userId,
                    messageId : messageId,
                    media : new InputMediaPhoto(new InputMedia(DataConnection.GetImage("News"), "News.png")),
                    replyMarkup : inlineKeyBoard);

                await BotController.Bot.EditMessageCaptionAsync(userId, messageId, $"Самые свежие новости на сайте: ", replyMarkup : inlineKeyBoard);

                DataBaseContext.SetStepId(userId, (int)InlinePanelStep.News);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                RunDefaultCreatingProcess(userId);
            }
        }
Example #5
0
        public static async Task ListCurrentPack(Chat chat, User user)
        {
            AssertDraftStarted(user);
            var draft = _userDrafts[user];

            if (draft != null)
            {
                var pack = draft.ListPack(user.Id);
                if (pack.Contains("You cannot see the pack yet."))
                {
                    await TelegramCommunication.SendTextMessageAsync(chat.Id, $"{pack}");
                }

                var cardNames = pack.Split(";;", StringSplitOptions.RemoveEmptyEntries);
                pack = pack.Replace(";;", "");
                var buttonList = new List <List <InlineKeyboardButton> >
                {
                    new List <InlineKeyboardButton>()
                };
                int cardIndex       = 0;
                int buttonListIndex = 0;
                foreach (var name in cardNames)
                {
                    buttonList[buttonListIndex]
                    .Add(InlineKeyboardButton.WithCallbackData($"{cardIndex}", $"/pick {cardIndex}"));
                    cardIndex++;
                    if (cardIndex % 7 == 0)
                    {
                        buttonListIndex++;
                        buttonList.Add(new List <InlineKeyboardButton>());
                    }
                }

                InlineKeyboardMarkup replyMarkup = new InlineKeyboardMarkup(buttonList);
                await TelegramCommunication.SendTextMessageAsync(chat.Id, $"{pack}", keyboardMarkup : replyMarkup);

                return;
            }

            await TelegramCommunication.SendTextMessageAsync(chat.Id, $"Could not list your pack.");
        }
Example #6
0
        static public InlineKeyboardButton[][] GetInlineKeyboard(string[] stringArray, int ColInRow,
                                                                 int btnType, InlineKeyboardButton[] extrabtn, string Link = "")
        {
            //btnType ==> 1: URL  2:CallBack
            int col = ColInRow;
            int row = stringArray.Length / col;

            row = (stringArray.Length % col) != 0 ? ++row : row;

            col = col > stringArray.Length ? stringArray.Length : col;
            var keyboardInline = new InlineKeyboardButton[row + (extrabtn != null ? 1 : 0)][];

            int IndexstringArray = 0;
            int btnarrcur        = 0;

            for (var j = 0; j < row; j++)
            {
                col = ((j + 1) == row && (stringArray.Length % col != 0)) ? (col - 1) : col;
                var keyboardButtons = new InlineKeyboardButton[col];
                for (var i = 0; i < col; i++)
                {
                    keyboardButtons[i] = new InlineKeyboardButton
                    {
                        Text         = stringArray[IndexstringArray],
                        CallbackData = stringArray[IndexstringArray],
                    };
                    if (Link != "")
                    {
                        keyboardButtons[i].Url = Link;
                    }
                    ++btnarrcur;
                    IndexstringArray++;
                }
                keyboardInline[j] = keyboardButtons;
            }
            if (extrabtn != null)
            {
                keyboardInline[row] = extrabtn;
            }
            return(keyboardInline);
        }
        public static IReplyMarkup CreateInlineKeyboardButtonForFutureEvents(List <Event> eventList, int columns)
        {
            if (columns == 0)
            {
                columns = 1;
            }
            int rows = (int)Math.Ceiling((double)eventList.Count / (double)columns);

            InlineKeyboardButton[][] buttons = new InlineKeyboardButton[rows][];

            for (int i = 0; i < buttons.Length; i++)
            {
                buttons[i] = eventList
                             .Skip(i * columns)
                             .Take(columns)
                             .Select(direction => InlineKeyboardButton.WithCallbackData(
                                         direction.Name, $"GetFutureEvents:{direction.Id.ToString()}"))
                             .ToArray();
            }
            return(new InlineKeyboardMarkup(buttons));
        }
Example #8
0
 public async Task <Session> ExecuteCommand(MessageEventArgs e, Session session)
 {
     try
     {
         await _botClient.SendTextMessageAsync(
             chatId : e.Message.Chat,
             text : $"*Message*: `{e.Message.Text}`\n" + $"*Sender*: `{e.Message.From}`\n" + $"*Date*: `{e.Message.Date}`\n",
             parseMode : ParseMode.Markdown,
             replyToMessageId : e.Message.MessageId,
             replyMarkup : new InlineKeyboardMarkup(InlineKeyboardButton.WithUrl(
                                                        "Author",
                                                        "https://t.me/martcs"
                                                        ))
             );
     }
     catch (Exception exception)
     {
         throw  new Exception("Exception occured in TextCommand: " + exception.Message);
     }
     return(null);
 }
Example #9
0
        public async Task Should_Send_Game_With_ReplyMarkup()
        {
            Message gameMessage = await BotClient.SendGameAsync(
                /* chatId: */ _fixture.SupergroupChat.Id,
                /* gameShortName: */ _classFixture.GameShortName,
                replyMarkup : new[]
            {
                InlineKeyboardButton.WithCallBackGame(/* text: */ "Play"),
                InlineKeyboardButton.WithCallbackData(/* textAndCallbackData: */ "Second button")
            }
                );

            Assert.Equal(MessageType.Game, gameMessage.Type);
            Assert.NotEmpty(gameMessage.Game.Title);
            Assert.NotEmpty(gameMessage.Game.Description);
            Assert.NotNull(gameMessage.Game.Photo);
            Assert.NotEmpty(gameMessage.Game.Photo.Select(p => p.FileId));
            Assert.All(gameMessage.Game.Photo, p => Assert.True(p.FileSize > 1_000));
            Assert.All(gameMessage.Game.Photo, p => Assert.True(p.Width > 80));
            Assert.All(gameMessage.Game.Photo, p => Assert.True(p.Height > 40));
        }
Example #10
0
        public static ResponseMessage FormatItem(TodoItem todo, string tickCallbackAddress, string removeCallbackAddress)
        {
            var tickButton = new InlineKeyboardButton()
            {
                Text         = "✅",
                CallbackData = tickCallbackAddress
            };

            var removeButton = new InlineKeyboardButton()
            {
                Text         = "❌",
                CallbackData = removeCallbackAddress
            };

            return(new ResponseMessage()
            {
                Message = (todo.Finished ? "✅" : "") + todo.Text,
                InlineKeyboardButtons = !todo.Finished ? new InlineKeyboardButton[][] { new[] { tickButton, removeButton } }
                                                           : new InlineKeyboardButton[][] { new[] { removeButton } }
            });
        }
Example #11
0
        async Task SendReplyKeyboard(Message message)
        {
            var newWord = await _wordsService.GetWordAsync();

            var inlineKeyboard = new InlineKeyboardMarkup(new[]
            {
                // first row
                new []
                {
                    InlineKeyboardButton.WithCallbackData("Infinitive", $"inf;{newWord}"),
                    InlineKeyboardButton.WithCallbackData("Gerund", $"ger;{newWord}"),
                    InlineKeyboardButton.WithCallbackData("Both", $"both;{newWord}"),
                }
            });

            await _botClient.Bot.SendTextMessageAsync(
                chatId : message.Chat.Id,
                text : newWord,
                replyMarkup : inlineKeyboard
                );
        }
Example #12
0
        public async Task SendMessageButtonMarkdownV2Async(long chatId, int replyToMessageId, string text)
        {
            var inlineKeyboardButton = new InlineKeyboardButton
            {
                Text         = $"{Commands.REMOVE}",
                CallbackData = $"{Commands.REMOVE}"
            };
            var keyboard = new InlineKeyboardMarkup(inlineKeyboardButton);

            try
            {
                await Client.SendTextMessageAsync(
                    chatId : chatId,
                    replyToMessageId : replyToMessageId,
                    parseMode : ParseMode.MarkdownV2,
                    disableWebPagePreview : false,
                    replyMarkup : keyboard,
                    text : text);
            }
            catch (Exception ex) { }
        }
Example #13
0
        private static InlineKeyboardButton[][] GetInlineKeyboard_AssertOrder(string goods_categorie_id)
        {
            var keyboardInline = new InlineKeyboardButton[2][];
            var yes_btn        = new InlineKeyboardButton[1];

            yes_btn[0] = new InlineKeyboardButton()
            {
                CallbackData = goods_categorie_id, Text = "хочу"
            };
            var no_btn = new InlineKeyboardButton[1];

            no_btn[0] = new InlineKeyboardButton()
            {
                CallbackData = "no", Text = "не хочу"
            };

            keyboardInline[0] = yes_btn;
            keyboardInline[1] = no_btn;

            return(keyboardInline);
        }
Example #14
0
        public override async Task Execute(Message message, TelegramBotClient client)
        {
            var chatId         = message.Chat.Id;
            var messageId      = message.MessageId;
            var inlineKeyboard = new InlineKeyboardMarkup(new[]
            {
                new []         // first row
                {
                    InlineKeyboardButton.WithCallbackData("Hello!", "/hello"),
                    InlineKeyboardButton.WithCallbackData("Inline Button", "/inline"),
                    InlineKeyboardButton.WithCallbackData("Inline Button", "/setusers")
                }
            });

            await client.SendTextMessageAsync(chatId, "Привіт!\n Скористайтеся командою /createusers \nдля створення нових користувачів", replyToMessageId : messageId
                                              //  replyMarkup: createKeyboard()
                                              );

            //   return;
            // await client.SendTextMessageAsync(chatId, "Hello!", replyToMessageId: messageId);
        }
        public void Execute()
        {
            Response <IList <ChannelEntity> > channels = _queryChannelService.GetList(_callbackQueryEventArgs.CallbackQuery.From.Id, CDO.Enums.Chat.ChatType.Group);

            InlineKeyboardButton[][] keyboardButtonsListChannels = new InlineKeyboardButton[channels.ResponseData.Count + 1][];
            keyboardButtonsListChannels = new InlineKeyboardButton[channels.ResponseData.Count + 1][];

            for (int i = 0; i < channels.ResponseData.Count; i++)
            {
                int count = _queryRssChatRelationService.GetList(_callbackQueryEventArgs.CallbackQuery.From.Id, channels.ResponseData[i].Name, CDO.Enums.Chat.ListChatRelation.ByChatName).ResponseData.Count;
                keyboardButtonsListChannels[i] = new InlineKeyboardButton[] { InlineKeyboardButton.WithCallbackData(string.Concat(channels.ResponseData[i].Name, " (", count, ")"), string.Concat("Group_", channels.ResponseData[i].Id)) };
            }

            keyboardButtonsListChannels[channels.ResponseData.Count] = new InlineKeyboardButton[] { InlineKeyboardButton.WithCallbackData("Back to Home") };

            _telegramBotClient.EditMessageTextAsync(
                _callbackQueryEventArgs.CallbackQuery.From.Id,
                _callbackQueryEventArgs.CallbackQuery.Message.MessageId,
                "you can attach rss to selected group from rss list.",
                replyMarkup: new InlineKeyboardMarkup(keyboardButtonsListChannels)).GetAwaiter();
        }
Example #16
0
 public async Task StartMessage(string userId, string emailAddress)
 {
     var message = $"You are already autorized as {emailAddress}";
     var button  = new InlineKeyboardButton
     {
         Text         = "Authorize another account",
         CallbackData = new GetCallbackData
         {
             Command = TextCommand.AUTHORIZE_COMMAND
         }
     };
     var keyboard = new InlineKeyboardMarkup
     {
         InlineKeyboard = new List <List <InlineKeyboardButton> > {
             new List <InlineKeyboardButton> {
                 button
             }
         }
     };
     await _telegramMethods.SendMessage(userId, message, null, false, false, null, keyboard);
 }
Example #17
0
        static GameRoom()
        {
            var admin = new KeyboardButton[3][];

            admin[0]    = new KeyboardButton[] { Strings.NewGame, Strings.RemainingRoles };
            admin[1]    = new KeyboardButton[] { Strings.PlayersNumber, Strings.Configuration };
            admin[2]    = new KeyboardButton[] { Strings.LeaveRoom, Strings.RoomID };
            MarkupAdmin = new ReplyKeyboardMarkup(admin, true);

            var def = new KeyboardButton[2][];

            def[0]        = new KeyboardButton[] { Strings.PlayersNumber, Strings.Configuration };
            def[1]        = new KeyboardButton[] { Strings.LeaveRoom, Strings.RoomID };
            MarkupDefault = new ReplyKeyboardMarkup(def, true);

            var conf = new InlineKeyboardButton[2][];

            conf[0]          = new InlineKeyboardButton[] { "0", "1", "2", "3", "4" };
            conf[1]          = new InlineKeyboardButton[] { "Отмена" };
            MarkupInlineConf = new InlineKeyboardMarkup(conf);
        }
Example #18
0
        public InlineKeyboardMarkup ConstructUrlButtonMarkup()
        {
            var inlineMarkup = new InlineKeyboardMarkup();

            if (UbPanels.Count != 0)
            {
                InlineKeyboardButton[][] array = new InlineKeyboardButton[UbPanels.Count][];
                for (int i = 0; i < UbPanels.Count; i++)
                {
                    array[i]    = new InlineKeyboardButton[1];
                    array[i][0] = new InlineKeyboardUrlButton(UbPanels[i].UbData.Name, UbPanels[i].UbData.Address);
                }
                InlineMarkup = new InlineKeyboardMarkup(array);
            }
            else
            {
                return(null);
            }

            return(inlineMarkup);
        }
/*        private static async void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs)
 *      {
 *          var message = messageEventArgs.Message;
 *          var s = Empty;
 *
 *          if (message.Text.Equals("/start"))
 *          {
 *              s = "Hello!\n";
 *              s += "Please, input some matrix.\n";
 *              s += "For example:\n";
 *              s += "1 1 1\n";
 *              s += "1 1 1\n";
 *              s += "1 1 1\n";
 *          }
 *          else
 *          {
 *              var matrix = new Matrix(message.Text);
 *              var solve = new DeterminantOfAmericanMethod(matrix);
 *              solve.GetDeterminant();
 *              s = solve.Logger;
 *          }
 *
 *          if (message?.Type == Telegram.Bot.Types.Enums.MessageType.Text)
 *          {
 *              await _client.SendTextMessageAsync(message.Chat.Id, s);
 *          }
 *      }  */

/*        private static async void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs)
 *      {
 *          var message = messageEventArgs.Message;
 *
 *          if (message == null || message.Type != MessageType.Text) return;
 *
 *          ReplyKeyboardMarkup replyKeyboard = new[]
 *          {
 *              new[] {"One", "Two"},
 *              new[] {"Three", "Four"}
 *          };
 *
 *          await _client.SendTextMessageAsync(message.Chat.Id, "Choose", replyMarkup: replyKeyboard);
 *      }  */


        private static async void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs)
        {
            var message = messageEventArgs.Message;

            if (message == null || message.Type != MessageType.Text)
            {
                return;
            }

            var inlineKeyboard = new InlineKeyboardMarkup(new[]
            {
                new [] // first row
                {
                    InlineKeyboardButton.WithCallbackData("Button 1", "callback1"),
                    InlineKeyboardButton.WithCallbackData("Button 2", "callback2"),
                }
            });


            await _client.SendTextMessageAsync(message.Chat.Id, "Choose", replyMarkup : inlineKeyboard);
        }
Example #20
0
        internal InlineKeyboardMarkup CreateGetInlineKeyboard(Guid guid)
        {
            InlineKeyboardMarkup GetInlineKeyboard
                = new InlineKeyboardMarkup(
                      new[]
            {
                new []
                {
                    InlineKeyboardButton.WithCallbackData(ListCommand.Key, ListCommand.Value + ":" + guid.ToString()),
                    InlineKeyboardButton.WithCallbackData(EnterNumbCommand.Key, EnterNumbCommand.Value + ":" + guid.ToString()),
                },
                new []
                {
                    InlineKeyboardButton.WithCallbackData(BackCommand.Key, BackCommand.Value + ":" + guid.ToString()),
                    InlineKeyboardButton.WithCallbackData(ExitCommand.Key, ExitCommand.Value + ":" + guid.ToString()),
                },
            }
                      );

            return(GetInlineKeyboard);
        }
Example #21
0
        public static async Task ShowStartMenu(TelegramBotClient bot, int userId)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("Если Вы хотите пополнить Ваш список желаемых подарков, то:\n");
            sb.Append("1) Нажмите «Зарегистрироваться»\n");
            sb.Append("2) Отправьте свой номер телефона, нажав на соответствующую кнопку на клавиатуре\n");
            sb.Append("3) Отправьте свой день и месяц рождения, для того чтобы Ваши друзья могли знать, что Вы хотели бы получить на свой день рождения.\n");
            sb.Append("4) Отправляйте в чат ссылки с любых сайтов, картинки или текстовое описание подарка.\n\n");
            sb.Append("Если Вы хотите узнать список желаемых подарков Вашего друга, то:\n");
            sb.Append("1) Нажмите «Хочу подарить»\n");
            sb.Append("2) Прикрепите контакт Вашего друга, из Вашего списка контактов\n");
            sb.Append("3) Получите список подарков, которые хочет получить Ваш друг\n");

            var inlineKeyBoard = new InlineKeyboardMarkup(new[]
            {
                new[] { InlineKeyboardButton.WithCallbackData("Зарегистрироваться") },
                //new[] { InlineKeyboardButton.WithCallbackData("Хочу подарить") },
            });
            await bot.SendTextMessageAsync(userId, sb.ToString(), replyMarkup : inlineKeyBoard);
        }
        public virtual InlineKeyboardMarkup CreateInlineKeyboardForDirections(string routeTag, string[] directions)
        {
            const int keysPerRow = 2;

            var keyboardRows = directions.Length / keysPerRow + directions.Length % keysPerRow;

            var keyboard = new InlineKeyboardButton[keyboardRows][];

            for (int i = 0; i < keyboard.Length; i++)
            {
                keyboard[i] = directions
                              .Skip(i * keysPerRow)
                              .Take(keysPerRow)
                              .Select(direction => InlineKeyboardButton.WithCallbackData(
                                          direction, Telegram.Constants.CallbackQueries.BusCommand.BusDirectionPrefix + direction
                                          ))
                              .ToArray();
            }

            return(new InlineKeyboardMarkup(keyboard));
        }
Example #23
0
        public static InlineKeyboardMarkup FromAdminList()
        {
            var Keyboard = new List <List <InlineKeyboardButton> >();
            var list     = Types.User.UserBase;

            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].LevelPermission == 1)
                {
                    Keyboard.Add(new List <InlineKeyboardButton>()
                    {
                        InlineKeyboardButton.WithCallbackData($"{list[i].Id}", $"Admin&RemoveAdmin&Select&{list[i].Id}")
                    });
                }
            }
            Keyboard.Add(new List <InlineKeyboardButton>()
            {
                InlineKeyboardButton.WithCallbackData("Назад", "Admin&MainMenu")
            });
            return(Keyboard.ToArray());
        }
    public async Task HandleAsync(
        IUpdateContext context,
        UpdateDelegate next,
        CancellationToken cancellationToken
        )
    {
        await _telegramService.AddUpdateContext(context);

        var message = _telegramService.Message;

        var pinnedMsg = message.PinnedMessage;

        var messageLink = pinnedMsg.GetMessageLink();
        var keyboard    = new InlineKeyboardMarkup(InlineKeyboardButton.WithUrl("➡ Ke Pesan", messageLink));

        var sendText = $"📌 Pesan di sematkan baru!" +
                       $"\nPengirim: {pinnedMsg.GetFromNameLink()}" +
                       $"\nPengepin: {message.GetFromNameLink()}";

        await _telegramService.SendTextMessageAsync(sendText, keyboard, replyToMsgId : 0);
    }
Example #25
0
        private static void Button(MessageEventArgs e)
        {
            var inlineKeyboard = new InlineKeyboardMarkup(new[]
            {
                new []
                {
                    InlineKeyboardButton.WithCallbackData(Resources.Bot.Info),
                },
                new []
                {
                    InlineKeyboardButton.WithCallbackData(Resources.Bot.Deposit),
                    InlineKeyboardButton.WithCallbackData(Resources.Bot.Settings),
                },
                new []
                {
                    InlineKeyboardButton.WithCallbackData(Resources.Bot.Groups)
                }
            });

            Bot.SendTextMessageAsync(e.Message.Chat.Id, Resources.Bot.ChooseOption, replyMarkup: inlineKeyboard);
        }
Example #26
0
        public async Task DisplayMainMenu(Chat chat)
        {
            var optionsKeyboard = new InlineKeyboardMarkup(new[]
            {
                new []         // first row
                {
                    InlineKeyboardButton.WithCallbackData("Show Secret", OptionKeys.showSecret.ToString()),
                    InlineKeyboardButton.WithCallbackData("Acount Recovery", OptionKeys.recoverSecret.ToString()),
                    InlineKeyboardButton.WithCallbackData("New Account", OptionKeys.newSecret.ToString()),
                },
                new []         // second row
                {
                    InlineKeyboardButton.WithCallbackData("Faucet", OptionKeys.faucetHelp.ToString()),
                    InlineKeyboardButton.WithCallbackData("Transactions", OptionKeys.txHelp.ToString()),
                    InlineKeyboardButton.WithCallbackData("Trading", OptionKeys.tradeHelp.ToString()),
                }
            });

            await _TBC.SendTextMessageAsync(chatId : chat, $"WELCOME TO *KIRA WALLET* MAIN MENU",
                                            replyMarkup : optionsKeyboard, parseMode : ParseMode.Markdown);
        }
Example #27
0
        public async void ShowPlayerButtons(object sender, MessageEventArgs messageargs)
        {
            await Bot.SendChatActionAsync(Properties.Socials.Default.TelegramUserID.ToString(), ChatAction.Typing);

            var keyboard = new InlineKeyboardMarkup(new[]
            {
                new[]     // first row
                {
                    InlineKeyboardButton.WithCallbackData("⏮"),
                    InlineKeyboardButton.WithCallbackData("⏯"),
                    InlineKeyboardButton.WithCallbackData("⏭"),
                },
                new []     // second row
                {
                    InlineKeyboardButton.WithCallbackData("-"),
                    InlineKeyboardButton.WithCallbackData("+"),
                }
            });
            await Bot.SendTextMessageAsync(Properties.Socials.Default.TelegramUserID.ToString(), "Управление плеером",
                                           replyMarkup : keyboard);
        }
Example #28
0
        public async Task Should_Answer_Inline_Query_With_Cached_Video()
        {
            // Video from https://pixabay.com/en/videos/fireworks-rocket-new-year-s-eve-7122/
            Message videoMessage = await BotClient.SendVideoAsync(
                chatId : _fixture.SupergroupChat,
                video : "https://pixabay.com/en/videos/download/video-7122_medium.mp4",
                replyMarkup : (InlineKeyboardMarkup)InlineKeyboardButton
                .WithSwitchInlineQueryCurrentChat("Start inline query")
                );

            Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync();

            const string resultId = "fireworks_video";

            InlineQueryResultBase[] results =
            {
                new InlineQueryResultCachedVideo(
                    id: resultId,
                    videoFileId: videoMessage.Video.FileId,
                    title: "New Year's Eve Fireworks")
                {
                    Description = "2017 Fireworks in Germany"
                }
            };

            await BotClient.AnswerInlineQueryAsync(
                inlineQueryId : iqUpdate.InlineQuery.Id,
                results : results,
                cacheTime : 0
                );

            (Update messageUpdate, Update chosenResultUpdate) =
                await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Video);

            Update resultUpdate = chosenResultUpdate;

            Assert.Equal(MessageType.Video, messageUpdate.Message.Type);
            Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId);
            Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query);
        }
Example #29
0
        public async Task Should_Answer_Inline_Query_With_Cached_Mpeg4Gif()
        {
            await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldAnswerInlineQueryWithCachedMpeg4Gif);

            Message gifMessage = await BotClient.SendDocumentAsync(
                chatId : _fixture.SupergroupChat,
                document : "https://upload.wikimedia.org/wikipedia/commons/2/2c/Rotating_earth_%28large%29.gif",
                replyMarkup : (InlineKeyboardMarkup)InlineKeyboardButton
                .WithSwitchInlineQueryCurrentChat("Start inline query"));

            Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync();

            const string resultId = "mpeg4_gif_result";

            InlineQueryResultBase[] results =
            {
                new InlineQueryResultCachedMpeg4Gif(
                    id: resultId,
                    mpeg4FileId: gifMessage.Document.FileId
                    )
                {
                    Caption = "Rotating Earth",
                }
            };

            await BotClient.AnswerInlineQueryAsync(
                inlineQueryId : iqUpdate.InlineQuery.Id,
                results : results,
                cacheTime : 0
                );

            (Update messageUpdate, Update chosenResultUpdate) =
                await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Document);

            Update resultUpdate = chosenResultUpdate;

            Assert.Equal(MessageType.Document, messageUpdate.Message.Type);
            Assert.Equal(resultId, resultUpdate.ChosenInlineResult.ResultId);
            Assert.Equal(iqUpdate.InlineQuery.Query, resultUpdate.ChosenInlineResult.Query);
        }
        private PreparedMessageContent PrepareSubmissionStatus(DbValidationResult responseData, int problemId)
        {
            var sb = new StringBuilder();

            if (responseData.Result)
            {
                sb.AppendLine(Resources.QueryCorrect);
            }
            else
            {
                for (var i = 0; i < responseData.Description.Count; i++)
                {
                    if (responseData.Description[i].Contains("SUBMIS0004ER"))
                    {
                        var parsed = responseData.Description[i].Split(',');
                        sb.AppendLine($"The number of rows returned is different on database №-{i + 1}.\n quantity: {parsed[1]}. expected: {parsed[2]}"); //TODO: Ask Ermek
                    }
                    else if (responseData.Description[i].Contains("SUBMIS0003ER"))
                    {
                        var parsed = responseData.Description[i].Split(',');
                        sb.AppendLine($"The number of returned columns is different.\n quantity: {parsed[1]}. expected: {parsed[2]}");
                    }
                    else
                    {
                        sb.AppendLine(responseData.Description[0]);
                    }
                }
            }

            var buttons = new InlineKeyboardButton[1][];

            buttons[0]    = new InlineKeyboardButton[2];
            buttons[0][0] = InlineKeyboardButton.WithCallbackData(Resources.TableResultButton, $"{SectionEnums.TableResult}");
            buttons[0][1] = InlineKeyboardButton.WithCallbackData(Resources.SolveAgainButton, $"{SectionEnums.DbProblemSolve} {problemId}");
            return(new PreparedMessageContent
            {
                ResponseText = sb.ToString(),
                InlineKeyboardMarkup = new InlineKeyboardMarkup(buttons)
            });
        }
        public async Task Should_Generate_Auth_Link()
        {
            const string publicKey = "-----BEGIN PUBLIC KEY-----\n" +
                                     "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0VElWoQA2SK1csG2/sY/\n" +
                                     "wlssO1bjXRx+t+JlIgS6jLPCefyCAcZBv7ElcSPJQIPEXNwN2XdnTc2wEIjZ8bTg\n" +
                                     "BlBqXppj471bJeX8Mi2uAxAqOUDuvGuqth+mq7DMqol3MNH5P9FO6li7nZxI1FX3\n" +
                                     "9u2r/4H4PXRiWx13gsVQRL6Clq2jcXFHc9CvNaCQEJX95jgQFAybal216EwlnnVV\n" +
                                     "giT/TNsfFjW41XJZsHUny9k+dAfyPzqAk54cgrvjgAHJayDWjapq90Fm/+e/DVQ6\n" +
                                     "BHGkV0POQMkkBrvvhAIQu222j+03frm9b2yZrhX/qS01lyjW4VaQytGV0wlewV6B\n" +
                                     "FwIDAQAB\n" +
                                     "-----END PUBLIC KEY-----";

            PassportScope scope = new PassportScope(new[]
            {
                new PassportScopeElementOne(PassportEnums.Scope.Address)
            });
            AuthorizationRequestParameters authReq = new AuthorizationRequestParameters(
                botId: _fixture.BotUser.Id,
                publicKey: publicKey,
                nonce: "Test nonce for address",
                scope: scope
                );

            await BotClient.SendTextMessageAsync(
                _fixture.SupergroupChat,
                "Share your *residential address* with bot using Passport.\n\n" +
                "1. Click inline button\n" +
                "2. Open link in browser to redirect you back to Telegram passport\n" +
                "3. Authorize bot to access the info",
                ParseMode.Markdown,
                replyMarkup : (InlineKeyboardMarkup)InlineKeyboardButton.WithUrl(
                    "Share via Passport",
                    $"https://telegrambots.github.io/Telegram.Bot.Extensions.Passport/redirect.html?{authReq.Query}"
                    )
                );

            Update passportUpdate = await _fixture.UpdateReceiver.GetPassportUpdate();

            _classFixture.Entity = passportUpdate;
        }
 public InlineKeyboardMarkup(InlineKeyboardButton[][] inlineKeyboard)
 {
     InlineKeyboard = inlineKeyboard;
 }