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); } }
private async ValueTask <IAlbumInputMedia> ToAlbumInputMediaAsync(MessageInfo message, IMedia media) { InputMedia inputMedia = await GetInputMediaAsync(message, media); switch (media) { case Video v: var video = new InputMediaVideo(inputMedia) { SupportsStreaming = true }; if (v.ThumbnailUrl != null) { video.Thumb = new InputMedia( await _httpClient.GetStreamAsync(v.ThumbnailUrl, message.CancellationToken), "Thumbnail"); } if (v.Duration?.Seconds != null) { video.Duration = (int)v.Duration?.Seconds; } if (v.Width != null) { video.Width = (int)v.Width; } if (v.Height != null) { video.Height = (int)v.Height; } return(video); default: return(new InputMediaPhoto(inputMedia)); } }
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 }
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"); } } } } }