internal override async Task Reply(Message message, TelegramBotClient botClient) { var inlineKeyboarButtons = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton[BloodTestIndicatorsCommand.InlineKeyboardRowsCount][]; for (int i = 0, j = 0, k = 1; i < BloodTestIndicatorsCommand.InlineKeyboardRowsCount; i++, j += BloodTestIndicatorsCommand.InlineKeyboardColumnsCount, k += BloodTestIndicatorsCommand.InlineKeyboardColumnsCount) { // row i inlineKeyboarButtons[i] = new[] { // column 1 Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData(BloodTestIndicatorsCommand.IndicatorsList[j], $"{BloodTestIndicatorsCommand.IndicatorsList[j]}{BloodTestIndicatorsCommand.CallbackData}"), // column 2 Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData(BloodTestIndicatorsCommand.IndicatorsList[k], $"{BloodTestIndicatorsCommand.IndicatorsList[k]}{BloodTestIndicatorsCommand.CallbackData}") }; } var inlineKeyboar = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(inlineKeyboarButtons); var chatId = message.Chat.Id; string newBotMessage = "Выберете интересующий Вас показатель:"; var media = new InputMediaPhoto("https://raw.githubusercontent.com/OnofreichukRoman/MedicalTelegramBot/master/Images/Bloodtestindicators.jpg"); await botClient.EditMessageMediaAsync(chatId, message.MessageId, media, replyMarkup : inlineKeyboar); await botClient.EditMessageCaptionAsync(chatId, message.MessageId, newBotMessage, replyMarkup : inlineKeyboar, parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown); }
public override async Task Execute(Message message, TelegramBotClient botClient, Client person) { InlineKeyboardMarkup inlineKeyboardMarkup = GetImageKeyboard(); List <InputMediaPhoto> album = new List <InputMediaPhoto>(); foreach (var photo in inlineImageGallery.ImageGalleries) { InputMediaPhoto p = new InputMediaPhoto(); p.Media = photo.URLImage; p.Caption = photo.Descriptipon; album.Add(p); } //InputMedia media = new InputMedia(inlineImageGallery.ImageGalleries[0].URLImage, "123"); // InputMediaPhoto photo = new InputMediaPhoto(media); try { var t = await botClient.SendMediaGroupAsync(message.Chat.Id, album); // await botClient.SendPhotoAsync(message.Chat.Id, inlineImageGallery.ImageGalleries[0].URLImage, inlineImageGallery.ImageGalleries[0].Descriptipon, replyMarkup: inlineKeyboardMarkup, parseMode: Telegram.Bot.Types.Enums.ParseMode.Html); // await botClient.EditMessageMediaAsync(callbackQuery.Message.Chat.Id, callbackQuery.Message.MessageId, photo); // await botclient.SendPhotoAsync(callbackQuery.Message.Chat.Id, stream); } catch (Exception ex) { Bot.MyLogger(ex.Message); Bot.MyLogger(ex.StackTrace); } }
public async Task ExecuteQuery(CallbackQuery callbackQuery, TelegramBotClient botClient) { try { string url = "1"; var m = from t in inlineImageGallery.ImageGalleries where t.Descriptipon == callbackQuery.Data.Substring(callbackQuery.Data.IndexOf('z') + 1) select t; url = m.ToList()[0].URLImage; InputMediaPhoto media = new InputMediaPhoto(new InputMedia(url)); media.Caption = m.ToList()[0].Descriptipon; await botClient.EditMessageMediaAsync(callbackQuery.Message.Chat.Id, callbackQuery.Message.MessageId, media, replyMarkup : GetImageKeyboard()); // string s = callbackQuery.Data.Substring(callbackQuery.Data.IndexOf(' ') + 1); // int level = int.Parse(callbackQuery.Data.Remove(callbackQuery.Data.IndexOf(' '))); await botClient.AnswerCallbackQueryAsync(callbackQuery.Id, ""); } catch (Exception ex) { Bot.MyLogger(ex.Message); Bot.MyLogger(ex.StackTrace); } }
/// <summary> /// Assemblies post content into ready to send files /// </summary> /// <param name="template">Template where content stores</param> /// <returns>Message if no any photos added or List<InputMediaBase> if there is 1 or more photos</returns> public static async Task <Object> AssemblyTemplate(TelegramBotClient client, PostTemplate template) { IOrderedEnumerable <PostContent> orderedList = template.PostContent.OrderBy(c => c.Order); Message textMessage = null; List <InputMediaBase> inputMedias = new List <InputMediaBase>(); foreach (PostContent content in orderedList) { Message forward = await client.ForwardMessageAsync(CommandText.bufferChannelId, CommandText.bufferChannelId, content.MessageId); if (forward.Type != Telegram.Bot.Types.Enums.MessageType.Text) { InputMediaPhoto photo = new InputMediaPhoto(new InputMedia(forward.Photo[0].FileId)); inputMedias.Add(photo); } else { textMessage = forward; } } if (inputMedias.Count != 0) { if (textMessage != null && !String.IsNullOrEmpty(textMessage.Text)) { inputMedias[0].Caption = textMessage.Text; } return(inputMedias); } return(textMessage); }
private void GetPhotoList() { //Ищем фотографии для этого бота var photo = db.ProductPhoto.Where(p => p.ProductId == ProductId).OrderByDescending(o => o.AttachmentFsId).Take(10); //Проверяем загружены ли фотографии на сервер телеграм foreach (ProductPhoto pp in photo) { var TelegramAttach = db.AttachmentTelegram.Where(a => a.AttachmentFsId == pp.AttachmentFsId && a.BotInfoId == BotId).LastOrDefault(); //файл уже загружен на сервер. Вытаскиваем FileID if (TelegramAttach != null && TelegramAttach.FileId != null && TelegramAttach.FileId != "") { string Caption = db.AttachmentFs.Find(TelegramAttach.AttachmentFsId).Caption; InputMediaType inputMediaType = new InputMediaType(TelegramAttach.FileId); InputMediaPhoto mediaPhoto = new InputMediaPhoto { Media = inputMediaType, Caption = Caption }; PhotoListMedia.Add(mediaPhoto); //Добавляем в ассоциативный массив данные о том что эта фотография уже загружена на сервер телеграм MediaGroupPhoto.FsIdTelegramFileId.Add(Convert.ToInt32(TelegramAttach.AttachmentFsId), TelegramAttach.FileId); } //Файл еще не загруже на север телеграм else { var AttachFs = db.AttachmentFs.Find(Convert.ToInt32(pp.AttachmentFsId)); MemoryStream ms = new MemoryStream(AttachFs.Fs); InputMediaType inputMediaType = new InputMediaType(AttachFs.Name, ms); InputMediaPhoto mediaPhoto = new InputMediaPhoto { Media = inputMediaType, Caption = AttachFs.Caption }; PhotoListMedia.Add(mediaPhoto); MediaGroupPhoto.FsIdTelegramFileId.Add(Convert.ToInt32(pp.AttachmentFsId), null); } } }
private static async Task PosterWork(Group group) { var bot = _botService.Client; var mainUser = _botService.UserAccess.FirstOrDefault(); // the first user in config will be used for send inforamtion try { while (true) { //delay will be first, coz groups may be have diff interval, so just for stop spaming await Task.Delay(group.Interval * 1000 * 60); //convert to minutes DbManager db = new DbManager(); //for randomly post var postsCount = db.GetCountAvailablePostForGroup(group); if (postsCount == 0) { await bot.SendTextMessageAsync(mainUser, $"All content for {group.GroupId}:{group.Title} was posted !"); return; } var rnd = new Random().Next(postsCount); var post = db.GetContentByNumber(rnd, group.GroupId); if (post != null) { var postList = new List <InputMediaBase>(); foreach (var photoLink in post.PhotoList) { var photo = new InputMediaPhoto(); photo.Media = new InputMedia(photoLink); postList.Add(photo); } await bot.SendMediaGroupAsync(group.GroupId, postList); db.MakePosted(post); } //make post as "posted" } } catch (Exception err) { await bot.SendTextMessageAsync(mainUser, err.Message); } }
private void AlbumHandler(object sender, ElapsedEventArgs e) { lock (locker) { if (MessagesStorage.Count != 0) { List <InputMediaPhoto> temp = new List <InputMediaPhoto>(); foreach (Message mess in MessagesStorage) { InputMediaPhoto inputMediaPhoto = new InputMediaPhoto(new InputMedia(mess.Photo[0].FileId)); temp.Add(inputMediaPhoto); } client.SendMediaGroupAsync(temp, MessagesStorage[0].Chat.Id); MessagesStorage.Clear(); } } }
public static IAlbumInputMedia?ToInputMedia(this Message message) { switch (message.Type) { case MessageType.Photo: var photo = new InputMediaPhoto(message.Photo.GetLargestPhotoSize().FileId); photo.Caption = message.Caption; photo.ParseMode = ParseMode.Html; return(photo); case MessageType.Video: var video = new InputMediaVideo(message.Video.FileId); video.Caption = message.Caption; video.ParseMode = ParseMode.Html; return(video); default: return(null); } }
internal override async Task Reply(Message message, TelegramBotClient botClient) { var inlineKeyboardButtons = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton[][] { // row 1 new [] { // column 1 Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData("<< Назад", "Показатели анализа крови") } }; var inlineKeyboar = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(inlineKeyboardButtons); string newBotMessage = "*Лейкоциты* – клетки крови, которые образуются в костном мозге. Основная их функция – бороться с инфекцией и повреждением тканей. Выделяют пять типов лейкоцитов, которые отличаются по внешнему виду и выполняемым функциям: эозинофилы, базофилы, нейтрофилы, лимфоциты и моноциты. Они присутствуют в организме в относительно стабильных пропорциях и, хотя их численность может значительно изменяться в течение дня, в норме обычно остаются в пределах референсных значений. \nЛейкоциты образуются из стволовых клеток костного мозга и в процессе созревания проходят ряд промежуточных стадий, в ходе которых клетка и содержащееся в ней ядро уменьшаются. В кровоток должны попадать только зрелые лейкоциты.Они живут недолго, так что происходит их постоянное обновление. Производство лейкоцитов в костном мозге возрастает в ответ на любое повреждение тканей, это часть нормального воспалительного ответа. Цель воспалительного ответа – отграничение повреждения, удаление вызвавшего его причинного фактора и восстановление ткани."; var chatId = message.Chat.Id; var media = new InputMediaPhoto("https://raw.githubusercontent.com/OnofreichukRoman/MedicalTelegramBot/master/Images/leukocytes.jpg"); await botClient.EditMessageMediaAsync(chatId, message.MessageId, media, replyMarkup : inlineKeyboar); await botClient.EditMessageCaptionAsync(chatId, message.MessageId, newBotMessage, replyMarkup : inlineKeyboar, parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown); }
internal override async Task Reply(Message message, TelegramBotClient botClient) { var inlineKeyboardButtons = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton[][] { // row 1 new [] { // column 1 Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData("<< Назад", "Показатели анализа крови") } }; var inlineKeyboar = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(inlineKeyboardButtons); string newBotMessage = "*Нейтрофилы* – самая многочисленная разновидность лейкоцитов. Зрелые сегментоядерные нейтрофилы у здорового взрослого человека составляют 47-72% всех лейкоцитов крови; в анализе крови определяются также незрелые палочкоядерные нейтрофилы, доля которых в норме составляет 1-6%. Повышенное содержание нейтрофилов в крови называется нейтрофилией; пониженное – нейтропенией. Нейтрофилы играют огромную роль в защите организма от инфекционных заболеваний, особенно бактериальных и грибковых. Нейтрофилы способны покидать кровяное русло и устремляться к очагу инфекции, принимая активное участие в развитии воспаления. Они также обладают способностью поглощать и разрушать чужеродные частицы – бактерии и грибы. Этот процесс называется фагоцитозом. Повышенная продукция нейтрофилов и их миграция к очагу инфекции часто являются первым ответом организма на инфекционное заболевание."; var chatId = message.Chat.Id; var media = new InputMediaPhoto("https://raw.githubusercontent.com/OnofreichukRoman/MedicalTelegramBot/master/Images/neutrophils.jpg"); await botClient.EditMessageMediaAsync(chatId, message.MessageId, media, replyMarkup : inlineKeyboar); await botClient.EditMessageCaptionAsync(chatId, message.MessageId, newBotMessage, replyMarkup : inlineKeyboar, parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown); }
internal override async Task Reply(Message message, TelegramBotClient botClient) { var inlineKeyboardButtons = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton[][] { // row 1 new [] { // column 1 Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData("<< Назад", "Показатели анализа крови") } }; var inlineKeyboar = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(inlineKeyboardButtons); string newBotMessage = "*Эозинофилы* — один из видов лейкоцитов, клеток иммунной системы, защищающих человеческий организм от паразитов и участвующих в развитии аллергических реакций. \nЭозинофилия крови — это состояние, характеризующееся абсолютным или относительным повышением числа эозинофилов. \nАнализ крови на эозинофилы свидетельствует о наличии различных заболеваний и помогает своевременно начать их лечение."; var chatId = message.Chat.Id; var media = new InputMediaPhoto("https://raw.githubusercontent.com/OnofreichukRoman/MedicalTelegramBot/master/Images/eosinophils.jpg"); await botClient.EditMessageMediaAsync(chatId, message.MessageId, media, replyMarkup : inlineKeyboar); await botClient.EditMessageCaptionAsync(chatId, message.MessageId, newBotMessage, replyMarkup : inlineKeyboar, parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown); }
internal override async Task Reply(Message message, TelegramBotClient botClient) { var inlineKeyboardButtons = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton[][] { // row 1 new [] { // column 1 Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData("<< Назад", "Показатели анализа крови") } }; var inlineKeyboar = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(inlineKeyboardButtons); string newBotMessage = "*Лимфоциты* – это один из видов лейкоцитов, особых клеток, которые циркулируют в крови человека и являются главными клетками иммунной системы. \nРазные виды лимфоцитов способны вырабатывать антитела, уничтожать чужеродные агенты(в первую очередь – вирусы, а также бактерии, грибки и простейшие) и пораженные клетки собственного организма, обуславливать развитие аллергических реакций. В детском возрасте происходит распределение и обучение в органах иммунной системы исходно недифференцированных лимфоцитов, это является основой формирования иммунитета. \nВсе лейкоциты, а значит лимфоциты в том числе, образуются в костном мозге, а затем «дозревают» в других органах в зависимости от назначения.Существуют несколько видов лимфоцитов: Т - клетки, В - клетки и NK-клетки."; var chatId = message.Chat.Id; var media = new InputMediaPhoto("https://raw.githubusercontent.com/OnofreichukRoman/MedicalTelegramBot/master/Images/lymphocytes.jpg"); await botClient.EditMessageMediaAsync(chatId, message.MessageId, media, replyMarkup : inlineKeyboar); await botClient.EditMessageCaptionAsync(chatId, message.MessageId, newBotMessage, replyMarkup : inlineKeyboar, parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown); }
internal override async Task Reply(Message message, TelegramBotClient botClient) { var inlineKeyboardButtons = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton[][] { // row 1 new [] { // column 1 Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData("<< Назад", "Показатели анализа крови") } }; var inlineKeyboar = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(inlineKeyboardButtons); string newBotMessage = "*Базофилы* являются разновидностью лейкоцитов. Они представляют собой самую малую группу и составляют не более 1 % от общей массы лейкоцитов. При обнаружении антигена(аллергена) в базофилах происходит дегрануляция. Другими словами, они выпускают свое содержимое наружу, благодаря чему блокируют аллергены, усиливают кровоток и увеличивают проницаемость сосудов. В результате создается очаг воспаления, к которому устремляются другие гранулоциты(моноциты и эозинофилы) на борьбу с чужеродным элементом. Это и есть главная функция базофилов — вовремя обнаружить и подавить аллергены, не дать им распространиться по всему организму и призвать остальных гранулоцитов к месту воспаления. Кроме своей главной функции базофилы, благодаря наличию гепарина, участвуют в процессах свертываемости крови, препятствуют образованию тромбов в мелких сосудах легких и печени. Также они осуществляют питание тканей, поддерживают нормальный кровоток в малых кровеносных сосудах и рост новых капилляров."; var chatId = message.Chat.Id; var media = new InputMediaPhoto("https://raw.githubusercontent.com/OnofreichukRoman/MedicalTelegramBot/master/Images/basophils.jpg"); await botClient.EditMessageMediaAsync(chatId, message.MessageId, media, replyMarkup : inlineKeyboar); await botClient.EditMessageCaptionAsync(chatId, message.MessageId, newBotMessage, replyMarkup : inlineKeyboar, parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown); }
public MegiaGroupWrapper(ChatId To, List <string> InputMediaIds, string text, int inReplyOf, InlineKeyboardMarkup keyboardMarkup = null) : base(To, "", keyboardMarkup: keyboardMarkup) { this.ChatID = To; this._ChatID = To.Identifier; this.inReplyOf = inReplyOf; this.text = text; int i = 0; foreach (string InputMediaId in InputMediaIds) { InputMediaPhoto inputMediaPhoto = new InputMediaPhoto(new InputMedia(InputMediaId)); if (i == 0) { inputMediaPhoto.Caption = text; inputMediaPhoto.ParseMode = ParseMode.Html; } media.Add(inputMediaPhoto); i++; } }
internal override async Task Reply(Message message, TelegramBotClient botClient) { var inlineKeyboardButtons = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton[][] { // row 1 new [] { // column 1 Telegram.Bot.Types.ReplyMarkups.InlineKeyboardButton.WithCallbackData("<< Назад", "Показатели анализа крови") } }; var inlineKeyboar = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(inlineKeyboardButtons); string newBotMessage = "*Моноциты* – немногочисленные, но по размеру наиболее крупные иммунные клетки организма. \nЭти лейкоциты принимают участие в распознавании чужеродных веществ и обучению других лейкоцитов к их распознаванию.Могут мигрировать из крови в ткани организма.Вне кровеносного русла моноциты изменяют свою форму и преобразуются в макрофаги.Макрофаги могут активно мигрировать к очагу воспаления для того, чтобы принять участие в очищении воспаленной ткани от погибших клеток, лейкоцитов, бактерий. Благодаря такой работе макрофагов создаются все условия для восстановления поврежденных тканей."; var chatId = message.Chat.Id; var media = new InputMediaPhoto("https://raw.githubusercontent.com/OnofreichukRoman/MedicalTelegramBot/master/Images/monocytes.jpg"); await botClient.EditMessageMediaAsync(chatId, message.MessageId, media, replyMarkup : inlineKeyboar); await botClient.EditMessageCaptionAsync(chatId, message.MessageId, newBotMessage, replyMarkup : inlineKeyboar, parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown); }
public override async Task Post(Post post) { try { // @Tor Browser\Browser\TorBrowser\Data\Tor\torrc // +SocksPort 127.0.0.1:9050 var botClient = new TelegramBotClient(_accessToken, new HttpToSocks5Proxy("127.0.0.1", 9050)); var imageStream = System.IO.File.OpenRead(post.PathToImageToAttach); var mediaPhoto = new InputMediaPhoto(); mediaPhoto.Media = new InputMedia(imageStream, "test-file-name"); mediaPhoto.Caption = post.MultilineText + Environment.NewLine + "#" + string.Join(" #", post.Hashtags) + Environment.NewLine; mediaPhoto.ParseMode = Telegram.Bot.Types.Enums.ParseMode.Markdown; var message = await botClient.SendMediaGroupAsync( new[] { mediaPhoto }, _chatId ); } catch (Exception ex) { Console.WriteLine($"telegram> {ex.ToString()}"); } }
public override async Task <Unit> Handle(MoreFusionCallbackAction request, CancellationToken cancellationToken) { var fusionResult = PokemonService.GetFusion(); var photo = new InputMediaPhoto(fusionResult.Image.ToString()); if (string.IsNullOrWhiteSpace(Ctx.GetCallbackQuery().InlineMessageId)) { await Ctx.Client.EditMessageMediaAsync(Ctx.GetTelegramChat(), Ctx.GetCallbackQuery().Message.MessageId, photo, fusionResult.ToInlineQueryResultPhoto().ReplyMarkup, cancellationToken); await Ctx.Client.EditMessageCaptionAsync(Ctx.GetTelegramChat(), Ctx.GetCallbackQuery().Message.MessageId, fusionResult.Name, fusionResult.ToInlineQueryResultPhoto().ReplyMarkup, cancellationToken); } else { await Ctx.Client.EditMessageMediaAsync(Ctx.GetCallbackQuery().InlineMessageId, photo, fusionResult.ToInlineQueryResultPhoto().ReplyMarkup, cancellationToken); await Ctx.Client.EditMessageCaptionAsync(Ctx.GetCallbackQuery().InlineMessageId, fusionResult.Name, fusionResult.ToInlineQueryResultPhoto().ReplyMarkup, cancellationToken); } return(default);
public async Task Execute(IJobExecutionContext context) { BotClient = new TelegramBotClient("1046277477:AAHxIx5MkmYSEH9qIiGYlLMTEUcz5Nage6E"); DataBase db = Singleton.GetInstance().Context; PostTemplate[] postTemplate = db.GetPostTemplates(); foreach (PostTemplate post in postTemplate) { if (post.IsPaid == true) { foreach (PostTime time in post.PostTime) { if (time.Time.Year == System.DateTime.Now.Year && time.Time.Month == System.DateTime.Now.Month && time.Time.Day == System.DateTime.Now.Day && time.Time.Hour == System.DateTime.Now.Hour && time.Time.Minute == System.DateTime.Now.Minute && time.isWorked == false) { foreach (PostChannel channel in post.PostChannel) { try { IOrderedEnumerable <PostContent> orderedList = post.PostContent.OrderBy(c => c.Order); Message textMessage = null; List <InputMediaBase> inputMedias = new List <InputMediaBase>(); foreach (PostContent content in orderedList) { Message forward = await BotClient.ForwardMessageAsync(CommandText.bufferChannelId, CommandText.bufferChannelId, content.MessageId); if (forward.Type != Telegram.Bot.Types.Enums.MessageType.Text) { InputMediaPhoto photo = new InputMediaPhoto(new InputMedia(forward.Photo[0].FileId)); inputMedias.Add(photo); } else { textMessage = forward; } } try { Message[] messages = await BotClient.SendMediaGroupAsync(channel.ChannelId, inputMedias); foreach (Message item in messages) { db.Add <Post>(new Post() { Template = post, ChannelId = item.Chat.Id, MessageId = item.MessageId }); } Message message; message = await BotClient.ForwardMessageAsync(channel.ChannelId, CommandText.bufferChannelId, textMessage.MessageId); if (post.isPinnedMessage == (System.Int32)TypePostTime.PinnedMessage) { await BotClient.PinChatMessageAsync(channel.ChannelId, message.MessageId, disableNotification : false); } else if (post.isPinnedMessage == (System.Int32)TypePostTime.PinnedMessageNotification) { await BotClient.PinChatMessageAsync(channel.ChannelId, message.MessageId, disableNotification : true); } db.Add <Post>(new Post() { Template = post, ChannelId = message.Chat.Id, MessageId = message.MessageId }); } catch (System.Exception ex) { Log.Logging(ex); } time.isWorked = true; db.Save(); } catch (System.Exception ex) { Log.Logging(ex); } } } } } } foreach (PostTemplate post in postTemplate) { System.Boolean result = true; foreach (PostTime time in post.PostTime) { if (time.isWorked == false) { result = false; break; } } if (result) { post.PostTime.Clear(); post.IsPaid = false; post.IsValidated = false; post.IsOnValidation = false; db.Save(); } } }
public override async void Execute(Message message, TelegramBotClient client, ApplicationDbContext context) { string text = string.Empty; string setName = string.Empty; text = message.Text.Replace("/combo ", ""); var queryCards = text.Trim().Split("+"); var msg = string.Empty; var chatId = message.Chat.Id; var ComboList = new List <Card>(); Console.WriteLine("Cards in combo: " + queryCards.ToList().Count); foreach (var comboPiece in queryCards) { var cpName = comboPiece.Trim(); Console.WriteLine("|" + comboPiece + "|" + cpName + "|"); Card card; card = Helpers.CardSearch.GetCardByName(cpName); if (card != null) { Console.WriteLine("Card found"); ComboList.Add(card); } else { Console.WriteLine("Not found"); msg += "❌Карта " + cpName + " была не найдена\r\n"; } } List <IAlbumInputMedia> media = new List <IAlbumInputMedia>(); foreach (var card in ComboList) { //var req = WebRequest.Create("https://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=" + card.multiverseId + "&type=card"); //using (Stream fileStream = req.GetResponse().GetResponseStream()) //{ var imp = new InputMediaPhoto(new InputMedia("https://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=" + card.multiverseId + "&type=card")) { Caption = card.name }; media.Add(imp); // } // req. } foreach (var z in media) { Console.WriteLine(z.Caption); } if (media.Count > 0) { await client.SendMediaGroupAsync(media, chatId); } if (msg.Length > 5) { await client.SendTextMessageAsync(chatId, msg, Telegram.Bot.Types.Enums.ParseMode.Html, replyToMessageId : message.MessageId); } }
private static async Task SendAlbumAsync(List <PostBase> album) { var mediaList = new List <InputMediaBase>(); List <InlineKeyboardButton[]> allButtons = new List <InlineKeyboardButton[]>(); List <InlineKeyboardButton> row = new List <InlineKeyboardButton>(); string links = ""; foreach (var postInAlbum in album) { string fileUrl = ""; if (postInAlbum.GetOriginalSize() > 5000000) { if (postInAlbum.GetSampleSize() < 5000000) { fileUrl = postInAlbum.GetSampleUrl(); } } else { fileUrl = postInAlbum.GetFileUrl(); } if (fileUrl.Equals("") || fileUrl.Contains(".gif") || fileUrl.Contains(".webm")) { continue; } var media = new InputMediaPhoto { Media = new InputMedia(fileUrl), Caption = postInAlbum.GetTags(10) }; mediaList.Add(media); links = string.Concat(links, $"\n<a href=\"{postInAlbum.GetPostLink()}\">Post {mediaList.Count}</a>"); row.Add(InlineKeyboardButton.WithUrl($"Post {mediaList.Count}", postInAlbum.GetPostLink())); if (row.Count == 2) { allButtons.Add(row.ToArray()); row = new List <InlineKeyboardButton>(); } } if (row.Count > 0) { allButtons.Add(row.ToArray()); } var keyboard = new InlineKeyboardMarkup(allButtons); try { await Bot.SendMediaGroupAsync(ChatId, mediaList, disableNotification : true); await Bot.SendTextMessageAsync(ChatId, "🔗Links", replyMarkup : keyboard, disableNotification : true); } catch (Exception e) { LogWrite($"(!) {DateTime.UtcNow}: {e.Source}:::{e.Message}", ConsoleColor.Red); foreach (var media in mediaList) { LogWrite($"(!) {DateTime.UtcNow}:{media.Media.Url}", ConsoleColor.Red); } } }
public override async void Execute(Message message, TelegramBotClient client, ApplicationDbContext context) { var chatId = message.Chat.Id; await client.SendChatActionAsync(chatId, Telegram.Bot.Types.Enums.ChatAction.UploadPhoto); string text = string.Empty; string setName = string.Empty; var originalMessage = message.Text.Substring(message.Text.IndexOf("/c ")); if (originalMessage.Contains("(") && originalMessage.Contains(")")) { var match = Regex.Match(originalMessage, @"/c (.*)\((.*)\)"); text = match.Groups[1].Value; setName = match.Groups[2].Value; } else { text = originalMessage.Replace("/c ", ""); } var msg = string.Empty; Card card; if (setName != string.Empty) { card = Helpers.CardSearch.GetCardByName(text.Trim(), setName); } else { card = Helpers.CardSearch.GetCardByName(text.Trim()); } string nameEn = string.Empty; string nameRu = string.Empty; string price = string.Empty; if (card != null) { nameEn += "<b>🇺🇸 " + card.name + "</b>"; if (card.foreignData.Any(c => c.language.Equals("Russian"))) { nameRu += "<b>🇷🇺 " + card.ruName + "</b>"; } try { var prices = CardData.GetTcgPlayerPrices(card.tcgplayerProductId); if (prices["normal"] > 0) { price += "Цена: <b>$" + prices["normal"].ToString() + "</b>\r\n"; } if (prices["foil"] > 0) { price += "Цена фойлы: <b>$" + prices["foil"].ToString() + "</b>\r\n"; } if (prices["normal"] == 0 && prices["foil"] == 0) { price += "Цена: <i>Нет данных о цене</i>\r\n"; } } catch { } } else { msg = "<b>❌Карта не найдена по запросу \"" + text + "\".</b>"; } if (card != null) { if (card.names != null && card.names.Count > 0) { nameEn = "<b>🇺🇸</b>"; nameRu = "<b>🇷🇺</b>"; var ComboList = new List <Card>(); foreach (var comboPiece in card.names) { var cpName = comboPiece.Trim(); Card secondCard; secondCard = Helpers.CardSearch.GetCardByName(cpName, true); nameEn += "|<b>" + comboPiece + "</b>"; if (secondCard.foreignData.Any(c => c.language.Equals("Russian"))) { nameRu += "|<b>" + secondCard.ruName + "</b>"; } if (secondCard != null) { Console.WriteLine("Card found"); ComboList.Add(secondCard); } else { Console.WriteLine("Not found"); msg += "❌Карта " + cpName + " была не найдена\r\n"; } } List <IAlbumInputMedia> media = new List <IAlbumInputMedia>(); var firstCardMuId = 0; foreach (var foundCard in ComboList) { if (firstCardMuId != foundCard.multiverseId) { firstCardMuId = foundCard.multiverseId; var imp = new InputMediaPhoto(new InputMedia("https://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=" + foundCard.multiverseId + "&type=card")) { //Caption = foundCard.name }; media.Add(imp); } } foreach (var z in media) { Console.WriteLine(z.Caption); } int index = nameRu.IndexOf("|"); nameRu = (index < 0) ? nameRu : nameRu.Remove(index, 1); index = nameEn.IndexOf("|"); nameEn = (index < 0) ? nameEn : nameEn.Remove(index, 1); if (nameRu.Equals("<b>🇷🇺</b>")) { msg = nameEn + "\r\n" + price; } else { msg = nameEn + "\r\n" + nameRu + "\r\n" + price; } if (media.Count > 0) { await client.SendMediaGroupAsync(media, chatId); await client.SendTextMessageAsync(chatId, msg, Telegram.Bot.Types.Enums.ParseMode.Html); } } else { msg += nameEn + "\r\n" + nameRu + (nameRu.Length > 0 ? "\r\n" : "") + price; WebRequest req; if (card.multiverseId > 0) { req = WebRequest.Create("https://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=" + card.multiverseId + "&type=card"); } else { try { req = WebRequest.Create(CardData.GetTcgPlayerImage(card.tcgplayerProductId)); } catch { req = null; } } if (req != null) { using (Stream fileStream = req.GetResponse().GetResponseStream()) { await client.SendPhotoAsync(chatId, new InputOnlineFile(fileStream), msg, Telegram.Bot.Types.Enums.ParseMode.Html); } } else { await client.SendTextMessageAsync(chatId, msg, Telegram.Bot.Types.Enums.ParseMode.Html); } } } else { //msg = nameEn + "\r\n" + nameRu + "\r\n" + price; await client.SendTextMessageAsync(chatId, msg, Telegram.Bot.Types.Enums.ParseMode.Html, replyToMessageId : message.MessageId); } }
private void updateImage(long id, int messageId, bool imageModeSwitch = false) { var m = new InputMediaPhoto(new InputMedia(getImageStream(id, imageModeSwitch), "RenderedImage")); bot.EditMessageMediaAsync(id, messageId, m, replyMarkup: getNavigationKeyboard()).Wait(); }
private static async Task MatchDetailsCommand(IBotService botService, Message message, IOpenDotaService dotaService) { var client = botService.Client; var messageParts = message.Text.Split(' '); if (messageParts.Length >= 2) { var matchIdString = messageParts[2]; uint matchId; var parsed = uint.TryParse(matchIdString, out matchId); if (parsed) { var match = await dotaService.Client.GetMatchDetails(matchId); if (match != null) { var report = dotaService.Client.DrawMatchReport(match).ToArray(); var radiantReports = new List <InputMediaPhoto>(); var direReports = new List <InputMediaPhoto>(); for (var i = 0; i < report.Length; i++) { var picture = report[i]; string pictureName; if (i == 0) { using (var pictureStream = new MemoryStream(picture)) { await client.SendPhotoAsync ( message.Chat.Id, new InputOnlineFile(pictureStream, "MatchReport.png"), disableNotification : true, caption : "MatchReport", replyToMessageId : message.MessageId ); } } else if (i < 6) { pictureName = $"{((i - 1) / 5 == 0 ? "Radiant" : "Dire")} {(i - 1) % 5 + 1}"; var media = new InputMediaPhoto(); var pictureStream = new MemoryStream(picture); media.Media = new InputMedia(pictureStream, $"{pictureName}.png"); media.Caption = pictureName; radiantReports.Add(media); } else { pictureName = $"{((i - 1) / 5 == 0 ? "Radiant" : "Dire")} {(i - 1) % 5 + 1}"; var media = new InputMediaPhoto(); var pictureStream = new MemoryStream(picture); media.Media = new InputMedia(pictureStream, $"{pictureName}.png"); media.Caption = pictureName; direReports.Add(media); } } await client.SendMediaGroupAsync ( message.Chat.Id, radiantReports, disableNotification : true, replyToMessageId : message.MessageId ); await client.SendMediaGroupAsync ( message.Chat.Id, direReports, disableNotification : true, replyToMessageId : message.MessageId ); foreach (var playerReport in radiantReports) { playerReport.Media.Content.Dispose(); } foreach (var playerReport in direReports) { playerReport.Media.Content.Dispose(); } } else { await client.SendTextMessageAsync ( message.Chat.Id, "owpen dowta is down >w<!", replyToMessageId : message.MessageId ); } } else { await client.SendTextMessageAsync ( message.Chat.Id, "bwad match id >w<!", replyToMessageId : message.MessageId ); } } else { await client.SendTextMessageAsync ( message.Chat.Id, "pweese giw a walid command UwU!", replyToMessageId : message.MessageId ); } }
internal static void OnText(EventArgs args) { if (args is MessageEventArgs) { Message msg = (args as MessageEventArgs).msg; if (msg.text.ToLower().StartsWith("/ping")) { Methods.sendMessage(msg.chat.id, "pong"); } else if (msg.text.ToLower().StartsWith("/showalbum") || msg.text.ToLower().Contains("imgur.com/gallery")) { MatchCollection mc = Regex.Matches(msg.text, "(imgur\\.com\\/gallery.*?)(?>\\s|$)"); if (mc.Count == 0) { Methods.sendMessage(msg.chat.id, "no gallery link"); return; } foreach (Match m in mc) { MatchCollection m2 = Regex.Matches(m.Value, "(?>gallery\\/)(.*?)$"); if (m2.Count == 0) { Methods.sendMessage(msg.chat.id, "no gallery hash"); return; } string uriMethod = "https://api.imgur.com/3/album/" + m2[0].Value.Split('/')[1] + "/images"; var client = new HttpClient(); client.DefaultRequestHeaders.Add("Authorization", "Client-ID " + "b265968728f82eb"); var response = Task.Run(() => client.GetAsync(uriMethod)).Result; client.Dispose(); Console.WriteLine("Got Response from API"); Stream stream = Task.Run(() => response.Content.ReadAsStreamAsync()).Result; DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(ImgurResult <Image[]>)); try { ImgurResult <Image[]> result = (dcjs.ReadObject(stream)) as ImgurResult <Image[]>; if (result.success) { Methods.sendMessage(msg.chat.id, "SUCCESS: found " + result.data.Length + "images! Give me a moment to send them all!"); Methods.sendChatAction(msg.chat.id, "typing"); Console.WriteLine("SUCCESS: found " + result.data.Length + "images"); int count = result.data.Length; int pos = 0; while (count > 0) { int subcount = 0; List <InputMedia> media = new List <InputMedia>(); List <InputMedia> gifMedia = new List <InputMedia>(); List <InputMedia> videoMedia = new List <InputMedia>(); for (int i = 0; i < Math.Min(count, 10); i++) { InputMedia curMedia; if (result.data[i + pos].link.EndsWith("mp4")) // should be video { curMedia = new InputMediaVideo() { type = "video", media = result.data[i + pos].link, height = result.data[i + pos].height, width = result.data[i + pos].width }; videoMedia.Add(curMedia); subcount++; break; } if (result.data[i + pos].link.EndsWith("gif")) // should be video { curMedia = new InputMediaAnimation() { type = "animation", media = result.data[i + pos].link, height = result.data[i + pos].height, width = result.data[i + pos].width }; gifMedia.Add(curMedia); subcount++; break; } else //should be image? { curMedia = new InputMediaPhoto() { type = "photo", media = result.data[i + pos].link }; media.Add(curMedia); subcount++; } } if (media.Count() > 0) { Methods.sendChatAction(msg.chat.id, "upload_photo"); Methods.sendMediaGroup(msg.chat.id, media.ToArray()); } if (gifMedia.Count() > 0) { foreach (var gif in gifMedia) { Methods.sendChatAction(msg.chat.id, "upload_video"); Methods.sendAnimation(msg.chat.id, gif.media, ""); } } if (videoMedia.Count() > 0) { foreach (var vid in videoMedia) { Methods.sendChatAction(msg.chat.id, "upload_video"); Methods.sendAnimation(msg.chat.id, vid.media, ""); } } pos += subcount; count -= subcount; } } } catch (Exception e) { Console.WriteLine(e.Message); Methods.sendMessage(msg.chat.id, "Not an album"); } } } } }
public override async Task SendMessage(Conversation conversation, Message message) { Logger.LogTrace("Send message to conversation {0}", conversation.OriginId); var chat = new ChatId(Convert.ToInt64(conversation.OriginId)); #region Get forwarded and attachments var fwd = FlattenForwardedMessages(message); var attachments = GetAllAttachments(message, fwd); #endregion #region Send message var sender = ""; if (message.OriginSender != null) { sender = FormatSender(message.OriginSender) + "\n"; } var body = FormatMessageBody(message, fwd); if (body.Length > 0) { await BotClient.SendTextMessageAsync(new ChatId(conversation.OriginId), $"{sender}{body}", ParseMode.Html, true); } #endregion #region Send attachments if (attachments.Any()) { Logger.LogTrace("Sending message with attachments"); var groupableAttachments = attachments.OfType <ITgGroupableAttachment>(); Func <ITgGroupableAttachment, IAlbumInputMedia> AlbumAttachmentSelector() { return(media => { switch (media) { case PhotoAttachment albumPhoto: { if (albumPhoto.Meta is PhotoSize photo) { return new InputMediaPhoto(new InputMedia(photo.FileId)); } var tgPhoto = new InputMediaPhoto(new InputMedia(albumPhoto.Url)) { Caption = message?.OriginSender?.DisplayName != null ? $"[{message.OriginSender.DisplayName}] {albumPhoto.Caption ?? ""}" : albumPhoto.Caption }; return tgPhoto; } case VideoAttachment albumVideo: { if (albumVideo.Meta is Video video) { return new InputMediaPhoto(new InputMedia(video.FileId)); } var tgVideo = new InputMediaVideo(albumVideo.Url) { Caption = message?.OriginSender?.DisplayName != null ? $"[{message.OriginSender.DisplayName}] {albumVideo.Caption ?? ""}" : albumVideo.Caption, Duration = (int)(albumVideo.Duration ?? 0), Width = albumVideo.Width, Height = albumVideo.Height }; return tgVideo; } default: return null; } }); } var chunks = groupableAttachments .Select((val, i) => (val, i)) .GroupBy(tuple => tuple.i / 10); foreach (var chunk in chunks) { await BotClient.SendMediaGroupAsync( chunk.Select(x => x.val).Select(AlbumAttachmentSelector()), chat); } var restAttachments = attachments.Where(at => !(at is ITgGroupableAttachment)); foreach (var at in restAttachments) { if (at is AnimationAttachment animation) { await BotClient.SendAnimationAsync(chat, _getInputFile(message, animation), (int)(animation.Duration ?? 0), animation.Width, animation.Height, caption : animation.Caption); } else if (at is VoiceAttachment voice) { var req = (HttpWebRequest)WebRequest.Create(voice.Url); req.Timeout = 15000; var resp = (HttpWebResponse)req.GetResponse(); await BotClient.SendVoiceAsync(chat, new InputOnlineFile(resp.GetResponseStream(), voice.FileName), voice.Caption); } else if (at is AudioAttachment audio) { await BotClient.SendAudioAsync(chat, _getInputFile(message, audio), audio.Caption, duration : (int)(audio.Duration ?? 0), performer : audio.Performer, title : audio.Title); } else if (at is ContactAttachment contact) { await BotClient.SendContactAsync(chat, contact.Phone, contact.FirstName, contact.LastName, vCard : contact.VCard); } else if (at is LinkAttachment link) { await BotClient.SendTextMessageAsync(chat, $"{sender}{link.Url}", ParseMode.Html); } else if (at is StickerAttachment sticker) { var inputFile = _getInputFile(message, sticker); if (sticker.MimeType == "image/webp") { await BotClient.SendStickerAsync(chat, inputFile); } else { Logger.LogTrace("Converting sticker to webp format"); var req = (HttpWebRequest)WebRequest.Create(inputFile.Url); req.Timeout = 15000; var resp = (HttpWebResponse)req.GetResponse(); var image = SKImage.FromBitmap(SKBitmap.Decode(resp.GetResponseStream())); using (var p = image.Encode(SKEncodedImageFormat.Webp, 100)) { await BotClient.SendStickerAsync(chat, new InputMedia(p.AsStream(), "sticker.webp")); } } } else if (at is PlaceAttachment place) { if (place.Name != null && place.Address != null) { await BotClient.SendVenueAsync(chat, (float)place.Latitude, (float)place.Longitude, place.Name, place.Address); } else { await BotClient.SendLocationAsync(chat, (float)place.Latitude, (float)place.Longitude); } } else if (at is FileAttachment file) { if (file.MimeType == "image/gif" || file.MimeType == "application/pdf" || file.MimeType == "application/zip") { await BotClient.SendDocumentAsync(chat, _getInputFile(message, file), file.Caption); } else { var req = (HttpWebRequest)WebRequest.Create(file.Url); req.Timeout = 15000; var resp = (HttpWebResponse)req.GetResponse(); await BotClient.SendDocumentAsync(chat, new InputOnlineFile(resp.GetResponseStream(), file.FileName), file.Caption); } } } } #endregion }
public async void SendMessage(TelegramBotClient botClient) { //botClient.EditMessage(_message.From.Id, user.MessageID, "Реклама", "18 - ConfirmMyTransaction", user, InlineBatton.GetTemplateMenu(adUser)); //botClient.SendText(transaction.UserSenderId, $"Транзакция была подтверждена {user.FIO}"); if (postTemplate.PostContent.Count != 0) { IOrderedEnumerable <PostContent> orderedList = postTemplate.PostContent.OrderBy(c => c.Order); Message textMessage = null; List <InputMediaBase> inputMedias = new List <InputMediaBase>(); foreach (PostContent content in orderedList) { Message forward = await botClient.ForwardMessageAsync(CommandText.bufferChannelId, CommandText.bufferChannelId, content.MessageId); if (forward.Type != Telegram.Bot.Types.Enums.MessageType.Text) { InputMediaPhoto photo = new InputMediaPhoto(new InputMedia(forward.Photo[0].FileId)); inputMedias.Add(photo); } else { textMessage = forward; } } try { await botClient.SendMediaGroupAsync(_message.From.Id, inputMedias); } catch { } try { await botClient.ForwardMessageAsync(_message.From.Id, CommandText.bufferChannelId, textMessage.MessageId); } catch { } if (postTemplate.IsOnValidation == false && postTemplate.IsValidated == false) { botClient.DeleteMessage(_message.From.Id, user.MessageID, "275"); botClient.SendText(_message.From.Id, $"Управление шаблоном\n1. Заполните контент\n2. Введите время постинга.\n3. Выберете чат(ы)\n4. Отправите на проверку администрации.", user, replyMarkup: Advertising.InlineButton.GetTemplateMenu(adUser)); } else if (postTemplate.IsValidated == true && postTemplate.IsPaid == false) { botClient.DeleteMessage(_message.From.Id, user.MessageID, "275"); botClient.SendText(_message.From.Id, $"<b>Название поста: {textMessage.Text}</b>\n\nДанный пост одобрен администрацией, вы моежете его оплатить после чего он пойдет в работу!", user, replyMarkup: Advertising.InlineButton.GetTemplateMenu(adUser)); } else if (postTemplate.IsValidated == true && postTemplate.IsPaid == true) { botClient.DeleteMessage(_message.From.Id, user.MessageID, "275"); botClient.SendText(_message.From.Id, $"<b>Название поста: {textMessage.Text}</b>\n\nДанный пост находится в работе!", user, replyMarkup: Advertising.InlineButton.GetTemplateMenu(adUser)); } else { botClient.DeleteMessage(_message.From.Id, user.MessageID, "275"); botClient.SendText(_message.From.Id, $"<b>Название поста: {textMessage.Text}</b>\n\nДанный пост находится в работе!", user, replyMarkup: Advertising.InlineButton.GetTemplateMenu(adUser)); } } else { if (postTemplate.IsPaid == false) { botClient.EditMessage(_message.From.Id, _message.Message.MessageId, "Управление шаблоном\n1. Заполните контент\n2. Введите время постинга.\n3. Выберете чат(ы)\n4. Отправите на проверку администрации.", "276", user, replyMarkup: Advertising.InlineButton.GetTemplateMenu(adUser)); } else { botClient.EditMessage(_message.From.Id, _message.Message.MessageId, "Данный пост находится в работе!", "280", user, replyMarkup: Advertising.InlineButton.GetTemplateMenu(adUser)); } } }
public override async Task HandleAsync(IUpdateContext context, UpdateDelegate next, string[] args, CancellationToken cancellationToken) { _telegramService = new TelegramService(context); var client = _telegramService.Client; var message = _telegramService.Message; var partsText = message.Text.SplitText(" ").ToArray(); var chatId = message.Chat.Id; var listAlbum = new List <IAlbumInputMedia>(); var catSource = "http://aws.random.cat/meow"; var catNum = 1; var param1 = partsText.ValueOfIndex(1); if (param1.IsNotNullOrEmpty()) { if (!param1.IsNumeric()) { await _telegramService.SendTextAsync("Pastikan jumlah kochenk yang diminta berupa angka.") .ConfigureAwait(false); return; } catNum = param1.ToInt(); if (catNum > 10) { await _telegramService.SendTextAsync("Batas maksimal Kochenk yg di minta adalah 10") .ConfigureAwait(false); return; } } await _telegramService.SendTextAsync($"Sedang mempersiapkan {catNum} Kochenk") .ConfigureAwait(false); for (int i = 1; i <= catNum; i++) { Log.Information($"Loading cat {i} of {catNum} from {catSource}"); // await _telegramService.EditAsync($"Sedang mengambil {i} of {catNum} Kochenk") // .ConfigureAwait(false); var url = await catSource .GetJsonAsync <CatMeow>(cancellationToken) .ConfigureAwait(false); var urlFile = url.File.AbsoluteUri; Log.Information($"Adding kochenk {urlFile}"); var fileName = Path.GetFileName(urlFile); var timeStamp = DateTime.UtcNow.ToString("yyyy-MM-dd"); var saveName = Path.Combine(chatId.ToString(), $"kochenk_{timeStamp}_" + fileName); var savedPath = urlFile.SaveToCache(saveName); var fileStream = File.OpenRead(savedPath); // listAlbum.Add(new InputMediaPhoto() // { // Caption = $"Kochenk {i}", // Media = new InputMedia(fileStream, fileName), // ParseMode = ParseMode.Html // }); var inputMediaPhoto = new InputMediaPhoto(new InputMedia(fileStream, fileName)) { Caption = $"Kochenk {i}", ParseMode = ParseMode.Html }; listAlbum.Add(inputMediaPhoto); // listAlbum.Add(new InputMediaPhoto(new InputMedia())); await fileStream.DisposeAsync().ConfigureAwait(false); Thread.Sleep(100); } await _telegramService.DeleteAsync().ConfigureAwait(false); await client.SendMediaGroupAsync(listAlbum, chatId, cancellationToken : cancellationToken) .ConfigureAwait(false); }