Beispiel #1
0
        private async Task HandleResponse(CommandResult commandResult, long chat, CancellationToken cancellationToken)
        {
            switch (commandResult.Type)
            {
            case MessageType.Photo:
                if (commandResult.AdditionalData is string)
                {
                    await _client.SendPhotoAsync(chat, new InputOnlineFile((string)commandResult.AdditionalData),
                                                 commandResult.Text.ToString(), ParseMode.Html,
                                                 replyMarkup : new InlineKeyboardMarkup(commandResult.Buttons.SplitList()),
                                                 cancellationToken : cancellationToken);
                }
                else if (commandResult.AdditionalData is Stream)
                {
                    await _client.SendPhotoAsync(chat, new InputOnlineFile((Stream)commandResult.AdditionalData),
                                                 commandResult.Text.ToString(), ParseMode.Html,
                                                 replyMarkup : new InlineKeyboardMarkup(commandResult.Buttons.SplitList()),
                                                 cancellationToken : cancellationToken);
                }

                break;

            case MessageType.Text:
            default:
                await _client.SendTextMessageAsync(chat, commandResult.Text.ToString(),
                                                   replyMarkup : new InlineKeyboardMarkup(commandResult.Buttons.SplitList()),
                                                   parseMode : ParseMode.Html, cancellationToken : cancellationToken);

                break;
            }
        }
Beispiel #2
0
 public async void PostPhoto(Message message)
 {
     if (message != null)
     {
         await _botClient.SendPhotoAsync(
             chatId : ChatId,
             photo : "https://github.com/TelegramBots/book/raw/master/src/docs/photo-ara.jpg",
             caption : message.Text,
             parseMode : ParseMode.Html
             );
     }
 }
Beispiel #3
0
        /// <summary>
        /// Ответ на запрос изображения с камеры входа
        /// </summary>
        /// <param name="callbackQuery"></param>
        /// <returns></returns>
        private async Task ReplyEntranceCam(CallbackQuery callbackQuery)
        {
            //ответ на кнопку
            await _botClient.AnswerCallbackQueryAsync(
                callbackQuery.Id, cancellationToken : Token);

            // Показываем статус отправки фото
            await _botClient.SendChatActionAsync(callbackQuery.Message.Chat.Id, ChatAction.UploadPhoto, Token);

            string filePath = string.Empty;

            //отправка фото
            try
            {
                filePath = _camService.GetEntranceCam(out var fileName);
                await using FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);

                //удаление клавиатуры у предыдущего сообщения
                await RemoveKeyboardFromPrevious(callbackQuery);

                await _botClient.SendPhotoAsync(
                    chatId : callbackQuery.Message.Chat.Id,
                    photo : new InputOnlineFile(fileStream, fileName),
                    replyMarkup : _camerasKeyboard, cancellationToken : Token);
            }
            catch (Exception ex)
            {
                _logger.Error($"Ошибка получения изображения с камеры въезда - {ex.Message}");
                //удаление клавиатуры у предыдущего сообщения
                await RemoveKeyboardFromPrevious(callbackQuery);

                await _botClient.SendTextMessageAsync(
                    chatId : callbackQuery.Message.Chat.Id,
                    text : "Невозможно получить изображение с камеры въезда",
                    replyMarkup : _camerasKeyboard, cancellationToken : Token);
            }

            _logger.Info(string.IsNullOrEmpty(callbackQuery.From.FirstName)
                ? $"Запрос изображения с камеры въезда"
                : $"Запрос изображения с камеры въезда от {callbackQuery.From.FirstName}");
            try
            {
                File.Delete(filePath);
            }
            catch (Exception ex)
            {
                _logger.Warn($"Не удалось удалить изображение с камеры из временной директории - {ex.Message}");
            }
        }
Beispiel #4
0
        public static async Task <Message?> SendPhotoAsync(this ITelegramBotClient bot, TelegramChatStatusDesc desc, string?caption, InputOnlineFile file, IReplyMarkup replyMarkup = null, CancellationToken ct = default(CancellationToken))
        {
            if (bot == null)
            {
                return(null);
            }
            if (desc == null)
            {
                return(null);
            }
            int editMessageId = desc.LastMessageId;


            if (desc.DeleteMessage)
            {
                if (await bot.DeleteMessageIdAsync(desc, editMessageId))
                {
                    desc.AnswerToMessageId = 0;
                }
            }
            try
            {
                var photo = await bot.SendPhotoAsync(desc.ChatId, file, caption, ParseMode.Html, replyMarkup : replyMarkup);

                desc.LastMessageId = photo.MessageId;
                desc.DeleteMessage = true; //next time this message must be deleted, because updating the caption of a photo with somme random content doesn't make much sense
                return(photo);
            }
            catch (Exception e)
            {
                desc.DeleteMessage = false;
                log.Debug($"Bot: {bot.BotId}, To: {desc.ChatId} - Error SendPhotoAsync", e);
                return(null);
            }
        }
