Пример #1
0
        public async void DoHandleAsync(MiraiHttpSession session, IMessageBase[] chain, IBaseInfo info, bool isGroupMessage = true)
        {
            ChineseLunisolarCalendar calendar = new ChineseLunisolarCalendar();
            var now          = DateTime.Now;
            var year         = calendar.GetYear(now);
            var month        = calendar.GetMonth(now);
            var day          = calendar.GetDayOfMonth(now);
            var hasLeapMonth = calendar.GetLeapMonth(year) > 0;

            if (hasLeapMonth)
            {
                if (month < 13 && day < 23)
                {
                    if (month > 1 && day > 15)
                    {
                        return;
                    }
                }
            }
            else
            {
                if (month < 12 && day < 23)
                {
                    if (month > 1 && day > 15)
                    {
                        return;
                    }
                }
            }
            List <IMessageBase> result = new List <IMessageBase>();
            IMessageBase        img    = null;

            switch (chain.First(m => m.Type == "Plain").ToString())
            {
            case "新年快乐":
                img = await session.UploadPictureAsync(UploadTarget.Group, "Resources\\NewYear\\NewYearStick.png");

                result.Add(img);
                break;

            case "新年抽签":
                string[] lotterise = Directory.GetFiles("Resources\\Lottery");
                img = await session.UploadPictureAsync(UploadTarget.Group, lotterise[randomer.Next(0, lotterise.Length - 1)]);

                result.Add(img);
                break;

            default:
                break;
            }
            if (isGroupMessage)
            {
                await session.SendGroupMessageAsync(((IGroupMemberInfo)info).Group.Id, result.ToArray());
            }
            else
            {
                await session.SendFriendMessageAsync(info.Id, result.ToArray());
            }
        }
Пример #2
0
        public void SendMessage(MagickImage a)
        {
            Directory.CreateDirectory("caches");
            var fileName = System.IO.Path.GetFullPath(System.IO.Path.Combine("caches", $"{Guid.NewGuid():D}.png"));

            a.Write(fileName, MagickFormat.Png24);
            session.UploadPictureAsync(UploadTarget.Group, fileName).Wait();
            var imageMessage = session.UploadPictureAsync(UploadTarget.Friend, fileName).Result;

            session.SendFriendMessageAsync(TargetQQ, imageMessage).Wait();

            a.Dispose();
        }
Пример #3
0
        public override void SendGroupMessage(GroupID groupID, string message)
        {
            var isCommonMessage = message.Contains("好嘞") ||
                                  message.Contains("很抱歉, 这个命令可能需要更长的时间来执行.") ||
                                  message.Contains("I want to buy");

            // 这里仅仅为临时方案
            if (MiraiConfig.Instance.RenderTextInImage && !isCommonMessage)
            {
                var imageMsg = session.UploadPictureAsync(UploadTarget.Group, RenderImage(message)).Result;
                var regex    = new Regex(
                    @"(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[-A-Z0-9+&@#\/%=~_|$?!:,.])*(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[A-Z0-9+&@#\/%=~_|$])",
                    RegexOptions.Multiline | RegexOptions.IgnoreCase).Matches(message);
                if (regex.Count > 0)
                {
                    session.SendGroupMessageAsync(groupID, imageMsg, new PlainMessage(regex.Connect("\n"))).Wait();
                }
                else
                {
                    session.SendGroupMessageAsync(groupID, imageMsg).Wait();
                }
            }
            else
            {
                session.SendGroupMessageAsync(groupID, new PlainMessage(message)).Wait();
            }
        }
        private async Task SendPictureAsync(MiraiHttpSession session, string path) // 发图
        {
            // 你也可以使用另一个重载 UploadPictureAsync(PictureTarget, Stream)
            // mirai-api-http 在v1.7.0以下时将使用本地的HttpListener做图片中转
            ImageMessage msg = await session.UploadPictureAsync(PictureTarget.Group, path);

            IMessageBase[] chain = new IMessageBase[] { msg }; // 数组里边可以加上更多的 IMessageBase, 以此达到例如图文并发的情况
            await session.SendGroupMessageAsync(0, chain);     // 自己填群号, 一般由 IGroupMessageEventArgs 提供
        }
Пример #5
0
        public async void DoHandleAsync(MiraiHttpSession session, IMessageBase[] chain, IBaseInfo info, bool isGroupMessage = true)
        {
            logger.LogInformation($"{info.Name} 询问最新活动");
            var  latestEvent    = data.GetLatestEvent();
            bool isEventChanged = false;

            if (int.Parse(latestEvent.Item1) != latestEventId)
            {
                latestEventId  = int.Parse(latestEvent.Item1);
                isEventChanged = true;
            }
            string       message;
            IMessageBase img;

            if (isGroupMessage)
            {
                img = await session.UploadPictureAsync(UploadTarget.Group, await client.GetEventBannerImagePath(latestEvent.Item1));
            }
            else
            {
                img = await session.UploadPictureAsync(UploadTarget.Friend, await client.GetEventBannerImagePath(latestEvent.Item1));
            }
            DateTime endTime    = DateTimeOffset.FromUnixTimeMilliseconds(long.Parse(latestEvent.Item2.EndAt[0])).LocalDateTime;
            DateTime startTime  = DateTimeOffset.FromUnixTimeMilliseconds(long.Parse(latestEvent.Item2.StartAt[0])).LocalDateTime;
            string   eventState = startTime >= DateTime.Now ? $"即将开始,剩余{startTime - DateTime.Now:d\\日h\\小\\时m\\分}" : endTime <= DateTime.Now ? "结束" : $"正在进行,剩余{endTime - DateTime.Now:d\\日h\\小\\时m\\分}";

            message = $"活动名称: {latestEvent.Item2.EventName[0]}\n开始时间: {startTime}\n结束时间: {endTime}\n活动状态: {eventState}";
            logger.LogInformation($"已查到活动,并回复 {message}");
            IMessageBase[] result = new IMessageBase[]
            {
                new PlainMessage((isEventChanged ? "发现新活动!\n" : "") + message),
                img
            };
            if (isGroupMessage)
            {
                await session.SendGroupMessageAsync(((IGroupMemberInfo)info).Group.Id, result);
            }
            else
            {
                await session.SendFriendMessageAsync(info.Id, result);
            }
        }
Пример #6
0
        public static ImageMessage TextToImg(string text, MiraiHttpSession session)
        {
            string fileName = MD5(text);
            string fullPath = Path.Combine("Buffer\\", fileName);

            if (!File.Exists(fullPath))
            {
                Convert_Text_to_Image(text, "Times New Roman", 13).Save(fullPath);
            }
            return(session.UploadPictureAsync(UploadTarget.Group, fullPath).Result);
        }
