public async Task Should_Get_User_Profile_Photos() { UserProfilePhotos profilePhotos = await BotClient.GetUserProfilePhotosAsync( userId : _fixture.BotUser.Id ); Assert.True(1 <= profilePhotos.TotalCount); Assert.NotNull(profilePhotos.Photos.First()); }
public async Task Should_Get_User_Profile_Photos() { await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldGetBotProfilePhotos); UserProfilePhotos profilePhotos = await BotClient.GetUserProfilePhotosAsync( userId : _fixture.BotUser.Id ); Assert.True(1 <= profilePhotos.TotalCount); Assert.NotNull(profilePhotos.Photos.First()); }
public async Task <IActionResult> SetBotToken(string token) { Token = token; ITelegramBotClient Bot = new TelegramBotClient(token, new WebProxy("127.0.0.1:8888")); User user = await Bot.GetMeAsync(); UserProfilePhotos userProfilePhotos = await Bot.GetUserProfilePhotosAsync(user.Id); File file = await Bot.GetFileAsync(userProfilePhotos.Photos[0][0].FileId); return(Content("https://api.telegram.org/file/bot" + token + "/" + file.FilePath)); }
public static async Task <UserProfilePhotos> GetUserPrifilePhotoAsync(this Telegram telegram, GetUserProfilePhotoRequest sendRequest) { var result = new UserProfilePhotos(); var url = telegram.GetFullPathUrl("getUserProfilePhotos"); var request = new ExternalRequest <ResponseAnswer <UserProfilePhotos>, GetUserProfilePhotoRequest>() { Method = POST_METHOD, PostContentType = "application/json", PostContent = sendRequest }; var response = await RequestSender.Execute(DataAccessMode.Server, request, url).ConfigureAwait(false); result = response.Result.Result; return(result); }
private async Task SendPicture(long chatId, PlayerCountViewModel player, string msg) { UserProfilePhotos userProfilePhotos = null; try { userProfilePhotos = await _client.GetUserProfilePhotosAsync(player.UserId); } catch (Exception e) { var defaultConsoleColor = Console.BackgroundColor; Console.BackgroundColor = ConsoleColor.Red; Console.WriteLine(@"Exception creating picture, YearWinnerJob: " + e.Message); Console.BackgroundColor = defaultConsoleColor; } await using var winnerImage = await GetWinnerImage(userProfilePhotos); await _client.TrySendPhotoAsync(chatId, new InputOnlineFile(winnerImage), msg, ParseMode.Html); }
public async Task <Image> GetProfileImageAsync(int userId) { Image profileImage; try { UserProfilePhotos profilePhotos = await TelegramBot.GetUserProfilePhotosAsync(userId); PhotoSize photoSize = profilePhotos.Photos[0][1]; Telegram.Bot.Types.File profileFile = await TelegramBot.GetFileAsync(photoSize.FileId); Stream imageStream = new MemoryStream(); Telegram.Bot.Types.File getFile = await TelegramBot.GetInfoAndDownloadFileAsync(profileFile.FileId, imageStream); profileImage = Image.FromStream(imageStream); //profileImage.Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg); } catch (Exception ex) { ErrorHandler.SetError(source: "GetProfileImageAsync", error: ex.Message); profileImage = Image.FromFile("unkown.png"); } return(profileImage); }
public async Task Execute(params long[] chatIds) { for (long i = 0; i < chatIds.Length; i++) { try { var monthWinner = await _repository.GetWinnerForMonthAsync(chatIds[i], DateTime.Today); if (monthWinner != null) { var mention = monthWinner.GetUserMention(); var message = $"{Messages.MonthWinner}{Environment.NewLine}\u269C {mention} \u269C{Environment.NewLine}{Messages.Congrats}"; UserProfilePhotos userProfilePhotos = null; try { userProfilePhotos = await _client.GetUserProfilePhotosAsync(monthWinner.UserId); } catch (Exception e) { Console.WriteLine(e); } using var winnerImage = await GetWinnerImage(userProfilePhotos); await _client.TrySendPhotoAsync(chatIds[i], new InputOnlineFile(winnerImage), message, ParseMode.Markdown); } } catch (Exception e) { Console.WriteLine(@"Exception when executing MonthWinnerJob: " + e.Message); continue; } } }
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); }
public static void ClassInitialize(TestContext context) { _telegramMessagesCount = 0; _config = new ComparisonConfig { CompareChildren = true, CompareFields = false, CompareReadOnly = true, ComparePrivateFields = false, ComparePrivateProperties = false, CompareProperties = true, MaxDifferences = 50, MembersToIgnore = new List<string> { "MessageId", "Date", "ForwardDate", "UpdateId" } }; var rm = new ResourceManager("CoffeeJelly.TelegramBotApiWrapperTests.Token", Assembly.GetExecutingAssembly()); var token = rm.GetString("testToken"); _telegramMethods = new TelegramMethods(token, true); var t = _telegramMethods.DeleteWebhook().Result; _privateChat = new Chat { Id = 170181775, FirstName = "Coffee", LastName = "Jelly", Username = "******", Type = ChatType.Private }; _botUser = new User { Id = 252886092, FirstName = "Gmail control bot", Username = "******" }; _italicTextEntity = new MessageEntity { Type = MessageEntityType.Italic, Offset = 0, Length = 23 }; _urlEntity = new MessageEntity { Type = MessageEntityType.Url, Offset = 0, Length = 21 }; _testUrlButton = new InlineKeyboardButton { Text = "URL Button", Url = "https://www.twitch.tv" }; _testCallbackDataButton = new InlineKeyboardButton { Text = "Callback Button", CallbackData = "Test callback data" }; _testInlineKeyboardMarkup = new InlineKeyboardMarkup { InlineKeyboard = new List<List<InlineKeyboardButton>> { new List<InlineKeyboardButton> { _testUrlButton, _testCallbackDataButton } } }; _testTextKeyboardButton = new KeyboardButton { Text = "Test keyboard button" }; _testContactKeyboardButton = new KeyboardButton { Text = "Test contact keyboard button", RequestContact = true }; _testReplyKeyboardMarkup = new ReplyKeyboardMarkup { Keyboard = new List<List<KeyboardButton>> { new List<KeyboardButton> { _testTextKeyboardButton, _testContactKeyboardButton, }, new List<KeyboardButton> { _testContactKeyboardButton } } }; _testReplyKeyboardRemove = new ReplyKeyboardRemove(); _testForceReply = new ForceReply(); _botStartCommandEntity = new MessageEntity { Type = MessageEntityType.BotCommand, Offset = 0, Length = 6 }; _user = new User { Id = 170181775, FirstName = "Coffee", LastName = "Jelly", Username = "******", LanguageCode = "en" }; _location = new Location { Latitude = 53.901112F, Longitude = 27.562325F }; _photoSize1 = new PhotoSize { FileId = "AgADAgADqqcxG4_EJAo-Knthid_Ygy4XSA0ABHFCoFI0_mWuqGEBAAEC", FileSize = 10311, Width = 160, Height = 160 }; _photoSize2 = new PhotoSize { FileId = "AgADAgADqqcxG4_EJAo-Knthid_Ygy4XSA0ABII7yIDVjT7yqWEBAAEC", FileSize = 22094, Width = 320, Height = 320 }; _photoSize3 = new PhotoSize { FileId = "AgADAgADqqcxG4_EJAo-Knthid_Ygy4XSA0ABEN3DhgGCbBFqmEBAAEC", FileSize = 57644, Width = 640, Height = 640 }; _userProfilePhotos = new UserProfilePhotos { TotalCount = 1, Photos = new List<List<PhotoSize>> { new List<PhotoSize> { _photoSize1, _photoSize2, _photoSize3 } } }; _file = new File { FileId = "CAADAgADLgADk35wS_5j0ImZMegiAg", }; _supergroupChat = new Chat { Id = -1001076966401, Title = "testgrp_new_title", Type = ChatType.Supergroup }; _testChannel = new Chat { Id = -1001114442404, Title = "TestChannel", Type = ChatType.Channel }; _userChatMember = new ChatMember { Status = ChatMemberStatus.Creator, User = _user }; _botChatMember = new ChatMember { Status = ChatMemberStatus.Administrator, User = _botUser }; _githubBot = new User { Id = 107550100, FirstName = "GitHub", Username = "******" }; _githubBotChatMember = new ChatMember { Status = ChatMemberStatus.Administrator, User = _githubBot }; }
public async Task Start() { getUserSettings(update); switch (msgType) { case UpdateType.Message: Console.WriteLine($"@{msg.From.Username} ({msg.From.Id} {msg.From.FirstName} {msg.From.LastName}): {msgText}"); switch (msgText) { case "/start": UserProfilePhotos photos = await Bot.GetUserProfilePhotosAsync(msg.From.Id); if (photos.Photos.Length != 0) { using (FileStream saveLocation = new FileStream($@"C:\Users\Home\Desktop\{chatID}.png", FileMode.Create)) { await Bot.GetInfoAndDownloadFileAsync(photos.Photos[0][2].FileId, saveLocation); } } ; await sendCommandInfo(); await resetSettings(true); await sendFolderContent(BotDirectory); break; case "/info": await sendCommandInfo(true); break; case "/donate": await sendCommandDonate(); break; default: break; } msgText = null; break; case UpdateType.CallbackQuery: Console.WriteLine($"@{callback.Message.Chat.Username} ({callback.Message.Chat.Id} {callback.Message.Chat.FirstName} {callback.Message.Chat.LastName}): {callback.Data}"); if (await isNavigation()) { return; } Users[chatID].wayNow += Users[chatID].wayNow != "" ? $"\\{callback.Data}" : callback.Data; wayNow = CheckWayError(Users[chatID].wayNow); if (await isSendFile()) { if (Users[chatID].MessagesForEdit.Count == 0) { await sendFolderContent(BotDirectory); } return; } await sendFolderContent(BotDirectory, wayNow); break; case UpdateType.ShippingQuery: break; case UpdateType.PreCheckoutQuery: await Bot.AnswerPreCheckoutQueryAsync(preCheck.Id); if (preCheck.InvoicePayload == "Донат") { Users[chatID].isDonated = true; await Bot.SendTextMessageAsync(chatID, "Большое спасибо за поддержку 😊❤️"); return; } await Bot.EditMessageTextAsync( Channel, OrderQueue[chatID].MessageId, $"<b>Заказ ✅</b>\n\n" + $"" + $"🤖 Бот: {BotLink}\n" + $"🆔 Пользователь: @{preCheck.From.Username} ({getUserName(preCheck.From)})\n" + $"📎 Файл: <i>{preCheck.InvoicePayload}</i>\n" + $"💳 Сумма: {((double)preCheck.TotalAmount / 100).ToString().Replace(',', '.')} {preCheck.Currency}", ParseMode.Html); Console.WriteLine($"@{preCheck.From.Username} ({preCheck.From.FirstName}): Оплачено."); await sendFiles(preCheck.InvoicePayload, true); await resetSettings(); await sendFolderContent(BotDirectory); break; default: break; } }