Beispiel #5
0
        public async Task CommandFursuitBadge()
        {
            Func <Task> c1    = null;
            var         title = "Fursuit Badge";

            c1 = () => AskAsync($"*{title} - Step 1 of 1*\nType in the fursuit badge number.",
                                async input =>
            {
                await ClearLastAskResponseOptions();

                int badgeNo = 0;
                if (!int.TryParse(input, out badgeNo))
                {
                    await ReplyAsync("That's not a valid number.");
                    await c1();
                    return;
                }

                var badge =
                    await _fursuitBadgeRepository.FindOneAsync(a => a.ExternalReference == badgeNo.ToString());

                if (badge == null)
                {
                    await ReplyAsync($"*{title} - Result*\nNo badge found with it *{badgeNo}*.");
                    return;
                }

                await ReplyAsync(
                    $"*{title} - Result*\nNo: *{badgeNo}*\nOwner: *{badge.OwnerUid}*\nName: *{badge.Name.RemoveMarkdown()}*\nSpecies: *{badge.Species.RemoveMarkdown()}*\nGender: *{badge.Gender.RemoveMarkdown()}*\nWorn By: *{badge.WornBy.RemoveMarkdown()}*\n\nLast Change (UTC): {badge.LastChangeDateTimeUtc}");
                await BotClient.SendPhotoAsync(ChatId, new FileToSend(new Uri($@"https://app.eurofurence.org/api/v2/Fursuits/Badges/{badge.Id}/Image")));
            }, "Cancel=/cancel");
            await c1();
        }
        static async void Bot_OnMessage(object sender, MessageEventArgs e)
        {
            Random rand = new Random(DateTime.Now.Millisecond);

            if (e.Message.Text != null)
            {
                userQuery = e.Message.Text;

                string        html = GetHtmlCode();
                List <string> urls = GetUrls(html);
                currentUrl = urls[rand.Next(0, urls.Count - 1)];

                try
                {
                    await botClient.SendPhotoAsync(
                        chatId : e.Message.Chat,
                        caption : $"<b>{userQuery}</b>",
                        photo : currentUrl,
                        parseMode : ParseMode.Html);
                }
                catch (Exception)
                {
                    await botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : "OMG, thi's unbelivable i can't find a picture! \n " +
                        "Only text & emoji are correct. Don't remember check your connection :D");
                }
            }
        }
Beispiel #7
0
        static async void Bot_OnMessage(object sender, MessageEventArgs e)
        {
            Console.WriteLine($"Message from {e.Message.Chat.Id} : {e.Message.Text}");
            var answer = "";

            if (e.Message.Text != null)
            {
                answer = Commander.GetAnswer(e.Message.Text, e.Message.Chat.Id);
                await telegramBot.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text : answer
                    );
            }
            else
            {
                if (e.Message.Sticker != null)
                {
                    answer = ".!.";
                    await telegramBot.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : answer
                        );
                }
                else
                {
                    await telegramBot.SendPhotoAsync(
                        chatId : e.Message.Chat,
                        photo : "http://portal.tpu.ru/foto/21377.jpg"
                        );
                }
            }
        }
        private void SendImagePost(IPostModel post)
        {
            if (post.Attachments == null)
            {
                throw new ArgumentException("Images Post: post.attachments = null");
            }

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

            if (post.Attachments[0] == null)
            {
                throw new ArgumentException("Images Post: post.attachments[0] = null");
            }

            var temp = bot.SendPhotoAsync(
                ChannelID,
                new InputMedia(post.Attachments[0]),
                post.Text,
                ParseMode.Markdown);

            temp.Wait();
            Console.WriteLine(temp.Result);
        }
