public bool AddFileToSend(String file) { try { DicomFile dicomFile = new DicomFile(file); // Only load to sopy instance uid to reduce amount of data read from file dicomFile.Load(DicomTags.SopInstanceUid, DicomReadOptions.Default | DicomReadOptions.DoNotStorePixelDataInDataSet); FileToSend fileStruct = new FileToSend(); fileStruct.filename = file; string sopClassInFile = dicomFile.DataSet[DicomTags.SopClassUid].ToString(); if (sopClassInFile.Length == 0) return false; if (!sopClassInFile.Equals(dicomFile.SopClass.Uid)) { Logger.LogError("SOP Class in Meta Info does not match SOP Class in DataSet"); fileStruct.sopClass = SopClass.GetSopClass(sopClassInFile); } else fileStruct.sopClass = dicomFile.SopClass; fileStruct.transferSyntax = dicomFile.TransferSyntax; _fileList.Add(fileStruct); } catch (DicomException e) { Logger.LogErrorException(e, "Unexpected exception when loading file for sending: {0}", file); return false; } return true; }
private async static void Bot_OnMessageReceived(object sender, MessageEventArgs e) { var message = e.Message; if (message == null || message.Type != MessageType.TextMessage) { await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Извини, но я могу воспринимать только текст"); } string name = $"{message.From.FirstName}{message.From.LastName}"; Console.WriteLine($"{name} отправил(a) сообщение '{message.Text}' "); switch (message.Text) { case "/start": keyboard.Start(Bot, e); break; case "/inline": keyboard.Inline(Bot, e); break; case "/keyboard": keyboard.Keyboard_k(Bot, e); break; case "/help": keyboard.Help(Bot, e); break; case "/ideas": last_message = keyboard.Idea(Bot, e); break; case "/calculator": keyboard.Calculator(Bot, e); break; default: //Bot.SendTextMessageAsync(e.Message.From.Id, "Прости, я не понимаю тебя").Wait(); //var response = apiAi.TextRequest(message.Text); //string answer = response.Result.Fulfillment.Speech; //if (answer == "") // answer = "Прости, я не понимаю тебя"; //await Bot.SendTextMessageAsync(e.Message.From.Id, answer); break; } blaCount = bla.Count() - 1; for (int i = 0; i <= product.Count() - 1; i++) { if ((last_message + 1 == e.Message.MessageId) && (e.Message.Text.ToLower() == product[i].product.ToLower())) { select_product = product[i].product; } } if ((blaCount != 0) & (count_idea == 0)) { for (int i = 0; i <= blaCount; i++) { if (select_product == bla[i].Product.ToLower()) { DataOfIdea tmp = new DataOfIdea(); tmp.ID = bla[i].ID; tmp.Name = bla[i].Name; tmp.Product = bla[i].Product; tmp.Photo = bla[i].Photo; tmp.Description = bla[i].Description; data.Add(tmp); } } } if (count_idea == 5) { Bot.SendTextMessageAsync(e.Message.Chat.Id, "К сожалению, в данной категории больше нет идей! Для того, чтобы найти что-то другое нужно выбрать /ideas").Wait(); select_product = ""; data.Clear(); count_idea = 0; } else if (data.Count() != 0) { Bot.SendTextMessageAsync(e.Message.Chat.Id, data[count_idea].Name + "\n" + data[count_idea].Description).Wait(); var FileUrl = string.Format(@"images//{0}", data[count_idea].Photo); var stream = new FileStream(FileUrl, FileMode.Open); var fileToSend = new FileToSend(data[count_idea].Photo, stream); await Bot.SendPhotoAsync(e.Message.Chat.Id, fileToSend); count_idea++; } }
/// <summary> /// Copied from https://github.com/MrRoundRobin/telegram.bot.examples/blob/master/Telegram.Bot.Examples.Echo/Program.cs /// </summary> private static async void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs) { var message = messageEventArgs.Message; if (message == null || message.Type != MessageType.TextMessage) { return; } if (message.Text.StartsWith("/inline")) // send inline keyboard { await Bot.SendChatActionAsync(message.Chat.Id, ChatAction.Typing); var keyboard = new InlineKeyboardMarkup(new[] { new[] // first row { new InlineKeyboardButton("1.1"), new InlineKeyboardButton("1.2"), }, new[] // second row { new InlineKeyboardButton("2.1"), new InlineKeyboardButton("2.2"), } }); await Task.Delay(500); // simulate longer running task await Bot.SendTextMessageAsync(message.Chat.Id, "Choose", replyMarkup : keyboard); } else if (message.Text.StartsWith("/keyboard")) // send custom keyboard { var keyboard = new ReplyKeyboardMarkup(new[] { new [] // first row { new KeyboardButton("1.1"), new KeyboardButton("1.2"), }, new [] // last row { new KeyboardButton("2.1"), new KeyboardButton("2.2"), } }); await Bot.SendTextMessageAsync(message.Chat.Id, "Choose", replyMarkup : keyboard); } else if (message.Text.StartsWith("/photo")) // send a photo { await Bot.SendChatActionAsync(message.Chat.Id, ChatAction.UploadPhoto); const string file = @"<FilePath>"; var fileName = file.Split('\\').Last(); using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read)) { var fts = new FileToSend(fileName, fileStream); await Bot.SendPhotoAsync(message.Chat.Id, fts, "Nice Picture"); } } else if (message.Text.StartsWith("/request")) // request location or contact { var keyboard = new ReplyKeyboardMarkup(new[] { new KeyboardButton("Location") { RequestLocation = true }, new KeyboardButton("Contact") { RequestContact = true }, }); await Bot.SendTextMessageAsync(message.Chat.Id, "Who or Where are you?", replyMarkup : keyboard); } else { var usage = @"Usage: /inline - send inline keyboard /keyboard - send custom keyboard /photo - send a photo /request - request location or contact "; await Bot.SendTextMessageAsync(message.Chat.Id, usage, replyMarkup : new ReplyKeyboardHide()); } }
/// <summary> /// Use this method to send .webp stickers. On success, the sent Message is returned. /// </summary> /// <param name="chatId">Unique identifier for the message recipient — User or GroupChat id</param> /// <param name="sticker">Sticker to send. You can either pass a file_id as String to resend a sticker that is already on the Telegram servers, or upload a new sticker using multipart/form-data.</param> /// <param name="replyToMessageId">Optional. If the message is a reply, ID of the original message</param> /// <param name="replyMarkup">Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</param> /// <returns>On success, the sent Message is returned.</returns> public async Task <Message> SendSticker(int chatId, FileToSend sticker, int replyToMessageId = 0, ReplyMarkup replyMarkup = null) => await SendMessage(MessageType.StickerMessage, chatId, sticker, replyToMessageId, replyMarkup).ConfigureAwait(false);
/// <summary> /// Сообщение с инстуркцией по импорту данных и csv /// </summary> /// <returns></returns> private async Task <IActionResult> SendImportFAQ() { try { await base.SendMessage(new BotMessage { TextMessage = "1) Заполните csv файл " + BotMessage.NewLine() + "2) Сохраните файл как Import.csv" + BotMessage.NewLine() + "3) Отправьте файл боту" }); using (MarketBotDbContext db = new MarketBotDbContext()) { Configuration configuration = db.Configuration.FirstOrDefault(); // FileId файла Пример.csv есть в базе if (configuration != null && configuration.ExampleCsvFileId != null) { FileToSend fileToSend = new FileToSend { Filename = "Пример.csv", FileId = configuration.ExampleCsvFileId }; var message = await SendDocument(fileToSend, "Пример заполнения"); } // FileID в базе нет, отправляяем файл и сохраняем в бд FileID if (configuration != null && configuration.ExampleCsvFileId == null) { var stream = System.IO.File.Open("Пример.csv", FileMode.Open); FileToSend fileToSend = new FileToSend { Filename = "Пример.csv", Content = stream }; var message = await SendDocument(fileToSend, "Пример заполнения"); configuration.ExampleCsvFileId = message.Document.FileId; db.SaveChanges(); } // FileId файла Шаблон.csv есть в базе if (configuration != null && configuration.TemplateCsvFileId != null) { FileToSend fileToSend = new FileToSend { Filename = "Шаблон.csv", FileId = configuration.ExampleCsvFileId }; var message = await SendDocument(fileToSend, "Пример заполнения"); } // FileID в базе нет, отправляяем файл и сохраняем в бд FileID if (configuration != null && configuration.TemplateCsvFileId == null) { var stream = System.IO.File.Open("Шаблон.csv", FileMode.Open); FileToSend fileToSend = new FileToSend { Filename = "Шаблон.csv", Content = stream }; var message = await SendDocument(fileToSend, "Пример заполнения"); configuration.TemplateCsvFileId = message.Document.FileId; db.SaveChanges(); } } return(base.OkResult); } catch (Exception exp) { return(base.NotFoundResult); } }
/// <summary> /// Use this method to send .webp stickers. On success, the sent Message is returned. /// </summary> /// <param name="chatId">Username of the target channel (in the format @channelusername)</param> /// <param name="sticker">Sticker to send. You can either pass a file_id as String to resend a sticker that is already on the Telegram servers, or upload a new sticker using multipart/form-data.</param> /// <param name="replyToMessageId">Optional. If the message is a reply, ID of the original message</param> /// <param name="replyMarkup">Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</param> /// <returns>On success, the sent Message is returned.</returns> public Task <Message> SendSticker(string chatId, FileToSend sticker, int replyToMessageId = 0, ReplyMarkup replyMarkup = null) { return(SendMessage(MessageType.StickerMessage, chatId, sticker, replyToMessageId, replyMarkup)); }
/// <summary> /// Use this method to send general files. On success, the sent Message is returned. Bots can send files of any type of up to 50 MB in size. /// </summary> /// <param name="chatId">Unique identifier for the message recipient — User or GroupChat id</param> /// <param name="document">File to send. You can either pass a file_id as String to resend a file that is already on the Telegram servers, or upload a new file using multipart/form-data.</param> /// <param name="replyToMessageId">Optional. If the message is a reply, ID of the original message</param> /// <param name="replyMarkup">Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</param> /// <returns>On success, the sent Message is returned.</returns> public async Task <Message> SendDocument(int chatId, FileToSend document, int replyToMessageId = 0, ReplyMarkup replyMarkup = null) => await SendMessage(MessageType.DocumentMessage, chatId, document, replyToMessageId, replyMarkup).ConfigureAwait(false);
public JsonResult SavePrePayment(int id, int deposit, string cardDetails) { Response response = null; try { int userId = GetAuthenticatedUserId(); List <BotSettings> settings; BotUserData userData; BotOrder item; using (KiaGalleryContext db = new KiaGalleryContext()) { item = db.BotOrder.Include(x => x.BotOrderLogList).Include(x => x.Product).First(x => x.Id == id); item.Status = BotOrderStatus.UnderConstruction; item.Deposit = deposit; item.CardDetails = cardDetails; // item.FirstPaymentDate = DateTime.Now; BotOrderLog log = new BotOrderLog() { OrderId = item.Id, Status = BotOrderStatus.UnderConstruction, CreateUserId = userId, CreateDate = DateTime.Now, Ip = Request.UserHostAddress }; db.BotOrderLog.Add(log); settings = db.BotSettings.ToList(); userData = db.BotUserData.First(x => x.ChatId == item.ChatId); db.SaveChanges(); } TelegramBotClient Bot = new TelegramBotClient(settings.First(x => x.Key == "BotApi").Value); if (userData.Language == 0) { string message = settings.First(x => x.Key == "SavePrePaymentText").ValueFa .Replace("{Name}", item.FirstName + " " + item.LastName) .Replace("{Date}", DateUtility.GetPersianDateTime(DateTime.Now)) .Replace("{OrderNo}", item.OrderSerial) .Replace("{Code}", item.Product.Code) .Replace("{Desc}", item.Description) .Replace("{Price}", deposit.ToString()); if (string.IsNullOrEmpty(item.Product.ProductFileList.FirstOrDefault(x => x.FileType == FileType.Bot).FileId)) { string filePath = "/Upload/Product/" + item.Product.ProductFileList.FirstOrDefault(x => x.FileType == FileType.Bot).FileName; Stream stream = System.IO.File.OpenRead(filePath); FileToSend file = new FileToSend(System.IO.Path.GetFileName(filePath), stream); Bot.SendPhotoAsync(userData.ChatId, file, message, false, 0); } else { FileToSend file = new FileToSend(item.Product.ProductFileList.FirstOrDefault(x => x.FileType == FileType.Bot).FileId); Bot.SendPhotoAsync(userData.ChatId, file, message, false, 0); } } else { string message = settings.First(x => x.Key == "SavePrePaymentText").Value .Replace("{Name}", item.FirstName + " " + item.LastName) .Replace("{Date}", DateUtility.GetPersianDateTime(DateTime.Now)) .Replace("{OrderNo}", item.OrderSerial) .Replace("{Code}", item.Product.Code) .Replace("{Desc}", item.Description) .Replace("{Price}", deposit.ToString()); if (string.IsNullOrEmpty(item.Product.ProductFileList.FirstOrDefault(x => x.FileType == FileType.Bot).FileId)) { string filePath = "/Upload/Data/" + item.Product.ProductFileList.FirstOrDefault(x => x.FileType == FileType.Bot).FileName; Stream stream = System.IO.File.OpenRead(filePath); FileToSend file = new FileToSend(System.IO.Path.GetFileName(filePath), stream); Bot.SendPhotoAsync(userData.ChatId, file, message, false, 0); } else { FileToSend file = new FileToSend(item.Product.ProductFileList.FirstOrDefault(x => x.FileType == FileType.Bot).FileId); Bot.SendPhotoAsync(userData.ChatId, file, message, false, 0); } } response = new Response() { status = 200 }; } catch (Exception ex) { response = Core.GetExceptionResponse(ex); } return(Json(response, JsonRequestBehavior.AllowGet)); }
private static async void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs) { var message = messageEventArgs.Message; if (message == null || message.Type != MessageType.TextMessage) { return; } //if (message.Text.StartsWith("/inline")) // send inline keyboard //{ // await Bot.SendChatActionAsync(message.Chat.Id, ChatAction.Typing); // var keyboard = new InlineKeyboardMarkup(new[] // { // new[] // first row // { // new InlineKeyboardButton("1.1"), // new InlineKeyboardButton("1.2"), // }, // new[] // second row // { // new InlineKeyboardButton("2.1"), // new InlineKeyboardButton("2.2"), // } // }); // await Task.Delay(500); // simulate longer running task // await Bot.SendTextMessageAsync(message.Chat.Id, "Choose", // replyMarkup: keyboard); //} //else if (message.Text.StartsWith("/Contact")) // send custom keyboard { var contactTxt = @"فروشگاه شالی هوم واردات و پخش اجناس دکوری و تزیینی منزل آدرس: بازار شوش ، پاساژ الغدیر، ط همکف پلاک 21 تلفن تماس:02155183208 همراه:09212836980 @Shalihome"; await Bot.SendTextMessageAsync(message.Chat.Id, contactTxt); } else if (message.Text == "/Location") { var results = GetLocation(); await Bot.AnswerInlineQueryAsync(message.Chat.Id.ToString(), results, isPersonal : true, cacheTime : 0); } else if (message.Text.StartsWith("/Groups")) // send custom keyboard { var rowsCount = Groups.Length / EachRowItems; KeyboardButton[][] arr = new KeyboardButton[rowsCount][]; for (int i = 0; i < rowsCount; i++) { arr[i] = new KeyboardButton[EachRowItems]; } for (int j = 0; j < rowsCount; j++) { for (int i = 0; i < EachRowItems; i++) { arr[j][i] = Groups[i + j * EachRowItems]; } } var keyboard = new ReplyKeyboardMarkup(arr); keyboard.ResizeKeyboard = true; await Bot.SendTextMessageAsync(message.Chat.Id, "لطفا دسته مورد نظر را انتخاب نمایید:", replyMarkup : keyboard); } //else if (message.Text.StartsWith("/keyboard")) // send custom keyboard //{ // var keyboard = new ReplyKeyboardMarkup(new[] // { // new [] // first row // { // new KeyboardButton("1.1"), // new KeyboardButton("1.2"), // }, // new [] // last row // { // new KeyboardButton("2.1"), // new KeyboardButton("2.2"), // } // }); // await Bot.SendTextMessageAsync(message.Chat.Id, "Choose", // replyMarkup: keyboard); //} else if (message.Text == "منوی اصلی" || message.Text == "/start") { await Bot.SendTextMessageAsync(message.Chat.Id, Instructions); } else if (Groups.Contains(message.Text)) // send a photo { await Bot.SendChatActionAsync(message.Chat.Id, ChatAction.UploadPhoto); string dir = Path + "\\" + message.Text; if (!Directory.Exists(dir)) { await Bot.SendTextMessageAsync(message.Chat.Id, "موردی یافت نشد"); } else { string[] fileEntries = Directory.GetFiles(dir); if (fileEntries.Length > 0) { foreach (string fileName in fileEntries) { using ( var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read) ) { var fts = new FileToSend(fileName, fileStream); await Bot.SendPhotoAsync(message.Chat.Id, fts, fileName.Split('\\').Last()); } } } } } //else if (message.Text.StartsWith("/request")) // request location or contact //{ // var keyboard = new ReplyKeyboardMarkup(new[] // { // new KeyboardButton("Location") // { // RequestLocation = true // }, // new KeyboardButton("Contact") // { // RequestContact = true // }, // }); // await Bot.SendTextMessageAsync(message.Chat.Id, "Who or Where are you?", replyMarkup: keyboard); //} else { await Bot.SendTextMessageAsync(message.Chat.Id, Instructions); } }
private Func <Task> SendFileFn(FileToSend file, long chatId) => () => _botClient.SendDocumentAsync(chatId, file);
public async Task SendDocumentAsync(long botChatId, FileToSend fileToSend) { await _bot.SendDocumentAsync(botChatId, fileToSend); }
public async void StartListen() { var bot = new TelegramBotClient("1794355084:AAFlARMlsA6HlVpX1IXELAOdTxjWCrYgCWE"); await bot.SetWebhookAsync(""); try { photo = new FileToSend( "https://sun9-46.userapi.com/impg/yP7m1fjPEW27EEPT0ZC5MBCmErrYcEMNKeYBGw/KY22S9UjkNw.jpg?size=1036x588&quality=96&sign=679220da15c5f3bf9ac1c7de9b26453b&type=album"); bot.OnMessage += async(object sender, Telegram.Bot.Args.MessageEventArgs e) => { try { string message = e.Message.Text; if (message == "/start") { Logger.Input("Hello world"); using (DatabaseContext db = new DatabaseContext()) { List <DSTUSaved> saved = db.Saved.ToList(); saved = saved.OrderBy(p => p.SortId).ToList(); await bot.SendPhotoAsync(e.Message.Chat.Id, photo, "Ректор рекомендует!\nСтуденту от студентов! В 2021 году Студенческий совет разработал для тебя полезного бота! Мы выяснили, что необходимо студенту, чтобы комфортно адаптироваться в университете.Мы рады предложить тебе навигатор, который поможет в первые дни учебы)", false, 0, createKeyboardMenu(saved, false)); } return; } if (message == "Назад") { using (DatabaseContext db = new DatabaseContext()) { List <DSTUSaved> saved = db.Saved.ToList(); saved = saved.OrderBy(p => p.SortId).ToList(); await bot.SendPhotoAsync(e.Message.Chat.Id, photo, "Ректор рекомендует!\nСтуденту от студентов! В 2021 году Студенческий совет разработал для тебя полезного бота! Мы выяснили, что необходимо студенту, чтобы комфортно адаптироваться в университете.Мы рады предложить тебе навигатор, который поможет в первые дни учебы)", false, 0, createKeyboardMenu(saved, false)); } } using (DatabaseContext db = new DatabaseContext()) { List <DSTUSaved> ar = db.Saved.ToList(); ar = ar.OrderBy(p => p.SortId).ToList(); foreach (var item in ar) { if (item.Action == message) { if (item.SubActions == "null") { await bot.SendTextMessageAsync(e.Message.Chat.Id, item.OptionsJson, ParseMode.Default, false, false); } else { await bot.SendTextMessageAsync(e.Message.Chat.Id, item.OptionsJson, ParseMode.Default, false, false, 0, createSubMenu(JsonConvert.DeserializeObject <Dictionary <string, string> >(item.SubActions), true)); } await bot.DeleteMessageAsync(e.Message.Chat.Id, e.Message.MessageId); return; } if (item.SubActions != "null") { Dictionary <string, string> subActions = JsonConvert.DeserializeObject <Dictionary <string, string> >(item.SubActions); if (subActions.ContainsKey(message)) { await bot.SendTextMessageAsync(e.Message.Chat.Id, subActions[message]); await bot.DeleteMessageAsync(e.Message.Chat.Id, e.Message.MessageId); } } } } } catch (Exception ex) { await bot.SendTextMessageAsync(e.Message.Chat.Id, ex.Message); } }; } catch (Exception ex) { Console.WriteLine(ex.Message); } bot.StartReceiving(); while (true) { } }
public void SendPhoto(long chatId, string filename, Stream content) { var file = new FileToSend(filename, content); Try(t => t.SendPhotoAsync(chatId, file)); }
public void SendFile(long chatId, Uri url) { var file = new FileToSend(url); Try(t => t.SendDocumentAsync(chatId, file)); }
public void SendPhoto(long chatId, Uri url) { var file = new FileToSend(url); Try(t => t.SendPhotoAsync(chatId, file)); }
public Cleverbot(Instance db, Setting settings, TelegramBotClient bot) { var me = bot.GetMeAsync().Result; bot.OnUpdate += (sender, args) => { new Task(() => { if (!Enabled) { return; } try { //check to see if it was to me, a reply to me, whatever var message = args.Update.Message; if (message.Date < DateTime.UtcNow.AddSeconds(-10)) { return; } if (message?.Text == null) { return; } var text = message.Text.ToLower(); if (text.StartsWith("!") || text.StartsWith("/")) { return; //ignore commands } if (message.Chat.Type != ChatType.Private && message.Chat.Id != -1001119386963) { return; } if (text.Contains(me.FirstName.ToLower()) || text.Contains(me.Username.ToLower()) || message.ReplyToMessage?.From.Id == me.Id || message.Chat.Type == ChatType.Private) { text = text.Replace(me.FirstName.ToLower(), "Mitsuku").Replace("@", "").Replace(me.Username.ToLower(), "Mitsuku"); var response = Encoding.UTF8.GetString( new WebClient().UploadValues( "https://kakko.pandorabots.com/pandora/talk?botid=f326d0be8e345a13&skin=chat", new NameValueCollection() { { "message", text } })); var matches = Regex.Matches(response, "(Мitsuku:</B>(.*))"); var match = matches[0].Value; match = match.Replace("Мitsuku:", "") .Replace("</B> ", "") .Replace(" .", ".") .Replace("<br>", " ") .Replace("Mitsuku", "Seras") .Replace("Мitsuku", "Seras") .Replace(" < P ALIGN=\"CENTER\">", "") .Replace("</P>", " ") .Trim(); match = match.Replace("<B>", "```").Replace("You:", "").Replace("Μitsuku:", "").Trim(); match = match.Replace("Mousebreaker", "Para"); //[URL]http://www.google.co.uk/search?hl=en&q=dot net&btnI=I%27m+Feeling+Lucky&meta=[/URL] if (match.Contains("[URL]")) { //parse out the url var url = Regex.Match(match, @"(\[URL\].*\[/URL\])").Value; match = "[" + match.Replace(url, "") + "]"; url = url.Replace("[URL]", "").Replace("[/URL]", "").Replace(".co.uk", ".com"); match += $"({url})"; //markdown linking Console.WriteLine(match); bot.SendTextMessageAsync(args.Update.Message.Chat.Id, match, replyToMessageId: message.MessageId, parseMode: ParseMode.Markdown); } //<P ALIGN="CENTER"><img src="http://www.square-bear.co.uk/mitsuku/gallery/donaldtrump.jpg"></img></P> else if (match.Contains("img src=\"")) { var img = Regex.Match(match, "<img src=\"(.*)\"></img>").Value; match = match.Replace(img, "").Replace("<P ALIGN=\"CENTER\">", "").Trim(); ; img = img.Replace("<img src=\"", "").Replace("\"></img>", ""); //download the photo var filename = args.Update.Message.MessageId + ".jpg"; new WebClient().DownloadFile(img, filename); //create the file to send var f2S = new FileToSend(filename, new FileStream(filename, FileMode.Open, FileAccess.Read)); Console.WriteLine(match); bot.SendPhotoAsync(args.Update.Message.Chat.Id, f2S, match); //bot.SendTextMessageAsync(args.Update.Message.Chat.Id, match); } else { Console.WriteLine(match); bot.SendTextMessageAsync(args.Update.Message.Chat.Id, match, replyToMessageId: message.MessageId, parseMode: ParseMode.Markdown); } } } catch { // ignored } }).Start(); }; }