Example #1
0
        public async Task <IEnumerable <long> > SendMessage(long chatId, OutMessage message)
        {
            var result = new List <long>(message.Attachments.Count + 1);

            GroupAttachments(message.Attachments, out var photos, out var videos, out var others);
            var photoMediaGroup = photos.Select(TgConverter.ToTgPhoto);
            var videoMediaGroup = videos.Select(TgConverter.ToTgVideo);

            if (photos.Count > 0)
            {
                result.AddRange((await _api.SendMediaGroupAsync(photoMediaGroup, chatId).ConfigureAwait(false))
                                .Select(a => (long)a.MessageId));
            }
            if (videos.Count > 0)
            {
                result.AddRange((await _api.SendMediaGroupAsync(videoMediaGroup, chatId).ConfigureAwait(false))
                                .Select(a => (long)a.MessageId));
            }

            foreach (var attachment in others)
            {
                switch (attachment.Type)
                {
                case AttachmentType.Audio:
                    var sentAudio = await _api.SendAudioAsync(chatId, TgConverter.ToTgMedia(attachment))
                                    .ConfigureAwait(false);

                    result.Add(sentAudio.MessageId);
                    break;

                case AttachmentType.Voice:
                    var sentVoice = await _api.SendVoiceAsync(chatId, TgConverter.ToTgMedia(attachment))
                                    .ConfigureAwait(false);

                    result.Add(sentVoice.MessageId);
                    break;

                default:
                    var sendDocument = await _api.SendDocumentAsync(chatId, TgConverter.ToTgMedia(attachment))
                                       .ConfigureAwait(false);

                    result.Add(sendDocument.MessageId);
                    break;
                }
            }

            var keyboard = message.Keyboard switch
            {
                InlineKeyboard inlineKeyboard => TgConverter.ToTgKeyboard(inlineKeyboard),
                ReplyKeyboard replyKeyboard => TgConverter.ToTgKeyboard(replyKeyboard),
                _ => message.RemoveReplyKeyboard ? new ReplyKeyboardRemove() : null
            };

            var sentMessage = await _api.SendTextMessageAsync(chatId, message.Text, replyMarkup : keyboard)
                              .ConfigureAwait(false);

            result.Add(sentMessage.MessageId);

            return(result);
        }
Example #2
0
        private Task <Message[]> SendMediaAlbumWithCaption(MessageInfo message, IEnumerable <IAlbumInputMedia> telegramMedia)
        {
            _logger.LogInformation("Sending media album with caption");

            if (telegramMedia.FirstOrDefault() is InputMediaBase b)
            {
                b.Caption   = message.Message;
                b.ParseMode = TelegramConstants.MessageParseMode;
            }

            return(_client.SendMediaGroupAsync(
                       inputMedia: telegramMedia,
                       chatId: message.ChatId,
                       cancellationToken: message.CancellationToken));
        }
Example #3
0
        private async Task <int> SendResponse(long chatId,
                                              ResponseMessage response,
                                              IReadOnlyDictionary <ResponseMessage, int> prevResponseId)
        {
            if (response == null)
            {
                return(0);
            }

            if (response.ReplyToResponseMessage != null)
            {
                prevResponseId.TryGetValue(response.ReplyToResponseMessage, out int id);
                response.ReplyToId = id;
            }

            if (response.Images != null && response.Images.Any())
            {
                var mediaGroup = response.Images.Select(id => new InputMediaPhoto(new InputMedia(id))).ToList();
                if (response.Message != null)
                {
                    mediaGroup[0].Caption = response.Message;
                }

                var sentMessages = await _bot
                                   .SendMediaGroupAsync(mediaGroup, chatId, replyToMessageId : response.ReplyToId)
                                   .ConfigureAwait(false);

                return(sentMessages.LastOrDefault()?.MessageId ?? 0);
            }
            else if (!string.IsNullOrEmpty(response.Message))
            {
                IReplyMarkup replyMarkup = null;

                if (response.ReplyKerboardButtons != null)
                {
                    var buttons = response.ReplyKerboardButtons.Select(row => row.Select(button => new KeyboardButton(button)));
                    replyMarkup = new ReplyKeyboardMarkup(buttons)
                    {
                        OneTimeKeyboard = true
                    };
                }
                else if (response.InlineKeyboardButtons != null)
                {
                    //var buttons = response.InlineKeyboardButtons
                    //    .Select(row => row.Select(button => new InlineKeyboardButton() { Text = button, CallbackData = button }));
                    replyMarkup = new InlineKeyboardMarkup(response.InlineKeyboardButtons);
                }


                var sentMessage = await _bot
                                  .SendTextMessageAsync(chatId, response.Message, replyToMessageId : response.ReplyToId, replyMarkup : replyMarkup)
                                  .ConfigureAwait(false);

                return(sentMessage?.MessageId ?? 0);
            }

            return(0);
        }