Beispiel #9
0
        public static void CallbackQuery(CallbackQueryEventArgs e, ITelegramBotClient bot)
        {
            string message = e.CallbackQuery.Data;
            var    chatId  = e.CallbackQuery.From.Id;

            int id = 0;

            int.TryParse(message.Substring(6), out id);

            AdminBot.adminLog(message);

            Participant participant;

            using (MobileContext db = new MobileContext())
            {
                try
                {
                    var booking      = db.Bookings.Single(c => c.Id == id);
                    var bookingsWeek = db.Bookings.Remove(booking);
                    db.SaveChanges();
                } catch (InvalidOperationException ex)
                {
                    _ = bot.SendTextMessageAsync(chatId, "Бронь уже удалена").Result;
                    return;
                }

                participant = db.Participants.Single(c => c.Alias == e.CallbackQuery.From.Username);
            }

            using (FileStream fs = FormSchedule.FormScheduleImage(participant))
            {
                Message mes = bot.SendPhotoAsync(chatId: chatId, photo: new InputOnlineFile(fs, "schedule.png"), caption: "Бронь отменена.").Result;
            }
        }
Beispiel #10
0
        public override async Task Execute(Message message, ITelegramBotClient client)
        {
            string url = await GetImage(message);

            var image = new InputOnlineFile(new Uri(url));
            await client.SendPhotoAsync(message.Chat.Id, image);
        }
Beispiel #11
0
        public async Task SendNewCustomerMessageToGroup(CustomerInfo customerInfo)
        {
            botClient = new TelegramBotClient(apiToken)
            {
                Timeout = TimeSpan.FromSeconds(10)
            };
            //var me = botClient.GetMeAsync().Result;

            string template = GetTelegramMessageFromTemplate(TelegramMessageTypes.NewCustomer);

            string message = String.Format(
                template,
                customerInfo.FullName,
                customerInfo.Id,
                customerInfo.Email,
                customerInfo.PhoneNumber.Length > 0 ? customerInfo.PhoneNumber : noData,
                customerInfo.Courses,
                customerInfo.Tariff.Name,
                customerInfo.Tariff.NewPrice
                );

            // TODO ---> Change to senderIDs in prod.
            // long[] senderIDs = {annaChatId, devChatId, chatIdGroup};
            long[] devIDs = { devChatId };

            foreach (var chatId in devIDs)
            {
                await botClient.SendPhotoAsync(
                    chatId : chatId,
                    photo : "https://artmuz.com.ua/wp-content/uploads/2015/10/salut.jpg",
                    caption : message,
                    parseMode : ParseMode.Html
                    );
            }
        }
 public override void SendMessage(MessageEventArgs ev, ITelegramBotClient bot)
 {
     bot.SendTextMessageAsync(ev.Message.Chat.Id, "Первый вход.----------------");
     bot.SendPhotoAsync(ev.Message.Chat.Id, new InputMedia(ImgUrl),
                        "Это ваш первый вход в Sucks-bucks bot. \n" +
                        "Используйте команду /start чтобы начать работу.");
     InitUser(ev);
 }
Beispiel #13
0
 public static async Task <Message> SendPhotoAsync(this ITelegramBotClient bot, long chatId, string?caption, InputOnlineFile file, IReplyMarkup replyMarkup = null, CancellationToken ct = default(CancellationToken))
 {
     if (bot == null)
     {
         return(null);
     }
     return(await bot.SendPhotoAsync(GetChat(bot, chatId), caption, file, replyMarkup, ct));
 }
Beispiel #14
0
        static async void Bot_OnMessage(object sender, MessageEventArgs e)
        {
            try
            {
                if (e.Message.Text == "/pio")
                {
                    var parser = new UntappdParser();
                    var beers  = await parser.GetBeers();

                    foreach (var beer in beers)
                    {
                        await _botClient.SendPhotoAsync(e.Message.Chat.Id, new InputOnlineFile(new Uri(beer.ImageUrl)));

                        await _botClient.SendTextMessageAsync(
                            chatId : e.Message.Chat,
                            text : beer.ToString(),
                            ParseMode.Markdown
                            );
                    }
                }


                if (e.Message.Type == MessageType.Text && e.Message.Text.Contains("/pidor"))
                {
                    await Task.Delay(5000);

                    await _botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : "Оййй та бля пацани"
                        );

                    await _botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : "І так панятно що"
                        );

                    await _botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : "ЙОНЗА ПЕДРИЛО"
                        );
                }

                if (e.Message.Text != null && yosaList.Any(x => e.Message.Text.Contains(x, StringComparison.InvariantCultureIgnoreCase)))
                {
                    var rand      = new Random();
                    var randIndex = rand.Next(0, yosaJokeList.Count - 1);
                    await _botClient.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : yosaJokeList[randIndex]
                        );
                }
            }
            catch (Exception exception)
            {
                // ignored
            }
        }
