Пример #1
0
        public (bool success, string msg, string setUrl) ConvertPack(List <string> ids, string setName, string setTitle, List <DataGridViewRow> rows)
        {
            var bot = new TelegramBotClient(_botKey);

            if (false == setName.EndsWith($"_by_{_botName}"))
            {
                //依照API DOC 說明 https://core.telegram.org/bots/api#createnewstickerset
                //要以 _by_xxxbot 當作貼圖包name結尾
                setName = $"{setName}_by_{_botName}";
            }

            setTitle = $"{setTitle} @EsnChg";
            var addStickerUrl = $"https://t.me/addstickers/{setName}";

            try
            {
                var checkSetName = bot.GetStickerSetAsync(setName).Result;
                SendMessage($"同ID的貼圖包已存在 [<a href=\"{addStickerUrl}\">{setName}</a>],您可以考慮直接使用,或者重新給一個ID。");
                return(success : false, msg : $"同ID [{setName}] 的貼圖包已存在", setUrl : null);
            }
            catch { }

            try
            {
                #region 先拿第一張圖來建貼圖包

                var picPath = rows[0].Cells[0].Value.ToString().Replace("*****@*****.**", "@2x.png");
                var image   = new MagickImage(picPath);
                var ms      = new MemoryStream();
                image.VirtualPixelMethod = VirtualPixelMethod.Transparent;
                image.Resize(_stickerWidth, _stickerHeight);
                image.Write(ms, MagickFormat.Png);
                ms.Position = 0;

                //上第一張圖檔
                var firstSticker = new SimpleSticker
                {
                    fileId = bot.UploadStickerFileAsync(userId: _userId, pngSticker: ms).Result.FileId,
                    emojis = rows[0].Cells[2].Value.ToString()
                };

                //創建貼圖包
                var r = bot.CreateNewStickerSetAsync(userId: _userId,
                                                     name: setName,
                                                     title: setTitle,
                                                     pngSticker: firstSticker.fileId,
                                                     emojis: firstSticker.emojis).Wait(20000);
                var msgId = SendMessage($"已成功建立貼圖包[<a href=\"{addStickerUrl}\">{setTitle}</a>],剩下的貼圖將慢慢加入,請耐心等候;目前進度1/{rows.Count}。").msgId;

                rows.RemoveAt(0); //成功後移除第一張,下面迴圈剩下的慢慢加入
                #endregion

                #region 加入剩下的

                var idx = 2;
                foreach (var row in rows)
                {
                    picPath = row.Cells[0].Value.ToString().Replace("*****@*****.**", "@2x.png");
                    image   = new MagickImage(picPath);
                    ms      = new MemoryStream();
                    image.VirtualPixelMethod = VirtualPixelMethod.Transparent;
                    image.Resize(_stickerWidth, _stickerHeight);
                    image.Write(ms, MagickFormat.Png);
                    ms.Position = 0;

                    var sticker = new SimpleSticker
                    {
                        fileId = bot.UploadStickerFileAsync(userId: _userId, pngSticker: ms).Result.FileId,
                        emojis = row.Cells[2].Value.ToString()
                    };

                    Thread.Sleep(20);

                    bot.AddStickerToSetAsync(userId: _userId,
                                             name: setName,
                                             pngSticker: sticker.fileId,
                                             emojis: sticker.emojis).Wait(20000);

                    Thread.Sleep(20);

                    var editResult = EditMessage(msgId, $"已成功建立貼圖包[<a href=\"{addStickerUrl}\">{setTitle}</a>],剩下的貼圖將慢慢加入,請耐心等候;目前進度{idx}/{rows.Count + 1}。");

                    if (false == editResult.success)
                    {
                        msgId = Convert.ToInt32(editResult.msg);
                    }

                    idx++;
                }

                #endregion

                return(success : true, msg : msgId.ToString(), setUrl : addStickerUrl);
            }
            catch
            {
                return(success : false, msg : $"不知道什麼原因", setUrl : null);
            }
            finally
            {
                try
                {
                    DeleteFolder(new DirectoryInfo($"{AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\')}\\tmp"));
                }
                catch { }
            }
        }