Пример #7
0
        public async Task <bool> OnAt(MiraiHttpSession session, IGroupMessageEventArgs e)
        {
            bool selfAted = e.Chain.Where(msg => msg is AtMessage)
                            .Cast <AtMessage>()
                            .Select(atmsg => atmsg.Target)
                            .Contains(session.QQNumber.Value);

            if (selfAted)
            {
                var imgmsg = await session.UploadPictureAsync(UploadTarget.Group, @"..\..\..\images\kokoaCry.jpg");

                await session.SendGroupMessageAsync(e.Sender.Group.Id, new IMessageBase[] { new PlainMessage("检测到您正在at我!主人很懒,不想实" +
                                                                                                             "现接受at信息调用我的模块,请直接使用文字命令来调用!"),
                                                                                            imgmsg }, ((SourceMessage)e.Chain[0]).Id);
            }
            return(false);
        }
Пример #8
0
        public async Task <bool> GroupMessage(MiraiHttpSession session, IGroupMessageEventArgs e)
        {
            if (e.GetMessage().IsCommand())
            {
                var assembly    = Assembly.GetExecutingAssembly();
                var fileVersion = FileVersionInfo.GetVersionInfo(assembly.Location);

                switch (e.GetMessage())
                {
                case "/Help":
                    await session.SendPlainText(e, $"欢迎使用HeliumBot {fileVersion.FileVersion}", "===================",
                                                "/Help : 查看帮助",
                                                "/Genshin <uid> : 获取指定原神UID的公开信息",
                                                "/Genshin <uid> -Avatar : 获取指定原神UID的公开信息,并查看获得的角色",
                                                "/GenshinAbyss <uid> : 获取指定原神UID的深渊战绩",
                                                "/GenshinAbyss <uid> -Detail : 获取指定原神UID的深渊战绩,并且查看每层每间详情",
                                                "/Money : 给作者打钱",
                                                "/About : 查看Bot的关于信息");

                    break;

                case "/Money":
                    var img = await session.UploadPictureAsync(UploadTarget.Group,
                                                               await new HttpClient().GetStreamAsync("https://i.loli.net/2021/05/04/fXOm1xnrsBg45Zh.jpg"));

                    await session.SendGroupMessageAsync(e.Sender.Group.Id, img);

                    break;

                case "/About":
                    await session.SendPlainText(e, $"HeliumBot {fileVersion.FileVersion}",
                                                $"Maintain by AHpx(https://github.com/AHpxChina)",
                                                $"Based on Mirai-CSharp(https://github.com/Executor-Cheng/Mirai-CSharp)",
                                                $"Open source repository on https://github.com/AHpxChina/HeliumBot",
                                                $"Acknowledgment:",
                                                $"mirai(https://github.com/mamoe/mirai)",
                                                $"mirai-api-http(https://github.com/mamoe/mirai-api-http)",
                                                $"mirai-console(https://github.com/mamoe/mirai-console)");

                    break;
                }
            }

            return(false);
        }
Пример #9
0
        async Task <bool> ITempMessage.TempMessage(MiraiHttpSession session, ITempMessageEventArgs e)
        {
            if (BotInfo.BannedUser.Contains(e.Sender.Id))
            {
                return(false);
            }
            if (BotInfo.DebugMode)
            {
                if (BotInfo.DebugReplyAdminOnly)
                {
                    if (!BotInfo.AdminQQ.Contains(e.Sender.Id))
                    {
                        return(false);
                    }
                }
            }
            if (e.Chain.Length > 1)  //普通消息
            {
                switch (e.Chain[1].Type)
                {
                case "Plain":
                    PlainMessageHandler.HandleFriendMesage(session, e.Chain, e.Sender.Id);
                    break;

                case "Image":
                    for (int i = 1; i < e.Chain.Length; i++)
                    {
                        ImageMessage imgMsg = e.Chain[i] as ImageMessage;
                        await SearchPictureHandler.SearchPicture(imgMsg, picStream => session.UploadPictureAsync(UploadTarget.Group, picStream), msg => session.SendTempMessageAsync(e.Sender.Id, e.Sender.Group.Id, msg));
                    }
                    break;
                }
            }
            return(false);
        }
Пример #10
0
        protected static void OnMessage(MiraiHttpSession session, string message, Source Sender)
        {
            if (!booted)
            {
                return;
            }

            long ticks = DateTime.Now.Ticks;

            Func <string, Task> callback = async s =>
            {
                try
                {
                    Utils.Log(LoggerLevel.Debug, $"[{(DateTime.Now.Ticks - ticks) / 10000}ms] sent msg: " + s);
                    if (Sender.FromGroup != 0)
                    {
                        await session.SendGroupMessageAsync(Sender.FromGroup, await Utils.GetMessageChain(s, async p => await session.UploadPictureAsync(UploadTarget.Group, p)));
                    }
                    else if (!Sender.IsTemp)
                    {
                        await session.SendFriendMessageAsync(Sender.FromQQ, await Utils.GetMessageChain(s, async p => await session.UploadPictureAsync(UploadTarget.Temp, p)));
                    }
                    else
                    {
                        await session.SendTempMessageAsync(Sender.FromQQ, Sender.FromGroup, await Utils.GetMessageChain(s, async p => await session.UploadPictureAsync(UploadTarget.Friend, p)));
                    }
                }
                catch (Exception e)
                {
                    Utils.Log(LoggerLevel.Error, "error in msg: " + s + "\n" + e.ToString());
                }
            };

            Utils.Log(LoggerLevel.Debug, "recv msg: " + message);

            Task.Run(() => instance.OnMessage(new HandlerArgs
            {
                message  = message,
                Sender   = Sender,
                Callback = callback
            }));
        }