Beispiel #15
0
 /// <summary>
 /// Отправляет фото пользователю
 /// </summary>
 /// <param name="chatId">Идентификатор диалога с пользователем</param>
 /// <param name="image">Изображение</param>
 public async void SendPhoto(long chatId, Bitmap image)
 {
     using (MemoryStream ms = new MemoryStream())
     {
         image.Save(ms, ImageFormat.Png);
         ms.Position = 0;
         await botClient.SendPhotoAsync(chatId, new Telegram.Bot.Types.InputFiles.InputOnlineFile(ms));
     }
 }
 public async override void Execute(Message m, ITelegramBotClient client)
 {
     await client.SendPhotoAsync(
         chatId : m.Chat,
         photo : "https://telegrambots.github.io/book/2/docs/shot-photo_msg.jpg",
         caption : "<b>Ara bird</b>. <i>Source</i>: <a href=\"https://pixabay.com\">Pixabay</a>",
         parseMode : ParseMode.Html
         );
 }
 public async void SendImage(string image, string caption)
 {
     Program.loger.Log(">> [SENDING IMAGE] " + caption + Environment.NewLine);
     await botClient.SendPhotoAsync(
         chatId : MY_ID_CHAT,
         photo : image,
         caption : caption
         );
 }
Beispiel #18
0
 private async static void SendPhotoMessage(long id_chat, string text, string FileName)
 {
     Stream stream = File.OpenRead(@"Icon/" + FileName + ".png");
     await botClient.SendPhotoAsync
     (
         id_chat,
         stream,
         text
     );
 }
Beispiel #19
0
        private async Task SendDocument(Message message)
        {
            await _client.SendChatActionAsync(message.Chat.Id, ChatAction.UploadPhoto);

            const string filePath = @"Files/tux.png";

            await using var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            var fileName = filePath.Split(Path.DirectorySeparatorChar).Last();
            await _client.SendPhotoAsync(message.Chat.Id, new InputOnlineFile(fileStream, fileName), "Nice Picture");
        }
Beispiel #20
0
        static async void Bot_OnMessage(object sender, MessageEventArgs e)
        {
            if (e.Message.Text != null)
            {
                Console.WriteLine($"botClient:>> Received a text message from @{e.Message.Chat.Username}:" + e.Message.Text);

                if (e.Message.Text == "/start")
                {
                    var BotonesHYD = new InlineKeyboardMarkup(new[] {
                        new [] {
                            InlineKeyboardButton.WithCallbackData(
                                text: "Días de Circulación HN\U0001F699",
                                callbackData: "Circulacion"),
                            InlineKeyboardButton.WithCallbackData(
                                text: "Doctor COVID-19 \U0001F9D1",
                                callbackData: "AutoEvaluate")
                        },
                        new [] {
                            InlineKeyboardButton.WithUrl(
                                text: "Estadísticas \U0001F4C8",
                                url: "https://www.google.com/search?q=coronavirus+statistics&oq=coronavirus+st&aqs=chrome.0.0i67j69i57j0l6.6211j0j4&sourceid=chrome&ie=UTF-8"),
                            InlineKeyboardButton.WithCallbackData(
                                text: "Prevenir COVID-19\U0001F637",
                                callbackData: "prevenir")
                        },
                        new[] {
                            InlineKeyboardButton.WithCallbackData(
                                text: "Ayuda \U0001F6A8",
                                callbackData: "/help")
                        }
                    });

                    await botClient.SendPhotoAsync(
                        chatId : e.Message.Chat,
                        photo : "https://image.freepik.com/vector-gratis/coronavirus-covid-19-luchadores-02_126288-23.jpg",
                        caption : ""
                        );

                    await botClient.SendTextMessageAsync(e.Message.Chat.Id, "Bienvenid@ al BOT COVID19HN \n Selecciona el comando a ejecutar", replyMarkup : BotonesHYD);
                }
            }
        }
Beispiel #21
0
 public async Task SendImage(long id, string message, string?pictureId)
 {
     _logger.LogDebug($"Sending image: {id}: {pictureId}");
     try
     {
         await _botClient.SendPhotoAsync(id, new InputMedia(pictureId), message);
     }
     catch (Exception)
     {
     }
 }
