public async Task sentTelegram(string filename, string locationStr, int locationIndex) { try { var bot = new Telegram.Bot.TelegramBotClient("*******************"); List <int> ChatIDList = _context.LocationTelegram.Where(x => x.LocationIndex == locationIndex).Select(x => x.ChatID).ToList(); foreach (int chatID in ChatIDList) { await bot.SendTextMessageAsync(chatID, "From: SkyTech Mask Monitoring System"); await bot.SendTextMessageAsync(chatID, "Subject: Notification of people without mask"); await bot.SendTextMessageAsync(chatID, "Location: " + locationStr); await bot.SendTextMessageAsync(chatID, "Date Time: " + DateTime.Now); await bot.SendTextMessageAsync(chatID, "A person not wearing mask is discovered in the premises.<br/> This is a system generated email. Please do not reply."); using (Stream stream = System.IO.File.OpenRead(filename)) { await bot.SendPhotoAsync(chatID, stream); } } } catch (Exception ex) { Debug.WriteLine("Send telegram"); Debug.WriteLine(ex.InnerException); } }
private void SendOneMessage(long id, String s, Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup keyboardMarkup) { try { bot.SendTextMessageAsync(id, s, Telegram.Bot.Types.Enums.ParseMode.Default, true, false, 0, keyboardMarkup); } catch (Telegram.Bot.Exceptions.ApiRequestException ex) { SendMessagToMaster(ex.ToString()); } }
private void SendOneMessage(long id, String s, Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup keyboardMarkup) { try { bot.SendTextMessageAsync(id, s, true, true, 0, keyboardMarkup, Telegram.Bot.Types.Enums.ParseMode.Html); } catch (Telegram.Bot.Exceptions.ApiRequestException ex) { } }
private async void BotTelegram_OnMessage(object sender, MessageEventArgs e) { var message = e.Message; if (message == null || message.Type != MessageType.TextMessage) { return; } var client = new OpenWeatherMapClient("7574caa56a934eb3b27c54904c019e03"); var weather = client.CurrentWeather.GetByName(message.Text); var temp = "\uD83C\uDF21"; var degree = "\u00B0"; //if (/*weather.Status == TaskStatus.WaitingForActivation*/ weather.Exception == null && !message.Text.StartsWith("/start")) //{ //var clouds = Icons.getIcon(weather.Result.Clouds.Name); //await botTelegram.SendTextMessageAsync(message.Chat.Id, // "City: " + weather.Result.City.Name + "\n" + // "Temperature: " + temp + Math.Round((Convert.ToInt32(weather.Result.Temperature.Value) - 273.15), 1) + degree + "\n" + // "Clouds: " + clouds + weather.Result.Clouds.Name + "\n" + // "Pressure: " + Math.Round((Convert.ToDouble(weather.Result.Pressure.Value) / 1.333220000000039), 2)); //} //else //{ // if (message.Text.StartsWith("/start")) // { // await botTelegram.SendTextMessageAsync(message.Chat.Id, "Hello to WeatherBot!!!"); // } // else // { // await botTelegram.SendTextMessageAsync(message.Chat.Id, "Error city"); // } //} if (message.Text.StartsWith("/start")) { await botTelegram.SendTextMessageAsync(message.Chat.Id, "Hello to WeatherBot!!!"); } else { try { var clouds = Icons.getIcon(weather.Result.Clouds.Name); await botTelegram.SendTextMessageAsync(message.Chat.Id, "City: " + weather.Result.City.Name + "\n" + "Temperature: " + temp + Math.Round((Convert.ToInt32(weather.Result.Temperature.Value) - 273.15), 1) + degree + "\n" + "Clouds: " + clouds + weather.Result.Clouds.Name + "\n" + "Pressure: " + Math.Round((Convert.ToDouble(weather.Result.Pressure.Value) / 1.333220000000039), 2)); } catch (AggregateException) { botTelegram.SendTextMessageAsync(message.Chat.Id, "Error city"); // await botTelegram.SendTextMessageAsync(message.Chat.Id, "Error city"); } } }
static async Task RequestContact(Message message) { var RequestReplyKeyboard = new ReplyKeyboardMarkup(new[] { KeyboardButton.WithRequestContact("Contact"), }); await Bot.SendTextMessageAsync( chatId : message.Chat.Id, text : "Who are you?", replyMarkup : RequestReplyKeyboard ); }
private async static void SendMessageAsync(long?ChatId, string _Text, IReplyMarkup Markup = null) { try { // if (_Text.Length > 0 && ChatId != 0 && ChatId.HasValue) await bot.SendTextMessageAsync(ChatId.Value, _Text, ParseMode.Html, false, false, 0, Markup); } catch (System.Exception ex) { // ReportError(ex, "SendMessageAsync Error\n" + Info + "\nWas Blocked The Bot.", 301334572); } }
private static async void MessageReceived(object sender, MessageEventArgs e) { try { if (e.Message.Text.Contains("/report")) { var result = ""; foreach (var key in _messagesCount.Keys) { result += $"[{_messagesCount[key].Name}](tg://user?id={key}) - {_messagesCount[key].MessageCount} پیام\r\n"; } if (result.Length > 2) { result = result.Substring(0, result.Length - 2); } else { result = "حافظم خالیه"; } await botClient.SendTextMessageAsync(e.Message.Chat.Id, result, replyToMessageId : e.Message.MessageId, parseMode : ParseMode.Markdown); return; } if (!_messagesCount.ContainsKey(e.Message.From.Id)) { _messagesCount[e.Message.From.Id] = new UserData() { MessageCount = 0, }; } _messagesCount[e.Message.From.Id].MessageCount++; _messagesCount[e.Message.From.Id].Name = e.Message.From.FirstName + " " + e.Message.From.LastName; _messagesCount[e.Message.From.Id].UserName = e.Message.From.Username; if (_messagesCount[e.Message.From.Id].MessageCount >= Properties.Settings.Default.MessagePerDay) { if ((_messagesCount[e.Message.From.Id].MessageCount - Properties.Settings.Default.MessagePerDay) % 5 == 0) { await botClient.SendTextMessageAsync(e.Message.Chat.Id, $"{e.Message.From.FirstName} چقدر حرف میزنی. [مریم](tg://user?id=) ناراحت میشه. از صبح {_messagesCount[e.Message.From.Id].MessageCount} تا پیام فرستادی", replyToMessageId : e.Message.MessageId, parseMode : ParseMode.Markdown); } Console.WriteLine($"{e.Message.From.Username ?? e.Message.From.FirstName} has spoken beyond his/her limit({_messagesCount[e.Message.From.Id].MessageCount})"); } } catch { } Save(); }
private static async void GetMessage() { int lastMessageID = 0; while (true) { var message = await bot.GetUpdatesAsync(); if (message.Length > 0) { var last = message[message.Length - 1]; if (lastMessageID != last.Id) { Console.WriteLine(last.Message.Text); if (last.Message.Text == "Привет") { bot.SendTextMessageAsync(last.Message.Chat.Id, "Ну, здравствуй!").Wait(); } if (last.Message.Text == "Варя") { bot.SendTextMessageAsync(last.Message.Chat.Id, "Варя - самая красивая и умная на свете!").Wait(); } try { CultureInfo temp_culture = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US"); double cash = double.Parse(last.Message.Text); Thread.CurrentThread.CurrentCulture = temp_culture; if (cash > 0) { bot.SendTextMessageAsync(last.Message.Chat.Id, "Введено число. Что мы с ним будем делать?").Wait(); } } catch { } } lastMessageID = last.Id; } Thread.Sleep(200); } }
public async Task <IActionResult> NewMessage([FromForm] NewTelegramMessage newTelegramMessage) { try { _logger.LogInformation($"{newTelegramMessage.ChatId} : {newTelegramMessage.Text}"); var botClient = new Telegram.Bot.TelegramBotClient(newTelegramMessage.BotToken); var me = await botClient.GetMeAsync(); if (newTelegramMessage.File != null) { var resultPhotoMessage = await botClient.SendPhotoAsync(newTelegramMessage.ChatId, new InputMedia(newTelegramMessage.File.OpenReadStream(), newTelegramMessage.File.FileName), newTelegramMessage.Text); return(Ok(resultPhotoMessage.MessageId)); } else { var resultTextMessage = await botClient.SendTextMessageAsync(newTelegramMessage.ChatId, newTelegramMessage.Text); return(Ok(resultTextMessage.MessageId)); } } catch (Exception e) { _logger.LogError(e, e.Message); return(BadRequest(e.Message)); } }
public async Task <MessageSendResult> Send(INeedSend message) { ChatId destId = null; var user = _dbContext.Users.SingleOrDefault( x => x.Username != null && x.Username.ToLower() == message.To.ToLower() || x.PhoneNumber == _phoneHelper.Clear(message.To.ToLower())); if (user == null) { return(new MessageSendResult() { Message = message, IsSuccess = false, Error = $"Не могу отправить сообщение пользователю {message.To}, т.к.он не добавил бота в телеграмме" }); } destId = new ChatId(user.ChatId); var bot = new Telegram.Bot.TelegramBotClient(_configService.Config.BotApiKey); await bot.SendTextMessageAsync(destId, message.Text); return(new MessageSendResult() { Message = message, IsSuccess = true }); }
private static async void ProcessImage(string fileId, string path, long chatId) { try { string fileName = "./temp" + fileId + ".jpg"; var file = await Bot.GetFileAsync(fileId); FileStream fs = new FileStream(fileName, FileMode.Create); await Bot.DownloadFileAsync(file.FilePath, fs); fs.Close(); fs.Dispose(); Image img = System.Drawing.Image.FromFile(fileName); string cl_name = predict(img); await Bot.SendTextMessageAsync(chatId, cl_name); } catch (Exception ex) { Console.WriteLine("Error downloading: " + ex.Message); } }
private async Task ProceedUpdate(Update update) { try { Employee employee; if (update.Message.Contact != null) { employee = await this._employeeProvider.SetPhoneAndGetEmployee(update.Message.Contact.UserId, update.Message.Contact.PhoneNumber); await this.WriteMessageLog(new MessageLog(update, employee)); if (employee == null) { string text = "Вы не являетесь зарегистрированным участником проекта Чаевые-24. Проект Чаевые-24 позволяет работникам сферы услуг получать безналичные чаевые. Для подключения Вашего заведения свяжитесь с нашим учредителем:\r\nРинат @Rinat_G, +7 (927) 244-16-78"; await _telegramClient.SendTextMessageAsync(update.Message.From.Id, text, ParseMode.Default, false, false, 0, null, _cts.Token); await this.WriteMessageLog(new MessageLog(MessageLog.Types.NotRegistered, update.Message.From.Id)); return; } } else { employee = await this._employeeProvider.GetEmployeeByTelegramUserIdAsync(update.Message.From.Id); await this.WriteMessageLog(new MessageLog(update, employee)); if (employee == null) { string text = "Для авторизации в проекте Чаевые-24 нажмите на кнопку ниже"; await _telegramClient.SendTextMessageAsync(update.Message.From.Id, text, ParseMode.Default, false, false, 0, this.GetPhoneKeyboardMarkup(), _cts.Token); await this.WriteMessageLog(new MessageLog(MessageLog.Types.Authorize, update.Message.From.Id)); return; } } await this.ProcessCommand(update, employee); } catch (Exception ex) { string exStr = ex.ToString(); _logger.LogError(exStr); Helper.SaveDiagMessage(_sqlServer, DiagOptions.Tech, "TelegramHostedService.ProceedUpdate: " + exStr, _logger); } }
public async static Task <bool> sendMessage(string telegram_id, string message) { var Bot = new Telegram.Bot.TelegramBotClient(bot_id); Telegram.Bot.Types.Message msg = await Bot.SendTextMessageAsync(244853182, message); return(true); }
private static async System.Threading.Tasks.Task SendMessageAsync(string msg, string chatid) { Message message = await bot.SendTextMessageAsync( chatId : chatid, text : msg, parseMode : ParseMode.Html, disableNotification : false ); }
private async Task SendNotifications() { List <DiagBotUser> users = new List <DiagBotUser>(); List <DiagNotification> notifications = new List <DiagNotification>(); using (SqlConnection conn = this._sqlServer.GetConnection()) { await conn.OpenAsync(); using (SqlCommand cmd = this._sqlServer.GetSpCommand("telegram.Diag_Notifications_Proceed", conn)) { using (SqlDataReader dr = await cmd.ExecuteReaderAsync()) { while (dr.Read()) { users.Add(new DiagBotUser(dr)); } if (users.Count > 0) { dr.NextResult(); while (dr.Read()) { notifications.Add(new DiagNotification(dr)); } } } } } if (notifications.Count > 0) { foreach (DiagNotification n in notifications) { foreach (DiagBotUser u in users) { u.AddMessageIfNeeded(n); } } foreach (DiagBotUser u in users) { if (u.MessageCount > 0) { try { await _telegramClient.SendTextMessageAsync(u.TelegramId, u.GetMessages(), ParseMode.Html, false, false, 0, null, _cts.Token); } catch (Exception ex) { _logger.LogError(ex, "Ошибка при отправке оповещения"); } } } } }
/// <summary> /// 執行層,依照傳入參數發送訊息 /// </summary> /// /// <param name="token"></param> /// <param name="id"></param> /// /// <param name="message"></param> /// <returns></returns> public async Task Send(string token, string id, string message) { var Bot = new Telegram.Bot.TelegramBotClient(token); await Bot.SendTextMessageAsync( chatId : id, text : message ); }
private static void _bot_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e) { var chatId = e.Message.Chat.Id; var message = e.Message.Text; Random rand = new Random(); var r1 = rand.Next(0, 5); // от нуля до 4 _bot.SendTextMessageAsync(chatId, $"{dict[r1]}"); }
async void button1Click(Object sender, EventArgs e) { var Bot = new Telegram.Bot.TelegramBotClient("400994008:AAF_AngoYyaakmuAhsv63kSR_fXkO6NA8ek"); // инициализируем API await Bot.SetWebhookAsync(""); //Bot.SetWebhook(""); // Обязательно! убираем старую привязку к вебхуку для бота await Bot.SendTextMessageAsync(chatID, "Менты!! Мы закроемся не на долго🚔(Ведутся тех.работы)"); Application.Exit(); }
private static async void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs) { Telegram.Bot.Types.Message msg = messageEventArgs.Message; //создание экземпляра бота для чата var chatBot = new ChatBot("answersBase.txt", "dirtyBase.txt"); if (msg == null || msg.Type != MessageType.Text) { return; } String Answer = ""; switch (flag) { case 1: switch (msg.Text) { case "/start": Answer = "/stone - твой камень\r\n/scissors - твои ножницы\r\n/paper - твоя бумага\r\n/baba - показать смачную бабу"; break; case "/stone": Answer = "А у меня бумага - ты проиграл"; break; case "/scissors": Answer = "А у меня камень - ты проиграл"; break; case "/paper": Answer = "А у меня ножницы - ты проиграл"; break; case "/baba": Answer = "Вот тебе баба - http://holidaycalls.ru/wp-content/uploads/2012/07/%D0%91%D0%B0%D0%B1%D0%B0-%D0%AF%D0%B3%D0%B0-243x300.png"; break; default: Answer = chatBot.Ans(msg.Text); if (chatBot.temp == false) { flag = 3; chatBot.TeachQ(msg.Text); } break; } break; case 2: chatBot.TeachQ(msg.Text); Answer = "Вопрос запомнил. Теперь введи ответ."; flag = 3; break; case 3: chatBot.TeachA(msg.Text); flag = 1; chatBot.temp = true; Answer = "Запомнил!"; break; } await BOT.SendTextMessageAsync(msg.Chat.Id, Answer); }
public static void Send(string message) { try { var t = bot.SendTextMessageAsync(ID, message).Result; } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
public async Task <bool> GetResponse(long chatId) { string botToken = _configuration.GetValue <string>("Bot:Token"); Telegram.Bot.TelegramBotClient botClient = new Telegram.Bot.TelegramBotClient(botToken); try { BotResponseModel jsonResult = await Calculate(); string strFormattedResult = JsonConvert.SerializeObject(jsonResult, Formatting.Indented); await botClient.SendTextMessageAsync(chatId, strFormattedResult); return(true); } catch (Exception ex) { await botClient.SendTextMessageAsync(chatId, ex.Message); return(false); } }
private void send(string text, string destID) { try { var bot = new Telegram.Bot.TelegramBotClient(token); bot.SendTextMessageAsync(destID, text); } catch (Exception e) { throw e; } }
private async void Bot_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e) { var message = e.Message; if (message == null || message.Type != Telegram.Bot.Types.Enums.MessageType.Text) { return; } Console.WriteLine(message.Chat.Id + " " + message.Text); await Bot.SendTextMessageAsync(message.Chat.Id, message.Text); }
public async Task <IHttpActionResult> UpdateMsg(Update update) { try { if (update.Message.Text == "/start") { await Bot.SendTextMessageAsync(update.Message.From.Id, "Welcome To My Bot"); } else { string TranslateRequst = Translate.Translate(update.Message.Text, "Persian", "English"); await Bot.SendTextMessageAsync(update.Message.From.Id, TranslateRequst); } } catch (Exception ex) { throw; } return(Ok(update)); }
public async Task <bool> Execute() { string botToken = _configuration.GetValue <string>("Bot:Token"); Telegram.Bot.TelegramBotClient botClient = new Telegram.Bot.TelegramBotClient(botToken); BotSettingModel setting = LoadSetting(); Telegram.Bot.Types.Update[] updates = await botClient.GetUpdatesAsync(setting.LastChatID + 1); string RegisterKey = _configuration.GetValue <string>("Bot:RegisterKey"); string DeleteAccountKey = _configuration.GetValue <string>("Bot:DeleteAccountKey"); string GetResponseKey = _configuration.GetValue <string>("Bot:GetResponseKey"); foreach (Telegram.Bot.Types.Update update in updates) { string chatText = string.Empty; chatText = update?.Message?.Text ?? string.Empty; long chatId = update.Message.Chat.Id; if (chatText == RegisterKey) { if (!setting.Receivers.Any(x => x == chatId.ToString())) { setting.Receivers.Add(chatId.ToString()); await botClient.SendTextMessageAsync(chatId, "به دریافت کنندگان اضافه شدی", replyMarkup : getKeyboard()); } else { await botClient.SendTextMessageAsync(chatId, "قبلا اضافه شدی", replyMarkup : getKeyboard()); } } else if (chatText == DeleteAccountKey) { if (setting.Receivers.Any(x => x == chatId.ToString())) { setting.Receivers.Remove(chatId.ToString()); await botClient.SendTextMessageAsync(chatId, "از دریافت کنندگان حذف شدی", replyMarkup : getKeyboard()); } else { await botClient.SendTextMessageAsync(chatId, "توی لیست نیستی", replyMarkup : getKeyboard()); } } else if (chatText == "/start") { await botClient.SendTextMessageAsync(chatId, "سلام، چیکار کنم برات ؟!", replyMarkup : getKeyboard()); } else if (chatText == GetResponseKey) { await _restApi.GetResponse(chatId); } else { await botClient.SendTextMessageAsync(chatId, "نمیفهمم چی میگی", replyMarkup : getKeyboard()); } setting.LastChatID = update.Id; } SaveSetting(setting); return(true); }
private static async void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs) { Random rand = new Random(); int temp; Telegram.Bot.Types.Message msg = messageEventArgs.Message; if (msg == null || msg.Type != MessageType.Text) { return; } String Answer = ""; switch (msg.Text) { case "/start": Answer = "/stone - викинути камінь\r\n/scissors - викинути ножниці\r\n/paper - викинути бумагу\r https://takprosto.cc/wp-content/uploads/k/kak-vyigryvat-v-kamen-nozhnicy-bumaga/1.jpg"; break; case "/stone": temp = rand.Next(3); int n = 1; if (n == temp) { Answer = " А в меня бумага - ти програв https://s00.yaplakal.com/pics/pics_original/2/6/5/10431562.jpg"; } else { Answer = "Красавело-братело, ти виграв! https://day.kyiv.ua/sites/default/files/main/blogposts/maxresdefault_3.jpg"; } break; case "/scissors": temp = rand.Next(3); n = 1; if (n == temp) { Answer = "А у мене камінь - ти програв https://naked-science.ru/sites/default/files/styles/full_size/public/article/Depositphotos_41040383_m.jpg?itok=z_3ZSyF1"; } else { Answer = "Красавело-братело, ти виграв! https://gamebet.news/wp-content/uploads/2017/07/0273a1ada5003c5c2785b92fa7e9710a.jpg"; } break; case "/paper": temp = rand.Next(3); n = 1; if (n == temp) { Answer = "А у мене камінь - ти програв http://uaoch.com/wp-content/uploads/2018/06/1457cbc0d94ed3b.jpg"; } else { Answer = "Красавело-братело, ти виграв! https://i.ytimg.com/vi/gk5yeiydxV4/maxresdefault.jpg"; } break; default: Answer = "Не знаю такой команды"; break; } await BOT.SendTextMessageAsync(msg.Chat.Id, Answer); }
private static void BotOnTextReceived(object sender, MessageEventArgs messageEventArgs) { var message = messageEventArgs.Message; var inn = message.Text; try { if (inn == "/start") { while (true) { JObject jp = getInfo(); string res = parseJson(jp); Bot.SendTextMessageAsync(message.Chat.Id, res); Thread.Sleep(1000 * 60 * 60 * 4); } } } catch (Exception e) { Bot.SendTextMessageAsync(message.Chat.Id, "Неверно!"); } }
public async Task <bool> Send(int categoryId, string comment, string link) { var channels = _database.Channel.Where(o => o.CategoryId == categoryId).ToList(); foreach (var channel in channels) { var message = comment + Environment.NewLine + Environment.NewLine + link; var bot = new Telegram.Bot.TelegramBotClient(channel.Token); var result = await bot.SendTextMessageAsync(channel.Name, message, ParseMode.Default, false, false); } return(true); }
//Select statement public List <string>[] Select() { string query = "SELECT * FROM users WHERE chatID='252138799'"; //Create a list to store the result List <string>[] list = new List <string> [10]; var Bot = new Telegram.Bot.TelegramBotClient("508080647:AAFoHz99F8cgF4O4Yuj9uq7KrXYUKcXpExk"); list[0] = new List <string>(); list[1] = new List <string>(); list[2] = new List <string>(); list[3] = new List <string>(); list[4] = new List <string>(); list[5] = new List <string>(); list[6] = new List <string>(); list[7] = new List <string>(); //Open connection if (this.OpenConnection() == true) { //Create Command MySqlCommand cmd = new MySqlCommand(query, connection); //Create a data reader and Execute the command MySqlDataReader dataReader = cmd.ExecuteReader(); //Read the data and store them in the list while (dataReader.Read()) { list[0].Add(dataReader["Task"] + " "); list[1].Add(dataReader["Level"] + " "); list[2].Add(dataReader["Time"] + " "); list[3].Add(dataReader["Time2"] + " "); Bot.SendTextMessageAsync("252138799", dataReader["Task"].ToString() + " " + dataReader["Time"].ToString() + " " + dataReader["Time2"].ToString()); } //close Data Reader dataReader.Close(); //close Connection this.CloseConnection(); //return list to be displayed return(list); } else { return(list); } }
public static async Task SendMessage(string chatid, string message) { try { var bot = new Telegram.Bot.TelegramBotClient("312420207:AAGnEn6CztWMs8ExE9L808M2ZXApqTS2yPA"); await bot.SendTextMessageAsync(chatid, message); } catch (Exception ex) { Logger.Write("Telegram Nachricht Senden Fehlgeschlagen - Grund: " + ex.Message); if (OSystem.IsAvailableNetworkActive()) { } } }
public async Task PostToChannel(Comment comment) { try { if (string.IsNullOrWhiteSpace(token)) return; var api = new Telegram.Bot.TelegramBotClient(token); var text = GetChannelPostText(comment); await api.SendTextMessageAsync(channel, text, parseMode: ParseMode.Markdown, disableWebPagePreview: true); } catch (Exception e) { log.Error(e); ErrorLog.GetDefault(HttpContext.Current).Log(new Error(e)); } }