Пример #11
0
        private static void PluginInitialize(MiraiHttpSession session)
        {
            Configuration.Register(new Activation());
            Configuration.Register(new Delay());
            Configuration.Register(new MessageStatistic());
            Configuration.Register(new ReplyHandler());
            Configuration.Register(new Whitelist());
            Configuration.Register(new Admin());
            Configuration.Register(new Blacklist());
            Configuration.Register(new BlacklistF());
            Configuration.Register(new TitleCooldown());
            Configuration.Register(new PCRConfig());
            Configuration.Register(new R18Allowed());
            Configuration.Register(new NormalAllowed());
            Configuration.Register(new AccountBinding());
            Configuration.Register(new ServerManager());
            Configuration.Register(new TimeConfiguration());
            Configuration.Register(new GlobalConfiguration());
            Configuration.Register(new Antirevoke());
            Configuration.Register(new SetuConfig());
            Configuration.Register(new Save());
            Configuration.Register(new CarTypeConfig());
            //Configuration.Register(new PeriodRank());

            MessageHandler.Register(new CarHandler());
            MessageHandler.Register(Configuration.GetConfig <ReplyHandler>());
            MessageHandler.Register(new WhitelistHandler());
            MessageHandler.Register(new RepeatHandler());
            MessageHandler.Register(Configuration.GetConfig <MessageStatistic>());

            MessageHandler.Register(new YCM());
            MessageHandler.Register(new QueryCommand());
            MessageHandler.Register(new ReplyCommand());
            MessageHandler.Register(new FindCommand());
            MessageHandler.Register(new DelayCommand());
            MessageHandler.Register(new AdminCommand());
            MessageHandler.Register(new SekaiCommand());
            MessageHandler.Register(new SekaiPCommand());
            MessageHandler.Register(new WhitelistCommand());
            MessageHandler.Register(new GachaCommand());
            MessageHandler.Register(new GachaListCommand());
            MessageHandler.Register(new Activate());
            MessageHandler.Register(new Deactivate());
            MessageHandler.Register(new BlacklistCommand());
            MessageHandler.Register(new TitleCommand());
            MessageHandler.Register(new PCRRunCommand());
            MessageHandler.Register(new CarTypeCommand());
            MessageHandler.Register(new SekaiLineCommand());

            MessageHandler.Register(new DDCommand());
            MessageHandler.Register(new CDCommand());
            MessageHandler.Register(new CCDCommand());
            MessageHandler.Register(new SLCommand());
            MessageHandler.Register(new SCCommand());
            MessageHandler.Register(new TBCommand());
            MessageHandler.Register(new RCCommand());
            MessageHandler.Register(new CPMCommand());

            CommandHelper.Register <AdditionalCommands.随机禁言>();
            CommandHelper.Register <AdditionalCommands.泰拉在线>();
            CommandHelper.Register <AdditionalCommands.泰拉资料>();
            CommandHelper.Register <AdditionalCommands.封>();
            CommandHelper.Register <AdditionalCommands.注册>();
            CommandHelper.Register <AdditionalCommands.在线排行>();
            CommandHelper.Register <AdditionalCommands.物品排行>();
            CommandHelper.Register <AdditionalCommands.财富排行>();
            CommandHelper.Register <AdditionalCommands.渔夫排行>();
            CommandHelper.Register <AdditionalCommands.死亡排行>();
            CommandHelper.Register <AdditionalCommands.用户>();
            CommandHelper.Register <AdditionalCommands.解>();
            CommandHelper.Register <AdditionalCommands.重置>();
            CommandHelper.Register <AdditionalCommands.切换>();
            CommandHelper.Register <AdditionalCommands.绑定>();
            CommandHelper.Register <AdditionalCommands.执行>();
            CommandHelper.Register <AdditionalCommands.解绑>();
            CommandHelper.Register <AdditionalCommands.开启前缀检测>();
            CommandHelper.Register <AdditionalCommands.关闭前缀检测>();
            CommandHelper.Register <AdditionalCommands.开启自动清人>();
            CommandHelper.Register <AdditionalCommands.关闭自动清人>();
            CommandHelper.Register <AdditionalCommands.加入黑名单>();
            CommandHelper.Register <AdditionalCommands.移除黑名单>();
            CommandHelper.Register <AdditionalCommands.黑名单列表>();
            CommandHelper.Register <AdditionalCommands.务器列表>();
            CommandHelper.Register <AdditionalCommands.解ip>();
            CommandHelper.Register <AdditionalCommands.封ip>();
            CommandHelper.Register <AdditionalCommands.saveall>();

            MessageHandler.Register(new R18AllowedCommand());
            MessageHandler.Register(new NormalAllowedCommand());
            MessageHandler.Register(new SetuCommand());
            MessageHandler.Register(new ZMCCommand());
            MessageHandler.Register(new AntirevokeCommand());

            if (File.Exists("sekai"))
            {
                ScheduleManager.QueueTimed(() =>
                {
                    var id   = MasterData.Instance.events.Last().id;
                    var data = Utils.GetHttp($"https://bitbucket.org/sekai-world/sekai-event-track/raw/main/event{id}.json");
                    var fn   = $"sekai_event{id}.csv";

                    lock (SekaiFile)
                    {
                        if (!File.Exists(fn))
                        {
                            File.WriteAllText(fn, $"time,{string.Join(",", data.Properties().Where(p => p.Name.StartsWith("rank")).Select(p => p.Name))}\n");
                        }

                        File.AppendAllText(fn, $"{data["time"]},{string.Join(",", data.Properties().Where(p => p.Name.StartsWith("rank")).Select(p => p.Value.Single()["score"]))}\n");
                    }
                }, 60);
            }

            Configuration.LoadAll();

            foreach (var schedule in Configuration.GetConfig <TimeConfiguration>().t)
            {
                var s = schedule;
                ScheduleManager.QueueTimed(() =>
                {
                    session.SendGroupMessageAsync(s.group, Utils.GetMessageChain(s.message, p => session.UploadPictureAsync(UploadTarget.Group, p).Result));
                }, s.delay);
            }

            GC.Collect();
            MessageHandler.booted = true;
        }
Пример #12
0
#pragma warning disable CS1998 // 异步方法缺少 "await" 运算符,将以同步方式运行
        protected static async Task OnMessage(MiraiHttpSession session, string message, Source Sender)
#pragma warning restore CS1998 // 异步方法缺少 "await" 运算符,将以同步方式运行
        {
            if (!booted)
            {
                return;
            }

            bool isAdmin = AdminQQ == Sender.FromQQ || Configuration.GetConfig <Admin>().hash.Contains(Sender.FromQQ);
            long ticks   = DateTime.Now.Ticks;

            if (IsIgnore(Sender))
            {
                return;
            }

            Action <string> callback = delegate(string s)
            {
                try
                {
                    Utils.Log(LoggerLevel.Debug, $"[{(DateTime.Now.Ticks - ticks) / 10000}ms] sent msg: " + s);
                    if (Sender.FromGroup != 0)
                    {
                        session.SendGroupMessageAsync(Sender.FromGroup, Utils.GetMessageChain(s, p => session.UploadPictureAsync(UploadTarget.Group, p).Result)).Wait();
                    }
                    else if (!Sender.IsTemp)
                    {
                        session.SendFriendMessageAsync(Sender.FromQQ, Utils.GetMessageChain(s, p => session.UploadPictureAsync(UploadTarget.Temp, p).Result)).Wait();
                    }
                    else
                    {
                        session.SendTempMessageAsync(Sender.FromQQ, Sender.FromGroup, Utils.GetMessageChain(s, p => session.UploadPictureAsync(UploadTarget.Friend, p).Result)).Wait();
                    }
                }
                catch (Exception e)
                {
                    Utils.Log(LoggerLevel.Error, "error in msg: " + s + "\n" + e.ToString());
                }
            };

            Utils.Log(LoggerLevel.Debug, "recv msg: " + message);

            Task.Run(() =>
            {
                instance.OnMessage(message, Sender, isAdmin, callback);
            }).Start();
        }