Beispiel #22
0
        async void DisplayListOfPizza(long chatId)
        {
            var pizzas = site.GetPizzas().Skip(1).Take(4);

            foreach (var item in pizzas)
            {
                var newPhoto = new InputOnlineFile(item.ImageLink);
                await botClient.SendPhotoAsync(chatId, newPhoto, item.Name, Telegram.Bot.Types.Enums.ParseMode.Html, true);
            }
            await botClient.SendTextMessageAsync(chatId, $"I can offer a special list of tasty pizza, choose one please");
        }
        public override async Task <IHandlerResult <StartViewModel> > Handle(
            StartCommand request,
            CancellationToken cancellationToken)
        {
            _logger.Information("StartCommand invoked.");

            if (request.IsBot)
            {
                _logger.Fatal("Bot attempted to subscribe!");
                return(ValidationFailed("Sorry, no bots here!"));
            }

            if (request.ChatId <= 0)
            {
                _logger.Warning($"Bad parameter: {nameof(ChatId)}!");
                return(ValidationFailed($"Bad parameter: {nameof(ChatId)}!"));
            }

            var dbUser = await _userRepository.GetFirstAsync(u => u.ChatId == request.ChatId);

            if (!(dbUser is null))
            {
                var message = dbUser.IsSubscribed
                    ? "were"
                    : "were not";
                return(ValidationFailed(
                           $"You already registered to the bot previously and {message} subscribed to updates."));
            }

            var newUser = _mapper.Map <User>(request);

            newUser.IsSubscribed = true;
            newUser.RegisteredAt = DateTime.Now;

            await _userRepository.CreateAsync(newUser);

            var tours = await _toursFetcher.FetchToursAsync(true, 10);

            foreach (var tour in tours)
            {
                if (tour.ImgUrl != null)
                {
                    var uri = new Uri(tour.ImgUrl);
                    await _telegram.SendPhotoAsync(request.ChatId, new InputOnlineFile(uri), cancellationToken : cancellationToken);
                }

                if (tour.Text != null)
                {
                    await _telegram.SendTextMessageAsync(request.ChatId, tour.Text, cancellationToken : cancellationToken);
                }
            }

            return(Ok());
        }
Beispiel #24
0
    public async Task SendEpicGamesBroadcaster(long chatId)
    {
        var games = await GetFreeGamesParsed();

        var freeGames = games.FirstOrDefault();

        if (freeGames == null)
        {
            return;
        }

        var productUrl   = freeGames.ProductUrl;
        var productTitle = freeGames.ProductTitle;

        var chat = await _botClient.GetChatAsync(chatId);

        if (chat.LinkedChatId != null)
        {
            chatId = chat.LinkedChatId.Value;
        }

        var isHistoryExist = await _rssService.IsHistoryExist(chatId, productUrl);

        if (isHistoryExist)
        {
            Log.Information(
                "Seem EpicGames with Title: '{Title}' already sent to ChatId: {ChannelId}",
                productTitle,
                chatId
                );
        }
        else
        {
            await _botClient.SendPhotoAsync(
                chatId : chatId,
                photo : freeGames.Images.ToString(),
                caption : freeGames.Detail,
                parseMode : ParseMode.Html
                );

            await _rssService.SaveRssHistoryAsync(
                new RssHistory()
            {
                ChatId      = chatId,
                Title       = productTitle,
                Url         = productUrl,
                PublishDate = DateTime.UtcNow,
                Author      = "EpicGames Free",
                CreatedAt   = DateTime.UtcNow,
                RssSource   = "https://store.epicgames.com"
            }
                );
        }
    }