Example #4
0
        private void SendImagesPost(IPostModel post)
        {
            if (post.Attachments == null)
            {
                throw new ArgumentException("Images Post: post.attachments = null");
            }

            if (post.Attachments.Length < 2)
            {
                throw new ArgumentException("Images Post: post.attachments.length < 2");
            }

            var temp = bot.SendMediaGroupAsync(
                post.Attachments.Select(x => new InputMediaPhoto(new InputMedia(x))),
                ChannelID);

            temp.Wait();
            Console.WriteLine(temp.Result);
        }
 public Task <Message[]> SendMediaGroupAsync(
     IEnumerable <IAlbumInputMedia> inputMedia,
     bool disableNotification            = default,
     int replyToMessageId                = default,
     CancellationToken cancellationToken = default)
 => botClient
 .SendMediaGroupAsync(inputMedia,
                      userContextProvider.Update.Chat,
                      disableNotification,
                      replyToMessageId,
                      cancellationToken);
Example #6
0
        async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
        {
            // Only process Message updates: https://core.telegram.org/bots/api#message
            if (update.Type != UpdateType.Message)
            {
                return;
            }
            // Only process text messages
            if (update.Message !.Type != MessageType.Text)
            {
                return;
            }

            var chatId      = update.Message.Chat.Id;
            var messageText = update.Message.Text;

            int maxPages = 4;

            if (messageText.StartsWith("/pixiv"))
            {
                try {
                    long id     = Pixiv.Utils.GetWorkID(messageText);
                    var  illust = await PixivDownloader.GetIllustration(id);

                    List <IAlbumInputMedia> items = new List <IAlbumInputMedia>();

                    bool isFirstSent = true;

                    foreach (var imageTask in PixivDownloader.DownloadIllistrationAsync(illust, maxPages: 10, maxBytes: 8388119))
                    {
                        using (var image = await imageTask) {
                            var ms = new MemoryStream();
                            image.ImageData.CopyTo(ms);
                            ms.Position = 0;
                            items.Add(new InputMediaPhoto(new InputMedia(ms, image.Filename))
                            {
                                Caption = isFirstSent? illust.ToString() : null
                            });
                            isFirstSent = false;
                            //image.ImageData.Position = 0;
                        }
                    }

                    await botClient.SendMediaGroupAsync(chatId, items);


                    //foreach (var imageTask in PixivDownloader.DownloadIllistrationAsync(illust, maxPages: 4, maxBytes: 8388119).ToList()) {
                    //  using (var image = await imageTask) {
                    //    string text = isFirstSent ? illust.ToString() : string.Empty;
                    //    if (isFirstSent && maxPages > 0 && illust.PageCount > maxPages) ;
                    //      text += $" [Showing {maxPages} images out of {illust.PageCount}]";
                    //    if (!image.IsOriginal)
                    //      text += " (preview version)";
                    //    text = text.Trim();
                    //    isFirstSent = false;
                    //    Console.WriteLine($"Sending page {image.PageNumber}");
                    //    await botClient.SendPhotoAsync(chatId, new InputOnlineFile(image.ImageData, image.Filename), string.IsNullOrEmpty(text) ? null : text);
                    //  }
                    //}
                    return;
                }
                catch (Exception ex) {
                }
            }

            Console.WriteLine($"Received a '{messageText}' message in chat {chatId}.");

            // Echo received message text
            //Message sentMessage = await botClient.SendTextMessageAsync(
            //    chatId: chatId,
            //    text: "You said:\n" + messageText,
            //    cancellationToken: cancellationToken);
        }