Пример #13
0
        public static async void HandleFriendMesage(MiraiHttpSession session, IMessageBase[] Chain, long qqId)
        {
            Regex regexSearchOn           = new Regex(BotInfo.SearchModeOnCmd.ReplaceGreenOnionsTags());
            Regex regexSearchOff          = new Regex(BotInfo.SearchModeOffCmd.ReplaceGreenOnionsTags());
            Regex regexTranslateToChinese = new Regex(BotInfo.TranslateToChineseCMD.ReplaceGreenOnionsTags());
            Regex regexTranslateTo        = new Regex(BotInfo.TranslateToCMD.ReplaceGreenOnionsTags());
            Regex regexHPicture           = new Regex(BotInfo.HPictureCmd.ReplaceGreenOnionsTags());
            Regex regexShabHPicture       = new Regex(BotInfo.ShabHPictureCmd.ReplaceGreenOnionsTags());
            //Regex regexSelectPhone = new Regex($"({BotInfo.BotName}查询手机号[::])");


            string firstMessage = Chain[1].ToString();

            #region -- 连续搜图 --
            if (regexSearchOn.IsMatch(firstMessage))
            {
                if (Cache.SearchingPictures.ContainsKey(qqId))
                {
                    Cache.SearchingPictures[qqId] = DateTime.Now.AddMinutes(1);
                    await session.SendFriendMessageAsync(qqId, new PlainMessage(BotInfo.SearchModeAlreadyOnReply.ReplaceGreenOnionsTags()));
                }
                else
                {
                    Cache.SearchingPictures.Add(qqId, DateTime.Now.AddMinutes(1));
                    await session.SendFriendMessageAsync(qqId, new PlainMessage(BotInfo.SearchModeOnReply.ReplaceGreenOnionsTags()));

                    Cache.CheckSearchPictureTime(callback =>
                    {
                        Cache.SearchingPictures.Remove(qqId);
                        session.SendFriendMessageAsync(qqId, new PlainMessage(BotInfo.SearchModeTimeOutReply.ReplaceGreenOnionsTags()));
                    });
                }
            }
            else if (regexSearchOff.IsMatch(firstMessage))
            {
                if (Cache.SearchingPictures.ContainsKey(qqId))
                {
                    Cache.SearchingPictures.Remove(qqId);
                    await session.SendFriendMessageAsync(qqId, new PlainMessage(BotInfo.SearchModeOffReply.ReplaceGreenOnionsTags()));
                }
                else
                {
                    await session.SendFriendMessageAsync(qqId, new PlainMessage(BotInfo.SearchModeAlreadyOffReply.ReplaceGreenOnionsTags()));
                }
            }
            #endregion -- 连续搜图 --
            #region -- 翻译 --
            else if (regexTranslateToChinese.IsMatch(firstMessage))
            {
                foreach (Match match in regexTranslateToChinese.Matches(firstMessage))
                {
                    try
                    {
                        await session.SendFriendMessageAsync(qqId, new PlainMessage(await GoogleTranslateHelper.TranslateToChinese(firstMessage.Substring(match.Value.Length))));
                    }
                    catch (Exception ex)
                    {
                        await session.SendFriendMessageAsync(qqId, new PlainMessage("翻译失败," + ex.Message));
                    }
                    break;
                }
            }
            else if (regexTranslateTo.IsMatch(firstMessage))
            {
                foreach (Match match in regexTranslateTo.Matches(firstMessage))
                {
                    if (match.Groups.Count > 1)
                    {
                        try
                        {
                            await session.SendFriendMessageAsync(qqId, new PlainMessage(await GoogleTranslateHelper.TranslateTo(firstMessage.Substring(match.Value.Length), match.Groups[1].Value)));
                        }
                        catch (Exception ex)
                        {
                            await session.SendFriendMessageAsync(qqId, new PlainMessage("翻译失败," + ex.Message));
                        }
                    }
                    break;
                }
            }
            #endregion -- 翻译 --
            #region -- 色图 --
            #region  -- Lolicon图库 --
            else if (regexHPicture.IsMatch(firstMessage) || BotInfo.HPictureUserCmd.Contains(firstMessage))
            {
                if (Cache.CheckPMLimit(qqId))
                {
                    await session.SendFriendMessageAsync(qqId, new PlainMessage(BotInfo.HPictureOutOfLimitReply));

                    return;
                }
                if (Cache.CheckPMCD(qqId))
                {
                    await session.SendFriendMessageAsync(qqId, new PlainMessage(BotInfo.HPictureCDUnreadyReply));

                    return;
                }
                HPictureHandler.SendHPictures(session, firstMessage, BotInfo.HPictureAllowR18, BotInfo.HPictureEndCmd, stream => session.UploadPictureAsync(UploadTarget.Friend, stream), msg => session.SendFriendMessageAsync(qqId, msg), limitType =>
                {
                    if (limitType == LimitType.Frequency)
                    {
                        Cache.RecordFriendCD(qqId);
                        if (BotInfo.HPictureLimitType == LimitType.Frequency)
                        {
                            Cache.RecordLimit(qqId);
                        }
                    }
                    else if (limitType == LimitType.Count && BotInfo.HPictureLimitType == LimitType.Count)
                    {
                        Cache.RecordLimit(qqId);
                    }
                }, BotInfo.HPicturePMRevoke);
            }
            #endregion  -- Lolicon图库 --
            #region  -- Shab图库 --
            else if (regexShabHPicture.IsMatch(firstMessage) || BotInfo.HPictureUserCmd.Contains(firstMessage))
            {
                if (Cache.CheckPMLimit(qqId))
                {
                    await session.SendFriendMessageAsync(qqId, new PlainMessage(BotInfo.HPictureOutOfLimitReply));

                    return;
                }
                if (Cache.CheckPMCD(qqId))
                {
                    await session.SendFriendMessageAsync(qqId, new PlainMessage(BotInfo.HPictureCDUnreadyReply));

                    return;
                }
                HPictureHandler.SendHPictures(session, firstMessage, BotInfo.HPictureAllowR18, BotInfo.ShabHPictureEndCmd, stream => session.UploadPictureAsync(UploadTarget.Friend, stream), msg => session.SendFriendMessageAsync(qqId, msg), limitType =>
                {
                    if (limitType == LimitType.Frequency)
                    {
                        Cache.RecordFriendCD(qqId);
                        if (BotInfo.HPictureLimitType == LimitType.Frequency)
                        {
                            Cache.RecordLimit(qqId);
                        }
                    }
                    else if (limitType == LimitType.Count && BotInfo.HPictureLimitType == LimitType.Count)
                    {
                        Cache.RecordLimit(qqId);
                    }
                }, BotInfo.HPicturePMRevoke);
            }
            #endregion  -- Shab图库 --
            #endregion -- 色图 --
            else if (firstMessage == $"{BotInfo.BotName}帮助")
            {
                List <string> lstEnabledFeatures = new List <string>();
                if (BotInfo.SearchEnabled)
                {
                    lstEnabledFeatures.Add("搜图");
                }
                if (BotInfo.TranslateEnabled)
                {
                    lstEnabledFeatures.Add("翻译");
                }
                if (BotInfo.HPictureEnabled)
                {
                    lstEnabledFeatures.Add("GHS");
                }
                //if (BotInfo.QQId == 3246934384)
                //{
                //    lstEnabledFeatures.Add("查手机号");
                //}
                string strHelpResult = $"现在您可以让我{string.Join(",", lstEnabledFeatures)}。\r\n如果您觉得{BotInfo.BotName}好用,请到{BotInfo.BotName}的项目地址 https://github.com/Alex1911-Jiang/GreenOnions 给{BotInfo.BotName}一颗星星。";
                await session.SendFriendMessageAsync(qqId, new PlainMessage(strHelpResult));
            }
            //#region -- 查询手机号(夹带私货) --
            //else if (regexSelectPhone.IsMatch(firstMessage))
            //{
            //    if (BotInfo.QQId == 3246934384)
            //    {
            //        foreach (Match match in regexSelectPhone.Matches(firstMessage))
            //        {
            //            if (match.Groups.Count > 1)
            //            {
            //                string qqNumber = firstMessage.Substring(match.Groups[1].Length);
            //                long lQQNumber;
            //                if (long.TryParse(qqNumber, out lQQNumber))
            //                {
            //                    try
            //                    {
            //                        string result = AssemblyHelper.CallStaticMethod<string>("GreenOnions.QQPhone", "GreenOnions.QQPhone.QQAndPhone", "GetPhoneByQQ", lQQNumber);
            //                        await session.SendFriendMessageAsync(qqId, new PlainMessage(result));
            //                    }
            //                    catch (Exception ex)
            //                    {
            //                        await session.SendFriendMessageAsync(qqId, new PlainMessage("查询失败" + ex.Message));
            //                    }
            //                }
            //                else
            //                {
            //                    await session.SendFriendMessageAsync(qqId, new PlainMessage("请输入正确的QQ号码(不支持以邮箱查询)"));
            //                }
            //            }
            //        }
            //    }
            //}
            //#endregion -- 查询手机号(夹带私货) --
        }