Beispiel #25
0
        static async void Bot_OnMessage(object sender, MessageEventArgs e)
        {
            Console.WriteLine("rec");

            if (e.Message.Text == "newgame")
            {
                Console.WriteLine("Starting New Game");

                for (int i = 0; i < 3; i++)
                {
                    deckCardsUsed[i].Clear();
                }

                await botClient.SendTextMessageAsync(e.Message.Chat, "Начинаем новую игру... Все карты в колодах.");

                return;
            }

            if ((e.Message.Text == "3") || (e.Message.Text == "4") || (e.Message.Text == "5"))
            {
                int deck = Int16.Parse(e.Message.Text) - 3;


                if (deckCardsUsed[deck].Count < deckCardsCount[deck])
                {
                    bool used;
                    int  num = randNum.Next(1, deckCardsCount[deck] + 1);
                    do
                    {
                        used = false;
                        foreach (int cardCheck in deckCardsUsed[deck])
                        {
                            if (num == cardCheck)
                            {
                                used = true;
                                num  = randNum.Next(1, deckCardsCount[deck] + 1);
                            }
                        }
                    } while (used);

                    deckCardsUsed[deck].Add(num);

                    InputOnlineFile imageFile = new InputOnlineFile(new MemoryStream(System.IO.File.ReadAllBytes($"C:\\Working Projects\\Visual Studio\\Activity Online\\Cards\\{deck+3}\\{num}.jpg")));
                    await botClient.SendPhotoAsync(e.Message.Chat, imageFile);
                }
                else
                {
                    await botClient.SendTextMessageAsync(e.Message.Chat, "Карты этой сложности закончились");
                }
                return;
            }
            await botClient.SendTextMessageAsync(e.Message.Chat, "Нужно ввести номер колоды (3,4,5) или newgame, чтобы вернуть все карты в колоду");
        }
        public async Task <List <Message> > SendWakeUpMessageToAllUsersAsync(CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return(null);
            }

            var sentMessages = new List <Message>();

            IEnumerable <UserDbo> users = null;

            using (var context = _dbContextFactory.Create())
            {
                users = context.User
                        .Include(x => x.UserSettings)
                        .Include(x => x.RarityWeights)
                        .Where(x => x.UserSettings.RecieveReminders);
            }

            foreach (var user in users)
            {
                Message sentMessage = null;
                var     rarity      = _rarityRoller.RollRarityForUser(user);
                var     message     = await _messageTextProvider.GetMessage(MessageCategory.WAKEUP, MessageType.STANDARD, rarity, user.ChatId); // could already pass gender and so on

                if (message.ImageUrl == null)
                {
                    sentMessage = await _botClient.SendTextMessageAsync(user.ChatId, message.Text);
                }
                else
                {
                    sentMessage = await _botClient.SendPhotoAsync(user.ChatId, message.ImageUrl, caption : message.Text);
                }

                sentMessages.Add(sentMessage);
            }

            return(sentMessages);
        }
Beispiel #27
0
        public static async Task <Message> SendPhotoAsync(ITelegramBotClient client, ChatId chatId, string photoPath,
                                                          string caption = null, ParseMode?parseMode = null, IReplyMarkup replyMarkup = null)
        {
            bool success = PhotoIds.TryGetValue(photoPath, out string fileId);

            if (success)
            {
                var photo = new InputOnlineFile(fileId);
                return(await client.SendPhotoAsync(chatId, photo, caption, parseMode, replyMarkup : replyMarkup));
            }

            using (var stream = new FileStream(photoPath, FileMode.Open))
            {
                var     photo   = new InputOnlineFile(stream);
                Message message =
                    await client.SendPhotoAsync(chatId, photo, caption, parseMode, replyMarkup : replyMarkup);

                fileId = message.Photo.First().FileId;
                PhotoIds.TryAdd(photoPath, fileId);
                return(message);
            }
        }
Beispiel #28
0
            static async Task <Message> SendFile(ITelegramBotClient botClient, Message message)
            {
                await botClient.SendChatActionAsync(message.Chat.Id, ChatAction.UploadPhoto);

                const string filePath = @"Files/tux.png";

                using FileStream fileStream = new(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                var fileName = filePath.Split(Path.DirectorySeparatorChar).Last();

                return(await botClient.SendPhotoAsync(chatId : message.Chat.Id,
                                                      photo : new InputOnlineFile(fileStream, fileName),
                                                      caption : "Nice Picture"));
            }
Beispiel #29
0
        static async void SendPhoto(string link, long id, string Text, IReplyMarkup r = null)
        {
            try
            {
                await bot.SendPhotoAsync(id, link, Text, replyMarkup : r);

                DateTime stop = DateTime.Now;
                Console.WriteLine($"Відправлено \n {@Text} \n затрачено : {(stop - Users[id].start).Milliseconds} мс");
            }
            catch
            {
                Console.WriteLine("Error sending");
            }
        }
Beispiel #30
0
            static async Task SendDocument(Message message)
            {
                await botClient.SendChatActionAsync(message.Chat.Id, ChatAction.UploadPhoto);

                const string filePath = @"C:\Users\eriks\Desktop\erik.jpg";

                using var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                var fileName = filePath.Split(Path.DirectorySeparatorChar).Last();
                await botClient.SendPhotoAsync(
                    chatId : message.Chat.Id,
                    photo : new InputOnlineFile(fileStream, fileName),
                    caption : "Bonitão você hein!"
                    );
            }