/// <summary> /// Возвращает клавиатуру из указанных рядов кнопок. /// </summary> /// <returns>Клавиатура.</returns> /// <param name="buttonRows">Ряды из кнопок.</param> internal static KeyboardButton[][] BuildKeyboard(params KeyboardButton[][] buttonRows) { var result = new KeyboardButton[buttonRows.Length][]; for (int i = 0; i < buttonRows.Length; i++) { result[i] = buttonRows[i]; } return(result); }
static async Task RequestContactAndLocation(Message message) { var requestReplyKeyboard = new ReplyKeyboardMarkup(new[] { KeyboardButton.WithRequestLocation("Location"), KeyboardButton.WithRequestContact("Contact"), }); await Bot.SendTextMessageAsync( chatId : message.Chat.Id, text : "Who or Where are you?", replyMarkup : requestReplyKeyboard ); }
private KeyboardButton[] PopulateMenu2(IEnumerable <string> buttons) { KeyboardButton[] keyboardButtons = new KeyboardButton[buttons.Count()]; int i = 0; foreach (string text in buttons) { keyboardButtons[i] = new KeyboardButton("/" + text); keyboardButtons.Append(new KeyboardButton(text)); i++; } return(keyboardButtons); }
/// <summary> /// Возвращает кнопки с указанными заголовками. /// </summary> /// <returns>Кнопки для клавиатуры.</returns> /// <param name="captions">Заголовки кнопок.</param> internal static KeyboardButton[] BuildButtonsRow(params string[] captions) { var result = new KeyboardButton[captions.Length]; for (int i = 0; i < captions.Length; i++) { result[i] = new KeyboardButton { Text = captions[i] }; } return(result); }
public static ReplyKeyboardMarkup GetReplyKeyboard(List <string> keys) { var rkm = new ReplyKeyboardMarkup(); var rows = new List <KeyboardButton[]>(); var cols = new List <KeyboardButton>(); foreach (var t in keys) { KeyboardButton kButton = new KeyboardButton(t); cols.Add(kButton); rows.Add(cols.ToArray()); cols = new List <KeyboardButton>(); } rkm.Keyboard = rows.ToArray(); rkm.OneTimeKeyboard = true; return(rkm); }
private TelegramBotClient Bot; // ссылка на объект телеграмм-бот-клиента public Form1() { InitializeComponent(); Bot = new TelegramBotClient(Token); // создаём бота #region Задание кнопок leftbutton = new KeyboardButton("Старт"); // кнопка для пуска или интервала righttbutton = new KeyboardButton("Стоп"); // кнопка для остановки row = new KeyboardButton[2]; row[0] = leftbutton; row[1] = righttbutton; keyboard = new ReplyKeyboardMarkup(row); keyboard.ResizeKeyboard = true; #endregion Run(); }
static void First(Telegram.Bot.Args.MessageEventArgs e) { KeyboardButton[][] button = new KeyboardButton[2][]; button[0] = new KeyboardButton[2]; button[1] = new KeyboardButton[1]; button[0][0] = new KeyboardButton("ምስሊያዊ አነጋገር"); button[0][1] = new KeyboardButton("ፈሊጣዊ አነጋገር"); button[1][0] = new KeyboardButton("ጥያቄ"); ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup(button); bot.DeleteMessageAsync(e.Message.Chat.Id, e.Message.MessageId); Message Keyboard_msg = bot.SendTextMessageAsync( chatId: e.Message.Chat, text: "Selecte your choice! የሚፈልጉትን ይምረጡ!", parseMode: ParseMode.Html, disableNotification: true, replyMarkup: keyboardMarkup ).Result; markupID = Keyboard_msg.MessageId; }
public async Task <bool> GetBranch() { Dictionary <string, string> b = new Dictionary <string, string>() { { "BOS", "Boston" }, { "RHI", "Rhode Island" }, { "NJR", "New Jersey" }, { "CON", "Connecticut" }, { "PHI", "Philadelphia" }, { "CHI", "Chicago" }, { "CLE", "Cleveland" }, { "COL", "Columbus" }, { "VIR", "Virginia" }, { "VAB", "Virginia Beach" }, { "FTL", "Fort Lauderdale" }, { "KAN", "Kansas City" }, { "IND", "Indianapolis" }, { "MIN", "Minneapolis" }, { "WIL", "Wilmington" } }; KeyboardButton[][] buttons = new KeyboardButton[4][]; var keys = b.Keys.ToArray(); int count = 15; for (int i = 0; i < 4; i++) { buttons[i] = new KeyboardButton[Math.Min(4, count)]; for (int j = 0; j < buttons[i].Length; j++) { buttons[i][j] = keys[15 - count]; --count; } } var send = await this.Bot.SendTextMessageAsync(this.update.Message.Chat.Id, "What is your branch?", replyMarkup : new ReplyKeyboardMarkup(buttons, false, false)); if (send != null) { Task <bool> x; do { x = this.GetUpdates(); x.Wait(); } while (!x.Result); send = await this.Bot.SendTextMessageAsync(this.update.Message.Chat.Id, "Upload your doc!", replyMarkup : new ReplyKeyboardHide()); if (b.TryGetValue(this.msgs[0].update.Message.Text, out string branch)) { this.branch = branch; return(true); } else { var err = this.msgs[0].update.Message; string log = "\r\nGETBRANCH EXCEPTION - INVALID INPUT\r\n"; foreach (var prop in err.GetType().GetProperties()) { log += String.Format("{0} = {1}\r\n", prop.Name, prop.GetValue(err, null)); } System.IO.File.AppendAllText(this.botPath + "ErrorLog.txt", log); return(false); } } else { var err = this.update.Message.From; string log = "\r\nGETBRANCH EXCEPTION - MESSAGE FAILED TO SEND\r\n"; foreach (var prop in err.GetType().GetProperties()) { log += String.Format("{0} = {1}\r\n", prop.Name, prop.GetValue(err, null)); } System.IO.File.AppendAllText(this.botPath + "ErrorLog.txt", log); return(false); } }
private static async void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs) { var message = messageEventArgs.Message; if (message == null || message.Type != MessageType.Text) { return; } switch (message.Text.Split(' ').First()) { // send inline keyboard case "/inline": await Bot.SendChatActionAsync(message.Chat.Id, ChatAction.Typing); await Task.Delay(500); // simulate longer running task var inlineKeyboard = new InlineKeyboardMarkup(new[] { new [] // first row { InlineKeyboardButton.WithCallbackData("First"), InlineKeyboardButton.WithCallbackData("Second"), }, new [] // second row { InlineKeyboardButton.WithCallbackData("First"), InlineKeyboardButton.WithCallbackData("Second"), } }); await Bot.SendTextMessageAsync( message.Chat.Id, "Choose", replyMarkup : inlineKeyboard); break; // send custom keyboard case "/keyboard": ReplyKeyboardMarkup ReplyKeyboard = new[] { new[] { "First", "Second" }, new[] { "First", "Second" }, }; await Bot.SendTextMessageAsync( message.Chat.Id, "Choose", replyMarkup : ReplyKeyboard); break; // request location or contact case "/request": var RequestReplyKeyboard = new ReplyKeyboardMarkup(new[] { KeyboardButton.WithRequestLocation("Location"), KeyboardButton.WithRequestContact("Contact"), }); await Bot.SendTextMessageAsync( message.Chat.Id, "Who or Where are you?", replyMarkup : RequestReplyKeyboard); break; default: const string usage = @" Usage: /inline - send inline keyboard /keyboard - send custom keyboard /request - request location or contact /subscribe - add to db datas"; await Bot.SendTextMessageAsync( message.Chat.Id, usage, replyMarkup : new ReplyKeyboardRemove()); break; } }
static async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) { if (update.Type == UpdateType.Message && update.Message != null && update.Message.Type == MessageType.Text) { long chatId = update.Message.Chat.Id; string messageText = update.Message.Text; if (messageText == "/start") { string menu = "/start - запуск\n/inline - меню\n/keyboard - сообщения\n/clearkeyboard - убрать кнопки"; await botClient.SendTextMessageAsync(chatId, menu, cancellationToken : cancellationToken); } else if (messageText == "/inline") { InlineKeyboardMarkup inlineKeyboard = new InlineKeyboardMarkup(new[] { new[] { InlineKeyboardButton.WithUrl("VK", "https://vk.com/mishanya167"), InlineKeyboardButton.WithUrl("LinkedIn", "https://www.linkedin.com/in/%D0%BC%D0%B8%D1%85%D0%B0%D0%B8%D0%BB-%D0%BA%D0%BE%D0%B2%D0%B0%D0%BB%D1%91%D0%B2-79637b164/") }, new[] { InlineKeyboardButton.WithCallbackData("Дата и время", "DateTime"), InlineKeyboardButton.WithCallbackData("Картинка", "Photo") } }); await botClient.SendTextMessageAsync(chatId, "Выберите пункт меню: ", replyMarkup : inlineKeyboard, cancellationToken : cancellationToken); } else if (messageText == "/keyboard") { ReplyKeyboardMarkup replayKeyBoard = new ReplyKeyboardMarkup(new[] { new[] { new KeyboardButton("Привет"), new KeyboardButton("Как дела?") }, new[] { KeyboardButton.WithRequestContact("Контакт"), KeyboardButton.WithRequestLocation("Геолокация") } }); await botClient.SendTextMessageAsync(chatId, "Выберите сообщение.", replyMarkup : replayKeyBoard, cancellationToken : cancellationToken); } else if (messageText == "/clearkeyboard") { await botClient.SendTextMessageAsync(chatId, "Кнопки убраны.", replyMarkup : new ReplyKeyboardRemove(), cancellationToken : cancellationToken); } else { SessionsClient sessionsClient = await SessionsClient.CreateAsync(); SessionName sessionName = new SessionName("small-talk-srqi", Guid.NewGuid().ToString()); QueryInput queryInput = new QueryInput { Text = new TextInput { Text = messageText, LanguageCode = "ru-Ru" } }; DetectIntentResponse response = await sessionsClient.DetectIntentAsync(sessionName, queryInput); if (response.QueryResult.FulfillmentMessages.Count > 0) { await botClient.SendTextMessageAsync(chatId, response.QueryResult.FulfillmentText, cancellationToken : cancellationToken); } else { await botClient.SendTextMessageAsync(chatId, "Прости, я тебя не понимаю.", cancellationToken : cancellationToken); } } } if (update.Type == UpdateType.CallbackQuery && update.CallbackQuery.Message != null) { string data = update.CallbackQuery.Data; if (data == "DateTime") { await botClient.AnswerCallbackQueryAsync(update.CallbackQuery.Id, DateTime.Now.ToString(), cancellationToken : cancellationToken); } if (data == "Photo") { await botClient.SendPhotoAsync(update.CallbackQuery.Message.Chat.Id, "https://big-rostov.ru/wp-content/uploads/2021/04/i-7-1.jpg", cancellationToken : cancellationToken); } } }
private async Task BotOnMessageReceived(Message message) { Console.WriteLine($"Receive message type: {message.Type}"); if (message.Type != MessageType.Text) { return; } var action = (message.Text.Split(' ').First()) switch { "/inline" => SendInlineKeyboard(message), "/keyboard" => SendReplyKeyboard(message), "/photo" => SendFile(message), "/request" => RequestContactAndLocation(message), "/help" => Usage(message), _ => Nope(message) }; await action; // Send inline keyboard // You can process responses in BotOnCallbackQueryReceived handler async Task SendInlineKeyboard(Message message) { await _bot.SendChatActionAsync(message.Chat.Id, ChatAction.Typing); // Simulate longer running task await Task.Delay(500); var inlineKeyboard = new InlineKeyboardMarkup(new[] { // first row new [] { InlineKeyboardButton.WithCallbackData("1.1", "11"), InlineKeyboardButton.WithCallbackData("1.2", "12"), }, // second row new [] { InlineKeyboardButton.WithCallbackData("2.1", "21"), InlineKeyboardButton.WithCallbackData("2.2", "22"), } }); await _bot.SendTextMessageAsync( chatId : message.Chat.Id, text : "Choose", replyMarkup : inlineKeyboard ); } async Task SendReplyKeyboard(Message message) { var replyKeyboardMarkup = new ReplyKeyboardMarkup( new KeyboardButton[][] { new KeyboardButton[] { "1.1", "1.2" }, new KeyboardButton[] { "2.1", "2.2" }, }, resizeKeyboard: true ); await _bot.SendTextMessageAsync( chatId : message.Chat.Id, text : "Choose", replyMarkup : replyKeyboardMarkup ); } async Task SendFile(Message message) { await _bot.SendChatActionAsync(message.Chat.Id, ChatAction.UploadPhoto); const string filePath = @"Files/tux.png"; using var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); var fileName = filePath.Split(Path.DirectorySeparatorChar).Last(); await _bot.SendPhotoAsync( chatId : message.Chat.Id, photo : new InputOnlineFile(fileStream, fileName), caption : "Nice Picture" ); } async Task RequestContactAndLocation(Message message) { var RequestReplyKeyboard = new ReplyKeyboardMarkup(new[] { KeyboardButton.WithRequestLocation("Location"), KeyboardButton.WithRequestContact("Contact"), }); await _bot.SendTextMessageAsync( chatId : message.Chat.Id, text : "Who or Where are you?", replyMarkup : RequestReplyKeyboard ); } async Task Usage(Message message) { const string usage = "Usage:\n" + "/inline - send inline keyboard\n" + "/keyboard - send custom keyboard\n" + "/photo - send a photo\n" + "/request - request location or contact"; await _bot.SendTextMessageAsync( chatId : message.Chat.Id, text : usage, replyMarkup : new ReplyKeyboardRemove() ); } Task Nope(Message message) { return(Task.CompletedTask); } }
private static void Client_OnMessage(object sender, MessageEventArgs message) { long chatID = message.Message.Chat.Id; string userMessage = message.Message.Text; string botMessage = ""; decimal bankLat = 0, bankLng = 0, distance = 0, lat = 0, lng = 0; ReplyKeyboardMarkup loc = null; Dictionary <string, string> dbRatesInfo; List <Bank> dbBankRates; UserRequest userRequest = GetUserRequest(chatID, message); DB db = new DB(); if (userRequest.Location != null) { lat = Convert.ToDecimal(userRequest.Location.Latitude); lng = Convert.ToDecimal(userRequest.Location.Longitude); } if (userMessage != null) { db.SetLogin(chatID, lat, lng, userMessage); } MemoryStream img = new MemoryStream(); if (userRequest.Request == "/relocate" && message.Message.Location != null) { botMessage = "Дякую, Вашу локацію оновлено."; } else if (userMessage == "/statistics") { List <double> ratesList = db.GetLastRates(); double rateLast = ratesList.Last(); double rateDelta = Math.Round((rateLast / ratesList.First() - 1) * 100, 2); string[] prediction = db.GetPrediction().Split(','); botMessage = String.Concat( "На сьогодні середній курс $ = ", Math.Round(rateLast, 2), " грн/дол. ", "За останні два тижні курс ", (rateDelta < 0 ? "знизився" : "підвищився"), " на ", Math.Abs(rateDelta), "%.\n" ); ChartDrawer chart = new ChartDrawer(); Image chartImg = chart.GetChart(ratesList.ToArray()); chartImg.Save(img, ImageFormat.Png); img.Position = 0; } else if (userRequest.Request == null) { botMessage = String.Concat( "<b>Вітаю! Я Ваш валютний асистент</b>\n", "Оберіть одну з опцій: \n", "- я хочу купити $: /buy\n", "- я хочу продати $: /sell\n", "- я хочу купити €: /buy_eur\n", "- я хочу продати €: /sell_eur\n", "- змінити локацію: /relocate\n", "- статистика: /statistics\n", "- зворотній зв'язок: /feedback\n\n", "<i>*дані надані сайтом finance.ua</i>\n\n" ); } else if (userRequest.Location == null || userMessage == "/relocate") { botMessage = "Будь-ласка, відправте вашу локацію"; KeyboardButton k = new KeyboardButton("Відправити"); k.RequestLocation = true; loc = new ReplyKeyboardMarkup(new[] { k }); loc.ResizeKeyboard = true; } else if (userRequest.Location != null && (userRequest.Request == "/sell" || userRequest.Request == "/buy" || userRequest.Request == "/sell_eur" || userRequest.Request == "/buy_eur")) { if (userMessage != null) { Decimal.TryParse(Regex.Match(userMessage, @"\d+").Value, out distance); } if (distance > 99) { distance /= 1000; } if (distance == 0) { botMessage = "Будь-ласка, відправте радіус пошуку.\nНа приклад, 1км"; } } if (userRequest.Location != null && distance > 0) { lat = Convert.ToDecimal(userRequest.Location.Latitude); lng = Convert.ToDecimal(userRequest.Location.Longitude); byte orderType = (userRequest.Request == "/buy" || userRequest.Request == "/buy_eur") ? (byte)1 : (byte)2; string currencyCode = userRequest.Request.Contains("eur") ? "EUR" : "USD"; string currencyHTML = currencyCode == "USD" ? "$" : "€"; dbBankRates = db.GetBanksNearby(lat, lng, orderType, distance, currencyCode); if (dbBankRates.Count == 0) { botMessage = "В даному околі не знайдено жодного банку. Будь-ласка, оберіть більший радіус"; } else { bankLat = dbBankRates.First().Lat; //Convert.ToDecimal(dbBankRates["Lat"]); bankLng = dbBankRates.First().Lng; botMessage = String.Concat( "Найкращий курс в обраній локації:\n", dbBankRates.First().BankName, "\nВідстань: ", DistanceAdjuster(dbBankRates.First().Distance), "\nКурс ", currencyHTML, ": ", dbBankRates.First().Rate, "\n\nІнші варіанти в околі\n"); foreach (Bank item in dbBankRates.Skip(1)) { botMessage = String.Concat(botMessage, "💰 ", item.BankName, " : ", DistanceAdjuster(item.Distance), " : ", item.Rate, "\n"); } dbRatesInfo = db.GetRatesInfo(currencyCode); botMessage = String.Concat( botMessage, "\n<i>*оптимальний курс на ринку: ", dbRatesInfo[(orderType == 1 ? "OptimalAsk" : "OptimalBid")], "</i>"); } } if (userRequest.Request == "/feedback" && userMessage != "/feedback") { botMessage = "Дякую, Ваше повідомлення найближчим часом буде оброблено і надана відповідь."; userRequest.Request = null; } if (userMessage == "/feedback") { botMessage = "Напишіть, будь-ласка, Ваше повідомлення:"; } if (userMessage.Contains("subscribe")) { bool isUnsubscribe = (userMessage == "/subscribe") ? false : true; db.Unsubscribe(chatID, isUnsubscribe); botMessage = (isUnsubscribe) ? "Ви успішно відписані від розсилки" : "Ви успішно підписані на розсилку"; } if (botMessage.Length > 0) { client.SendTextMessageAsync(chatID, botMessage, ParseMode.Html, replyMarkup: loc); } if (userMessage == "/statistics") { client.SendPhotoAsync(chatID, new FileToSend("chart", img)); } if (bankLat > 0) { client.SendLocationAsync(chatID, (float)bankLng, (float)bankLat); } }
private static void Bot_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e) { if (e.Message.Text == "/start") { deleteErrorMsg(e); First(e); } else { if (e.Message.Text == "ምስሊያዊ አነጋገር") { bot.DeleteMessageAsync(e.Message.Chat.Id, e.Message.MessageId); bot.DeleteMessageAsync(e.Message.Chat.Id, markupID); KeyboardButton[][] button = new KeyboardButton[2][]; button[0] = new KeyboardButton[2]; button[1] = new KeyboardButton[1]; button[0][0] = new KeyboardButton("ምስሊያዊ አነጋገር"); button[0][1] = new KeyboardButton("ፈሊጣዊ አነጋገር"); button[1][0] = new KeyboardButton("ጥያቄ"); ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup(button); Message data = bot.SendTextMessageAsync( chatId: e.Message.Chat, text: dataምስሊያዊ(), parseMode: ParseMode.Html, replyMarkup: keyboardMarkup ).Result; markupID = data.MessageId; } else if (e.Message.Text == "ፈሊጣዊ አነጋገር") { bot.DeleteMessageAsync(e.Message.Chat.Id, e.Message.MessageId); bot.DeleteMessageAsync(e.Message.Chat.Id, markupID); KeyboardButton[][] button = new KeyboardButton[2][]; button[0] = new KeyboardButton[2]; button[1] = new KeyboardButton[1]; button[0][0] = new KeyboardButton("ምስሊያዊ አነጋገር"); button[0][1] = new KeyboardButton("ፈሊጣዊ አነጋገር"); button[1][0] = new KeyboardButton("ጥያቄ"); ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup(button); Message data = bot.SendTextMessageAsync( chatId: e.Message.Chat, text: dataፈሊጣዊ(), parseMode: ParseMode.Html, replyMarkup: keyboardMarkup ).Result; markupID = data.MessageId; } else if (e.Message.Text == "ጥያቄ") { string d1 = ""; string d2 = ""; string d3 = ""; string d4 = ""; if (!String.Equals(d1, d2) && !String.Equals(d2, d3) && !string.Equals(d1, d3)) { d1 += dataመልስ(); d2 += dataመልስ(); d3 += dataመልስ(); d4 += dataመልስ(); } if (e.Message.Text == dataመልስ()) { point += 10; bot.DeleteMessageAsync(e.Message.Chat.Id, e.Message.MessageId); bot.DeleteMessageAsync(e.Message.Chat.Id, markupID); KeyboardButton[][] button = new KeyboardButton[2][]; button[0] = new KeyboardButton[2]; button[1] = new KeyboardButton[2]; button[0][0] = new KeyboardButton(d1); button[0][1] = new KeyboardButton(d2); button[1][0] = new KeyboardButton(d3); button[1][1] = new KeyboardButton(d4); ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup(button); Message data = bot.SendTextMessageAsync( chatId: e.Message.Chat, text: dataጥያቄ(), parseMode: ParseMode.Html, replyMarkup: keyboardMarkup ).Result; markupID = data.MessageId; } else { bot.DeleteMessageAsync(e.Message.Chat.Id, e.Message.MessageId); bot.DeleteMessageAsync(e.Message.Chat.Id, markupID); KeyboardButton[][] button = new KeyboardButton[2][]; button[0] = new KeyboardButton[2]; button[1] = new KeyboardButton[2]; button[0][0] = new KeyboardButton(d1); button[0][1] = new KeyboardButton(d2); button[1][0] = new KeyboardButton(d3); button[1][1] = new KeyboardButton(d4); ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup(button); Message data = bot.SendTextMessageAsync( chatId: e.Message.Chat, text: dataጥያቄ(), parseMode: ParseMode.Html, replyMarkup: keyboardMarkup ).Result; markupID = data.MessageId; } } } }