Пример #14
0
        public static async void HandleGroupMesage(MiraiHttpSession session, IMessageBase[] Chain, IGroupMemberInfo sender, QuoteMessage quoteMessage)
        {
            Regex regexSearchOn           = new Regex(BotInfo.SearchModeOnCmd.ReplaceGreenOnionsTags());
            Regex regexSearchOff          = new Regex(BotInfo.SearchModeOffCmd.ReplaceGreenOnionsTags());
            Regex regexTranslateToChinese = new Regex(BotInfo.TranslateToChineseCMD.ReplaceGreenOnionsTags());
            Regex regexTranslateTo        = new Regex(BotInfo.TranslateToCMD.ReplaceGreenOnionsTags());
            Regex regexHPicture           = new Regex(BotInfo.HPictureCmd.ReplaceGreenOnionsTags());
            Regex regexShabHPicture       = new Regex(BotInfo.ShabHPictureCmd.ReplaceGreenOnionsTags());
            Regex regexSelectPhone        = new Regex($"({BotInfo.BotName}查询手机号[::])");


            string firstMessage = Chain[1].ToString();

            #region -- 连续搜图 --
            if (regexSearchOn.IsMatch(firstMessage))
            {
                if (Cache.SearchingPictures.ContainsKey(sender.Id))
                {
                    Cache.SearchingPictures[sender.Id] = DateTime.Now.AddMinutes(1);
                    await session.SendGroupMessageAsync(sender.Group.Id, new[] { new PlainMessage(BotInfo.SearchModeAlreadyOnReply.ReplaceGreenOnionsTags()) }, quoteMessage.Id);
                }
                else
                {
                    Cache.SearchingPictures.Add(sender.Id, DateTime.Now.AddMinutes(1));
                    await session.SendGroupMessageAsync(sender.Group.Id, new[] { new PlainMessage(BotInfo.SearchModeOnReply.ReplaceGreenOnionsTags()) }, quoteMessage.Id);

                    Cache.CheckSearchPictureTime(callback =>
                    {
                        Cache.SearchingPictures.Remove(sender.Id);
                        session.SendGroupMessageAsync(sender.Group.Id, new[] { new PlainMessage(BotInfo.SearchModeTimeOutReply.ReplaceGreenOnionsTags()) }, quoteMessage.Id);
                    });
                }
            }
            else if (regexSearchOff.IsMatch(firstMessage))
            {
                if (Cache.SearchingPictures.ContainsKey(sender.Id))
                {
                    Cache.SearchingPictures.Remove(sender.Id);
                    await session.SendGroupMessageAsync(sender.Group.Id, new[] { new PlainMessage(BotInfo.SearchModeOffReply.ReplaceGreenOnionsTags()) }, quoteMessage.Id);
                }
                else
                {
                    await session.SendGroupMessageAsync(sender.Group.Id, new[] { new PlainMessage(BotInfo.SearchModeAlreadyOffReply.ReplaceGreenOnionsTags()) }, quoteMessage.Id);
                }
            }
            #endregion -- 连续搜图 --
            #region -- 翻译 --
            else if (regexTranslateToChinese.IsMatch(firstMessage))
            {
                foreach (Match match in regexTranslateToChinese.Matches(firstMessage))
                {
                    try
                    {
                        await session.SendGroupMessageAsync(sender.Group.Id, new[] { new PlainMessage(await GoogleTranslateHelper.TranslateToChinese(firstMessage.Substring(match.Value.Length))) }, quoteMessage.Id);
                    }
                    catch (Exception ex)
                    {
                        await session.SendGroupMessageAsync(sender.Group.Id, new PlainMessage("翻译失败," + ex.Message));
                    }
                    break;
                }
            }
            else if (regexTranslateTo.IsMatch(firstMessage))
            {
                foreach (Match match in regexTranslateTo.Matches(firstMessage))
                {
                    if (match.Groups.Count > 1)
                    {
                        try
                        {
                            await session.SendGroupMessageAsync(sender.Group.Id, new[] { new PlainMessage(await GoogleTranslateHelper.TranslateTo(firstMessage.Substring(match.Value.Length), match.Groups[1].Value)) }, quoteMessage.Id);
                        }
                        catch (Exception ex)
                        {
                            await session.SendGroupMessageAsync(sender.Group.Id, new PlainMessage("翻译失败," + ex.Message));
                        }
                    }
                    break;
                }
            }
            #endregion -- 翻译 --
            #region -- 色图 --
            #region -- Lolicon图库 --
            else if (BotInfo.EnabledLoliconDataBase && (regexHPicture.IsMatch(firstMessage) || BotInfo.HPictureUserCmd.Contains(firstMessage)))
            {
                #region -- 异步流色图(已弃用) --
                //await foreach (var item in HPictureHandlerAsync.SendHPictures(session, firstMessage, BotInfo.HPictureAllowR18 && (!BotInfo.HPictureR18WhiteOnly || BotInfo.HPictureWhiteGroup.Contains(sender.Group.Id))))
                //{
                //    int messageID = await session.SendGroupMessageAsync(sender.Group.Id, new[] { item }, quoteMessage.Id);

                //    if (item is PlainMessage)  //地址发出去后记录次数
                //    {
                //        if (BotInfo.HPictureLimitType == LimitType.Frequency)
                //        {
                //            Cache.RecordLimit(sender.Id);
                //        }
                //        Cache.RecordCD(sender.Id, sender.Group.Id);
                //    }
                //    else if (item is ImageMessage)
                //    {
                //        if (BotInfo.HPictureLimitType == LimitType.Count)
                //        {
                //            Cache.RecordLimit(sender.Id);
                //        }
                //        HPictureHandler.RevokeHPicture(session, messageID, BotInfo.HPictureWhiteGroup.Contains(sender.Group.Id) ? BotInfo.HPictureWhiteRevoke : BotInfo.HPictureRevoke);
                //    }
                //}
                #endregion -- 异步流色图(已弃用) --

                if (sender.Permission == GroupPermission.Member || !BotInfo.HPictureManageNoLimit)
                {
                    if (Cache.CheckGroupLimit(sender.Id, sender.Group.Id))
                    {
                        await session.SendGroupMessageAsync(sender.Group.Id, new[] { new PlainMessage(BotInfo.HPictureOutOfLimitReply) }, quoteMessage.Id);

                        return;
                    }
                    if (Cache.CheckGroupCD(sender.Id, sender.Group.Id))
                    {
                        await session.SendGroupMessageAsync(sender.Group.Id, new[] { new PlainMessage(BotInfo.HPictureCDUnreadyReply) }, quoteMessage.Id);

                        return;
                    }
                }

                HPictureHandler.SendHPictures(session, firstMessage, BotInfo.HPictureAllowR18 && (!BotInfo.HPictureR18WhiteOnly || BotInfo.HPictureWhiteGroup.Contains(sender.Group.Id)), BotInfo.HPictureEndCmd, stream => session.UploadPictureAsync(UploadTarget.Group, stream), msg => session.SendGroupMessageAsync(sender.Group.Id, msg, quoteMessage.Id), limitType =>
                {
                    if (limitType == LimitType.Frequency)
                    {
                        Cache.RecordGroupCD(sender.Id, sender.Group.Id);
                        if (BotInfo.HPictureLimitType == LimitType.Frequency)
                        {
                            Cache.RecordLimit(sender.Id);
                        }
                    }
                    else if (limitType == LimitType.Count && BotInfo.HPictureLimitType == LimitType.Count)
                    {
                        Cache.RecordLimit(sender.Id);
                    }
                }, BotInfo.HPictureWhiteGroup.Contains(sender.Group.Id) ? BotInfo.HPictureWhiteRevoke : BotInfo.HPictureRevoke);
            }
            #endregion  -- Lolicon图库 --
            #region -- Shab图库 --
            else if (BotInfo.EnabledShabDataBase && (regexShabHPicture.IsMatch(firstMessage) || BotInfo.HPictureUserCmd.Contains(firstMessage)))
            {
                if (sender.Permission == GroupPermission.Member || !BotInfo.HPictureManageNoLimit)
                {
                    if (Cache.CheckGroupLimit(sender.Id, sender.Group.Id))
                    {
                        await session.SendGroupMessageAsync(sender.Group.Id, new[] { new PlainMessage(BotInfo.HPictureOutOfLimitReply) }, quoteMessage.Id);

                        return;
                    }
                    if (Cache.CheckGroupCD(sender.Id, sender.Group.Id))
                    {
                        await session.SendGroupMessageAsync(sender.Group.Id, new[] { new PlainMessage(BotInfo.HPictureCDUnreadyReply) }, quoteMessage.Id);

                        return;
                    }
                }

                HPictureHandler.SendHPictures(session, firstMessage, BotInfo.HPictureAllowR18 && (!BotInfo.HPictureR18WhiteOnly || BotInfo.HPictureWhiteGroup.Contains(sender.Group.Id)), BotInfo.ShabHPictureEndCmd, stream => session.UploadPictureAsync(UploadTarget.Group, stream), msg => session.SendGroupMessageAsync(sender.Group.Id, msg, quoteMessage.Id), limitType =>
                {
                    if (limitType == LimitType.Frequency)
                    {
                        Cache.RecordGroupCD(sender.Id, sender.Group.Id);
                        if (BotInfo.HPictureLimitType == LimitType.Frequency)
                        {
                            Cache.RecordLimit(sender.Id);
                        }
                    }
                    else if (limitType == LimitType.Count && BotInfo.HPictureLimitType == LimitType.Count)
                    {
                        Cache.RecordLimit(sender.Id);
                    }
                }, BotInfo.HPictureWhiteGroup.Contains(sender.Group.Id) ? BotInfo.HPictureWhiteRevoke : BotInfo.HPictureRevoke);
            }
            #endregion -- Shab图库 --
            #endregion -- 色图 --
            else if (firstMessage == $"{BotInfo.BotName}帮助")
            {
                List <string> lstEnabledFeatures = new List <string>();
                if (BotInfo.SearchEnabled)
                {
                    lstEnabledFeatures.Add("搜图");
                }
                if (BotInfo.TranslateEnabled)
                {
                    lstEnabledFeatures.Add("翻译");
                }
                if (BotInfo.HPictureEnabled)
                {
                    lstEnabledFeatures.Add("GHS");
                }
                if (BotInfo.QQId == 3246934384)
                {
                    lstEnabledFeatures.Add("查手机号");
                }
                string strHelpResult = $"现在您可以让我{string.Join(",", lstEnabledFeatures)}。\r\n如果您觉得{BotInfo.BotName}好用,请到{BotInfo.BotName}的项目地址 https://github.com/Alex1911-Jiang/GreenOnions 给{BotInfo.BotName}一颗星星。";
                await session.SendGroupMessageAsync(sender.Group.Id, new[] { new PlainMessage(strHelpResult) }, quoteMessage.Id);
            }
            #region -- 查询手机号(夹带私货) --
            else if (regexSelectPhone.IsMatch(firstMessage))
            {
                if (BotInfo.QQId == 3246934384)
                {
                    foreach (Match match in regexSelectPhone.Matches(firstMessage))
                    {
                        if (match.Groups.Count > 1)
                        {
                            string qqNumber = firstMessage.Substring(match.Groups[1].Length);
                            long   lQQNumber;
                            if (long.TryParse(qqNumber, out lQQNumber))
                            {
                                try
                                {
                                    string result = AssemblyHelper.CallStaticMethod <string>("GreenOnions.QQPhone", "GreenOnions.QQPhone.QQAndPhone", "GetPhoneByQQ", lQQNumber);
                                    await session.SendGroupMessageAsync(sender.Group.Id, new[] { new PlainMessage(result) }, quoteMessage.Id);
                                }
                                catch (Exception ex)
                                {
                                    await session.SendGroupMessageAsync(sender.Group.Id, new[] { new PlainMessage("查询失败" + ex.Message) }, quoteMessage.Id);
                                }
                            }
                            else
                            {
                                await session.SendGroupMessageAsync(sender.Group.Id, new[] { new PlainMessage("请输入正确的QQ号码(不支持以邮箱查询)") }, quoteMessage.Id);
                            }
                        }
                    }
                }
            }
            #endregion -- 查询手机号(夹带私货) --
        }