Пример #2
0
        public override async Task Execute(Message message, TelegramBotClient botClient)
        {
            long    chatId = message.Chat.Id;
            BotUser user;
            CreateMicroStickersRequest request;
            string url, result;
            Dictionary <string, string> query;
            HttpResponseMessage         response;
            HttpClient      client = new HttpClient();
            StickerToResize stickerToResize;

            client   = new HttpClient();
            url      = string.Format(AppSettings.Url, "api/1.0.0/users/") + chatId.ToString();
            response = await client.GetAsync(url);

            result = await response.Content.ReadAsStringAsync();

            user = JsonConvert.DeserializeObject <BotUser>(result);

            url = string.Format(AppSettings.Url, "api/1.0.0/users/") + chatId.ToString() + "/requests";

            response = await client.GetAsync(url);

            if (!response.IsSuccessStatusCode)
            {
                url   = string.Format(AppSettings.Url, "api/1.0.0/micro-sticker-requests");
                query = new Dictionary <string, string>()
                {
                    ["userId"] = user.Id.ToString()
                };
                await client.PostAsync(QueryHelpers.AddQueryString(url, query), null);

                user.CurentCommand = BotCommand.CreateMicroStickers;

                url = string.Format(AppSettings.Url, "api/1.0.0/users/") + chatId.ToString();
                await client.PutAsync(url, new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json"));

                await botClient.SendTextMessageAsync(chatId, "Please input name of the future sticker pack.", parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown);

                return;
            }

            result = await response.Content.ReadAsStringAsync();

            request = JsonConvert.DeserializeObject <CreateMicroStickersRequest>(result);

            switch (request.Status)
            {
            case MicroStickersStatus.AwaitingName:
                string name = message.Text;
                request.Name   = name;
                request.Status = MicroStickersStatus.AwaitingSticker;
                url            = string.Format(AppSettings.Url, "api/1.0.0/micro-sticker-requests/") + user.Id;
                await client.PutAsync(url, new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json"));

                await botClient.SendTextMessageAsync(chatId, "Good. Now send me a sticker.", parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown);

                break;

            case MicroStickersStatus.AwaitingSticker:
                Sticker    updateSticker = message.Sticker;
                StickerSet stickerSet    = await botClient.GetStickerSetAsync(updateSticker.SetName);

                List <string> stickerImages = new List <string>();
                List <string> emojis        = new List <string>();
                foreach (var sticker in stickerSet.Stickers)
                {
                    var file = await botClient.GetFileAsync(sticker.FileId);

                    string baseUrl = string.Format("https://api.telegram.org/file/bot{0}/{1}", AppSettings.Key, file.FilePath);
                    url             = string.Format(AppSettings.Url, "api/1.0.0/sticker/resize");
                    stickerToResize = new StickerToResize()
                    {
                        Url    = baseUrl,
                        Width  = _strickerWidth,
                        Height = _stickerHeight
                    };

                    response = await client.PostAsync(url, new StringContent(JsonConvert.SerializeObject(stickerToResize), Encoding.UTF8, "application/json"));

                    result = await response.Content.ReadAsStringAsync();

                    ImageUploadResult imageUrl = JsonConvert.DeserializeObject <ImageUploadResult>(result);

                    stickerImages.Add(imageUrl.Url.ToString());
                    emojis.Add(sticker.Emoji);
                }

                int    userId               = message.From.Id;
                string stickerPackName      = request.Name;
                string shortStickerPackName = stickerPackName.ToLower().Replace(' ', '_') + "_by_burnyaxa_bot";
                await botClient.CreateNewStickerSetAsync(userId, shortStickerPackName, stickerPackName, stickerImages.First(), emojis.First());

                stickerImages.RemoveAt(0);
                emojis.RemoveAt(0);
                if (stickerImages.Count() != 0 && emojis.Count() != 0)
                {
                    var stickerData = stickerImages.Zip(emojis, (s, e) => new { Image = s, Emoji = e });
                    foreach (var element in stickerData)
                    {
                        await botClient.AddStickerToSetAsync(userId, shortStickerPackName, element.Image, element.Emoji);
                    }
                }
                StickerSet newStickers = await botClient.GetStickerSetAsync(shortStickerPackName);

                await botClient.SendTextMessageAsync(chatId, "Enjoy your micro-stickers :)", parseMode : Telegram.Bot.Types.Enums.ParseMode.Markdown);

                await botClient.SendStickerAsync(chatId, newStickers.Stickers.First().FileId);

                url = string.Format(AppSettings.Url, "api/1.0.0/micro-sticker-requests/") + user.Id;

                await client.DeleteAsync(url);

                user.CurentCommand = BotCommand.Start;

                url = string.Format(AppSettings.Url, "api/1.0.0/users/") + chatId.ToString();
                await client.PutAsync(url, new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json"));

                break;
            }
        }