Пример #15
0
        async Task <bool> IGroupMessage.GroupMessage(MiraiHttpSession session, IGroupMessageEventArgs e)
        {
            if (BotInfo.BannedGroup.Contains(e.Sender.Group.Id))
            {
                return(false);
            }
            if (BotInfo.BannedUser.Contains(e.Sender.Id))
            {
                return(false);
            }
            if (BotInfo.DebugMode)
            {
                if (BotInfo.DebugReplyAdminOnly)
                {
                    if (!BotInfo.AdminQQ.Contains(e.Sender.Id))
                    {
                        return(false);
                    }
                }
                if (BotInfo.OnlyReplyDebugGroup)
                {
                    if (!BotInfo.DebugGroups.Contains(e.Sender.Group.Id))
                    {
                        return(false);
                    }
                }
            }

            QuoteMessage quoteMessage = new QuoteMessage((e.Chain[0] as SourceMessage).Id, e.Sender.Group.Id, e.Sender.Id, e.Sender.Id, null);

            if (e.Chain.Length > 1)  //普通消息
            {
                switch (e.Chain[1].Type)
                {
                case "At":
                    if (e.Chain.Length > 2)
                    {
                        #region -- @搜图 --
                        AtMessage atMe = e.Chain[1] as AtMessage;
                        if (atMe.Target == BotInfo.QQId)      //@自己
                        {
                            for (int i = 2; i < e.Chain.Length; i++)
                            {
                                if (e.Chain[i].Type == "Image")
                                {
                                    ImageMessage imgMsg = e.Chain[i] as ImageMessage;
                                    await SearchPictureHandler.SearchPicture(imgMsg, picStream => session.UploadPictureAsync(UploadTarget.Group, picStream), msg => session.SendGroupMessageAsync(e.Sender.Group.Id, msg, quoteMessage.Id));
                                }
                            }
                        }
                        #endregion -- @搜图 --
                    }
                    break;

                case "Plain":
                    PlainMessageHandler.HandleGroupMesage(session, e.Chain, e.Sender, quoteMessage);
                    break;

                case "Image":
                    if (Cache.SearchingPictures.Keys.Contains(e.Sender.Id))
                    {
                        #region -- 连续搜图 --
                        for (int i = 1; i < e.Chain.Length; i++)
                        {
                            ImageMessage imgMsg = e.Chain[i] as ImageMessage;
                            await SearchPictureHandler.SuccessiveSearchPicture(session, imgMsg, e.Sender, picStream => session.UploadPictureAsync(UploadTarget.Group, picStream), msg => session.SendGroupMessageAsync(e.Sender.Group.Id, msg, quoteMessage.Id));
                        }
                        #endregion -- 连续搜图 --
                    }
                    break;
                }
            }
            return(false);
        }
Пример #16
0
        public async void DoHandleAsync(MiraiHttpSession session, IMessageBase[] chain, IBaseInfo info, bool isGroupMessage = true)
        {
            List <IMessageBase> result = null;
            IMessageBase        img    = null;

            sb.Clear();
            switch (chain.First(m => m.Type == "Plain").ToString())
            {
            case "单抽":
                logger.LogInformation($"{info.Name} 单抽");
                var card = await GachaSingle();

                var message = $"单抽结果: {stars[card.Item2.Rarity]} {data.Characters[card.Item2.CharacterId.ToString()].CharacterName[0]} - {card.Item2.Prefix[0]}";
                img = await session.UploadPictureAsync(UploadTarget.Group, await client.GetCardThumbPath(card.Item2.ResourceSetName, card.Item1));

                result = new List <IMessageBase>
                {
                    new PlainMessage(message),
                    img
                };
                logger.LogInformation(message);
                break;

            case "当期池子":
                GachaDetail gd        = GetRecentGachaDetail();
                DateTime    endTime   = DateTimeOffset.FromUnixTimeMilliseconds(long.Parse(gd.ClosedAt[0])).LocalDateTime;
                DateTime    startTime = DateTimeOffset.FromUnixTimeMilliseconds(long.Parse(gd.PublishedAt[0])).LocalDateTime;
                sb.AppendLine(gd.GachaName[0]);
                sb.AppendLine(gd.Information.NewMemberInfo[0]);
                sb.AppendLine($"{startTime} - {endTime}");
                img = await session.UploadPictureAsync(UploadTarget.Group, await client.GetGachaBannerImagePath(gd.BannerAssetBundleName));

                result = new List <IMessageBase>
                {
                    new PlainMessage(sb.ToString()),
                    img
                };
                logger.LogInformation(sb.ToString());
                break;

            case "十连":
                List <(string, Card)> cards = new List <(string, Card)>(11);
                for (int i = 0; i < 9; i++)
                {
                    cards.Add(await GachaSingle());
                }
                cards.Add(await GachaSingle(tenTimes: true));
                img = await session.UploadPictureAsync(UploadTarget.Group, await render.RenderGachaImageAsync(cards));

                sb.AppendLine("十连结果:");
                foreach (var item in cards)
                {
                    sb.AppendLine($"{stars[item.Item2.Rarity]} {data.Characters[item.Item2.CharacterId.ToString()].CharacterName[0]} - {item.Item2.Prefix[0]}");
                }
                result = new List <IMessageBase>
                {
                    new PlainMessage(sb.ToString()),
                    img
                };
                logger.LogInformation(sb.ToString());
                break;

            default:
                break;
            }
            if (isGroupMessage)
            {
                await session.SendGroupMessageAsync(((IGroupMemberInfo)info).Group.Id, result.ToArray());
            }
            else
            {
                await session.SendFriendMessageAsync(info.Id, result.ToArray());
            }
        }
Пример #17
0
        public static async IAsyncEnumerable <IMessageBase> SendHPictures(this MiraiHttpSession session, string command, bool isAllowR18)
        {
            string strHttpRequest;

            if (BotInfo.HPictureUserCmd != null && BotInfo.HPictureUserCmd.Contains(command))
            {
                strHttpRequest = $@"https://api.lolicon.app/setu/?{ (BotInfo.HPictureSize1200 ? "size1200=true" : "") }";
            }
            else
            {
                //分割请求接口所需的参数
                long   lImgCount = 1;
                string keyword   = "";
                string size1200  = "";
                string strR18    = "0";

                #region -- R18 --
                Regex rxR18 = new Regex(BotInfo.HPictureR18Cmd);
                foreach (Match mchR18 in rxR18.Matches(command))
                {
                    strR18  = "1";
                    command = command.Replace(mchR18.Value, "");  //无论是否允许R18都现将命令中的R18移除, 避免和数量混淆
                }
                if (!isAllowR18)
                {
                    strR18 = "0";             //如果不允许R18
                }
                #endregion -- R18 --

                #region -- 色图数量 -- ;
                string strCount = StringHelper.GetRegex(command, BotInfo.HPictureBeginCmd, BotInfo.HPictureCountCmd, BotInfo.HPictureUnitCmd);

                if (!long.TryParse(strCount, out lImgCount) && !string.IsNullOrEmpty(strCount))
                {
                    lImgCount = StringHelper.Chinese2Num(strCount);
                }

                if (string.IsNullOrEmpty(strCount))
                {
                    lImgCount = 1;
                }

                if (lImgCount <= 0)
                {
                    yield break;                  //犯贱呢要0张或以下色图
                }
                if (lImgCount > 10)
                {
                    lImgCount = 10;
                }

                #endregion -- 色图数量 --

                #region -- 关键词 --
                string strKeyword = StringHelper.GetRegex(command, BotInfo.HPictureUnitCmd, BotInfo.HPictureKeywordCmd, BotInfo.HPictureEndCmd);

                if (!string.IsNullOrWhiteSpace(strKeyword))
                {
                    if (strKeyword.EndsWith("的"))
                    {
                        strKeyword = strKeyword.Substring(0, strKeyword.Length - 1);
                    }
                    keyword = "&keyword=" + strKeyword;
                }
                #endregion -- 关键词 --

                if (BotInfo.HPictureSize1200)
                {
                    size1200 = "&size1200=true";
                }

                strHttpRequest = $@"https://api.lolicon.app/setu/?apikey={BotInfo.HPictureApiKey}&num={lImgCount}&r18={strR18}{keyword}{size1200}";
            }

            string strFail     = null;
            string resultValue = "";
            try
            {
                resultValue = await HttpHelper.GetHttpResponseStringAsync(strHttpRequest, out _);
            }
            catch (Exception ex)
            {
                strFail = ex.Message;
            }
            if (!string.IsNullOrEmpty(strFail))
            {
                yield return(new PlainMessage(BotInfo.SearchErrorReply + strFail));  //没找到对应词条的色图
            }


            JObject jo = (JObject)JsonConvert.DeserializeObject(resultValue);
            JToken  jt = jo["data"];

            if (jo["code"].ToString() == "1")
            {
                yield return(new PlainMessage(BotInfo.HPictureNoResultReply));  //没找到对应词条的色图

                yield break;
            }

            IEnumerable <LoliconHPictureItem> enumImg = jt.Select(i => new LoliconHPictureItem(i["p"].ToString(), i["pid"].ToString(), i["url"].ToString(), @$ "https://www.pixiv.net/artworks/{i[" pid "].ToString()}(p{i[" p "].ToString()}"));

            if (enumImg == null)
            {
                yield break;                   //一般不会出现这个情况, 但是防止它报错
            }
            StringBuilder sbAddress = new StringBuilder();
            foreach (var item in enumImg)
            {
                string strAddress = @"https://www.pixiv.net/artworks/" + item.ID + $" (p{item.P})";
                sbAddress.AppendLine(strAddress);
            }

            if (string.IsNullOrEmpty(sbAddress.ToString()))
            {
                yield break;                                       //一般不会出现这个情况, 但是防止它报错
            }
            yield return(new PlainMessage(sbAddress.ToString()));  //第一条地址

            string imagePath = Environment.CurrentDirectory + "\\Image\\";
            if (!Directory.Exists(imagePath))
            {
                Directory.CreateDirectory(imagePath);
            }

            foreach (var pair in enumImg)
            {
                string imgName = $"{imagePath} {pair.ID}  _{ pair.P }{(BotInfo.HPictureSize1200 ? "_1200" : "")} .png";
                if (File.Exists(imgName) && new FileInfo(imgName).Length > 0)
                {
                    yield return(await session.UploadPictureAsync(UploadTarget.Group, imgName));                                                           //存在本地缓存时优先使用缓存
                }
                Stream ms = HttpHelper.DownloadImageAsMemoryStream(pair.URL, imgName);

                if (ms == null)
                {
                    yield return(new PlainMessage(BotInfo.HPictureDownloadFailReply.ReplaceGreenOnionsTags(new KeyValuePair <string, string>("URL", pair.Address))));
                }

                yield return(await session.UploadPictureAsync(UploadTarget.Group, ms));  //上传图片
            }
        }
Пример #18
0
 public static async Task <ImageMessage> UploadImageAsync(UploadTarget target, string path)
 {                                                         // Mirai-CSharp 的根据路径上传忘了释放创建的流
     using FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
     return(await session.UploadPictureAsync(target, fs)); // 直接返回 Task 会导致流提前释放
 }